title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
What is the difference between implicit and explicit type conversion in C#? | The following is the difference between implicit and explicit type conversion −
These conversions are performed by C# in a type-safe manner.
To understand the concept, let us implicitly convert int to long.
int val1 = 11000;
int val2 = 35600;
long sum;
sum = val1 + val2;
Above, we have two integer variable and when we sum it in a long variable, it won’t show an error. Since the compiler does the implicit conversion on its own.
Let us print the values now.
using System;
using System.IO;
namespace Demo {
class Program {
static void Main(string[] args) {
int val1 =34567;
int val2 =56743;
long sum;
sum = val1 + val2;
Console.WriteLine("Sum= " + sum);
Console.ReadLine();
}
}
}
These conversions are done explicitly by users using the pre-defined functions.
Let us see an example to typecast double to int −
using System;
namespace Program {
class Demo {
static void Main(string[] args) {
double d = 1234.89;
int i;
// cast double to int.
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
} | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "The following is the difference between implicit and explicit type conversion −"
},
{
"code": null,
"e": 1203,
"s": 1142,
"text": "These conversions are performed by C# in a type-safe manner."
},
{
"code": null,
"e": 1269,
"s": 1203,
"text": "To understand the concept, let us implicitly convert int to long."
},
{
"code": null,
"e": 1335,
"s": 1269,
"text": "int val1 = 11000;\nint val2 = 35600;\nlong sum;\n\nsum = val1 + val2;"
},
{
"code": null,
"e": 1494,
"s": 1335,
"text": "Above, we have two integer variable and when we sum it in a long variable, it won’t show an error. Since the compiler does the implicit conversion on its own."
},
{
"code": null,
"e": 1523,
"s": 1494,
"text": "Let us print the values now."
},
{
"code": null,
"e": 1820,
"s": 1523,
"text": "using System;\nusing System.IO;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n int val1 =34567;\n int val2 =56743;\n long sum;\n\n sum = val1 + val2;\n\n Console.WriteLine(\"Sum= \" + sum);\n\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1900,
"s": 1820,
"text": "These conversions are done explicitly by users using the pre-defined functions."
},
{
"code": null,
"e": 1950,
"s": 1900,
"text": "Let us see an example to typecast double to int −"
},
{
"code": null,
"e": 2214,
"s": 1950,
"text": "using System;\n\nnamespace Program {\n class Demo {\n static void Main(string[] args) {\n double d = 1234.89;\n int i;\n\n // cast double to int.\n i = (int)d;\n Console.WriteLine(i);\n Console.ReadKey();\n }\n }\n}"
}
] |
How to Check if a Number is Odd or Even using Python? | Python's modulo (%) operator (also called remainder operator) is useful to determine if a number is odd or even. We obtain remainder of division of a number by 2. If it is 0 , it is even otherwise it is odd
no=int(input('enter number'))
if no%2==0:
print ('{} is even'.format(no))
else:
print ('{} is odd'.format(no))
The output
enter number25
25 is odd
enter number40
40 is even | [
{
"code": null,
"e": 1269,
"s": 1062,
"text": "Python's modulo (%) operator (also called remainder operator) is useful to determine if a number is odd or even. We obtain remainder of division of a number by 2. If it is 0 , it is even otherwise it is odd"
},
{
"code": null,
"e": 1388,
"s": 1269,
"text": "no=int(input('enter number'))\nif no%2==0:\n print ('{} is even'.format(no))\nelse:\n print ('{} is odd'.format(no))"
},
{
"code": null,
"e": 1399,
"s": 1388,
"text": "The output"
},
{
"code": null,
"e": 1451,
"s": 1399,
"text": "enter number25\n25 is odd\n\nenter number40\n40 is even"
}
] |
F# - Modules | As per MSDN library, an F# module is a grouping of F# code constructs, such as types, values, function values, and code in do bindings. It is implemented as a common language runtime (CLR) class that has only static members.
Depending upon the situation whether the whole file is included in the module, there are two types of module declarations −
Top-level module declaration
Local module declaration
In a top-level module declaration the whole file is included in the module. In this case, the first declaration in the file is the module declaration. You do not have to indent declarations in a top-level module.
In a local module declaration, only the declarations that are indented under that module declaration are part of the module.
Syntax for module declaration is as follows −
// Top-level module declaration.
module [accessibility-modifier] [qualified-namespace.]module-name
declarations
// Local module declaration.
module [accessibility-modifier] module-name =
declarations
Please note that the accessibility-modifier can be one of the following − public, private, internal. The default is public.
The following examples will demonstrate the concepts −
The module file Arithmetic.fs −
module Arithmetic
let add x y =
x + y
let sub x y =
x - y
let mult x y =
x * y
let div x y =
x / y
The program file main.fs −
// Fully qualify the function name.
open Arithmetic
let addRes = Arithmetic.add 25 9
let subRes = Arithmetic.sub 25 9
let multRes = Arithmetic.mult 25 9
let divRes = Arithmetic.div 25 9
printfn "%d" addRes
printfn "%d" subRes
printfn "%d" multRes
printfn "%d" divRes
When you compile and execute the program, it yields the following output −
34
16
225
2
110
90
1000
10
// Module1
module module1 =
// Indent all program elements within modules that are declared with an equal sign.
let value1 = 100
let module1Function x =
x + value1
// Module2
module module2 =
let value2 = 200
// Use a qualified name to access the function.
// from module1.
let module2Function x =
x + (module1.module1Function value2)
let result = module1.module1Function 25
printfn "%d" result
let result2 = module2.module2Function 25
printfn "%d" result2
When you compile and execute the program, it yields the following output −
125
325
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2386,
"s": 2161,
"text": "As per MSDN library, an F# module is a grouping of F# code constructs, such as types, values, function values, and code in do bindings. It is implemented as a common language runtime (CLR) class that has only static members."
},
{
"code": null,
"e": 2510,
"s": 2386,
"text": "Depending upon the situation whether the whole file is included in the module, there are two types of module declarations −"
},
{
"code": null,
"e": 2539,
"s": 2510,
"text": "Top-level module declaration"
},
{
"code": null,
"e": 2564,
"s": 2539,
"text": "Local module declaration"
},
{
"code": null,
"e": 2777,
"s": 2564,
"text": "In a top-level module declaration the whole file is included in the module. In this case, the first declaration in the file is the module declaration. You do not have to indent declarations in a top-level module."
},
{
"code": null,
"e": 2902,
"s": 2777,
"text": "In a local module declaration, only the declarations that are indented under that module declaration are part of the module."
},
{
"code": null,
"e": 2948,
"s": 2902,
"text": "Syntax for module declaration is as follows −"
},
{
"code": null,
"e": 3156,
"s": 2948,
"text": "// Top-level module declaration.\nmodule [accessibility-modifier] [qualified-namespace.]module-name\n declarations\n\n// Local module declaration.\nmodule [accessibility-modifier] module-name =\n declarations\n"
},
{
"code": null,
"e": 3280,
"s": 3156,
"text": "Please note that the accessibility-modifier can be one of the following − public, private, internal. The default is public."
},
{
"code": null,
"e": 3335,
"s": 3280,
"text": "The following examples will demonstrate the concepts −"
},
{
"code": null,
"e": 3367,
"s": 3335,
"text": "The module file Arithmetic.fs −"
},
{
"code": null,
"e": 3483,
"s": 3367,
"text": "module Arithmetic\nlet add x y =\n x + y\n\nlet sub x y =\n x - y\n\t\nlet mult x y =\n x * y\n\t\nlet div x y =\n x / y"
},
{
"code": null,
"e": 3510,
"s": 3483,
"text": "The program file main.fs −"
},
{
"code": null,
"e": 3778,
"s": 3510,
"text": "// Fully qualify the function name.\nopen Arithmetic\nlet addRes = Arithmetic.add 25 9\nlet subRes = Arithmetic.sub 25 9\nlet multRes = Arithmetic.mult 25 9\nlet divRes = Arithmetic.div 25 9\n\nprintfn \"%d\" addRes\nprintfn \"%d\" subRes\nprintfn \"%d\" multRes\nprintfn \"%d\" divRes"
},
{
"code": null,
"e": 3853,
"s": 3778,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 3881,
"s": 3853,
"text": "34\n16\n225\n2\n110\n90\n1000\n10\n"
},
{
"code": null,
"e": 4375,
"s": 3881,
"text": "// Module1\nmodule module1 =\n // Indent all program elements within modules that are declared with an equal sign.\n let value1 = 100\n let module1Function x =\n x + value1\n\n// Module2\nmodule module2 =\n let value2 = 200\n\n // Use a qualified name to access the function.\n // from module1.\n let module2Function x =\n x + (module1.module1Function value2)\n\nlet result = module1.module1Function 25\nprintfn \"%d\" result\n\nlet result2 = module2.module2Function 25\nprintfn \"%d\" result2"
},
{
"code": null,
"e": 4450,
"s": 4375,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 4459,
"s": 4450,
"text": "125\n325\n"
},
{
"code": null,
"e": 4466,
"s": 4459,
"text": " Print"
},
{
"code": null,
"e": 4477,
"s": 4466,
"text": " Add Notes"
}
] |
Instruction type RLC in 8085 Microprocessor | In 8085 Instruction set, there is one mnemonic RLC stands for “Rotate Left Accumulator”. It rotates the Accumulator contents to the left by 1-bit position. The following Fig. shows the operation explicitly.
In this fig. it has been depicted that the most significant bit of the Accumulator will come out and left rotate will create an empty space at the least significant bit place and this come out bit will be copied at the empty bit place and also on the Cy bit in the flag register. Thus, Cy flag gets a copy of the bit moved out from the MS bit position. Notice that Cy flag is not involved in the rotation, and it is only 8-bit rotation of Accumulator contents. Only Cy flag is affected by this instruction execution.
This instruction can be used in following different case studies.
To check whether the number is positive or negative. As the most significant of the Accumulator content holds the sign bit.
To check whether the number is positive or negative. As the most significant of the Accumulator content holds the sign bit.
To perform multiplication by 2, rotate the Accumulator to left. It works correctly for unsigned numbers, as long as the MS bit of Accumulator is a 0 before rotation. As we know that multiplication by 2n results n-bit left shift of the number.
To perform multiplication by 2, rotate the Accumulator to left. It works correctly for unsigned numbers, as long as the MS bit of Accumulator is a 0 before rotation. As we know that multiplication by 2n results n-bit left shift of the number.
Let us discuss some examples on this mnemonic usage.
35H ---> 0011 0101
0 0110 1010 ---> 6AH
(A)
(Cy)
Here the accumulation content has been doubled as we had 1-bit left shift and the MSB was 0.
95H ---> 1001 0101
1 0010 1011 ---> 2BH
(A)
(Cy)
Here, in this example, the Accumulator value has not been doubled, as most significant bit of theAccumulator was a 1 before the rotation.
The timing diagram against this instruction RLC execution is as follows −
Summary − So this instruction RLC requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram. | [
{
"code": null,
"e": 1269,
"s": 1062,
"text": "In 8085 Instruction set, there is one mnemonic RLC stands for “Rotate Left Accumulator”. It rotates the Accumulator contents to the left by 1-bit position. The following Fig. shows the operation explicitly."
},
{
"code": null,
"e": 1786,
"s": 1269,
"text": "In this fig. it has been depicted that the most significant bit of the Accumulator will come out and left rotate will create an empty space at the least significant bit place and this come out bit will be copied at the empty bit place and also on the Cy bit in the flag register. Thus, Cy flag gets a copy of the bit moved out from the MS bit position. Notice that Cy flag is not involved in the rotation, and it is only 8-bit rotation of Accumulator contents. Only Cy flag is affected by this instruction execution."
},
{
"code": null,
"e": 1852,
"s": 1786,
"text": "This instruction can be used in following different case studies."
},
{
"code": null,
"e": 1976,
"s": 1852,
"text": "To check whether the number is positive or negative. As the most significant of the Accumulator content holds the sign bit."
},
{
"code": null,
"e": 2100,
"s": 1976,
"text": "To check whether the number is positive or negative. As the most significant of the Accumulator content holds the sign bit."
},
{
"code": null,
"e": 2343,
"s": 2100,
"text": "To perform multiplication by 2, rotate the Accumulator to left. It works correctly for unsigned numbers, as long as the MS bit of Accumulator is a 0 before rotation. As we know that multiplication by 2n results n-bit left shift of the number."
},
{
"code": null,
"e": 2586,
"s": 2343,
"text": "To perform multiplication by 2, rotate the Accumulator to left. It works correctly for unsigned numbers, as long as the MS bit of Accumulator is a 0 before rotation. As we know that multiplication by 2n results n-bit left shift of the number."
},
{
"code": null,
"e": 2639,
"s": 2586,
"text": "Let us discuss some examples on this mnemonic usage."
},
{
"code": null,
"e": 2693,
"s": 2639,
"text": "35H ---> 0011 0101\n 0 0110 1010 ---> 6AH\n"
},
{
"code": null,
"e": 2697,
"s": 2693,
"text": "(A)"
},
{
"code": null,
"e": 2702,
"s": 2697,
"text": "(Cy)"
},
{
"code": null,
"e": 2795,
"s": 2702,
"text": "Here the accumulation content has been doubled as we had 1-bit left shift and the MSB was 0."
},
{
"code": null,
"e": 2839,
"s": 2795,
"text": "95H ---> 1001 0101\n1 0010 1011 ---> 2BH\n"
},
{
"code": null,
"e": 2843,
"s": 2839,
"text": "(A)"
},
{
"code": null,
"e": 2848,
"s": 2843,
"text": "(Cy)"
},
{
"code": null,
"e": 2987,
"s": 2848,
"text": "Here, in this example, the Accumulator value has not been doubled, as most significant bit of theAccumulator was a 1 before the rotation."
},
{
"code": null,
"e": 3061,
"s": 2987,
"text": "The timing diagram against this instruction RLC execution is as follows −"
},
{
"code": null,
"e": 3204,
"s": 3061,
"text": "Summary − So this instruction RLC requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram."
}
] |
PiExa- ->Raspberry Pi + Amazon Alexa: A step-by-step guide to build your own hands-free Alexa with Raspberry Pi | by Naveen Manwani | Towards Data Science | Motivation Monk: Read everyday something no one else is reading, Think everyday something no one else is thinking. It is bad for the mind to be always part of unanimity.
PiExa ?? I know you all must be wondering what this writer is upto, what is PiExa why would this term has anything to do with Amazon Alexa and Raspberry Pi. Well, my fellow readers all your explicit questions, doubts will be answered through the end of this article.
Objective:This article is a step by step comprehensive guide to build your own hands-free Amazon Alexa with Raspberry Pi 3, using Alexa Voice Service (AVS). Through this article I’ll demonstrates how to access and test AVS using their Java sample app (running on a Raspberry Pi), a Node.js server, and a third-party wake word engine. So, by the end of this article if you follow along with me you might have your own hands free Alexa up and talking to you.
Nomenclature:Purposefully I coined the term “PiExa” which clearly reflects the amalgamation of Raspberry Pi with Amazon Alexa.
Flashback:Few weeks back when I built my own open source natural language processing based voice assistant Mycroft for Raspberry Pi — Picroft , I started thinking is it possible to make my own Alexa using Raspberry Pi, with a cheap speaker and an Universal Serial Bus (USB) microphone in the same way as I built Picroft.
My curious mind and few google searches took me to the Alexa repository which allowed me to convert my simple thought into a reality.
So, without any further diddle-daddle let’s start the step by step execution of building your own Alexa with Raspberry Pi 3.
Hardware Requirement:
Raspberry Pi 3 (Recommended) or Pi 2 Model B (Supported).Micro-USB power cable for Raspberry Pi.Micro SD Card (Minimum 8 GB) — You need an operating system to get started. NOOBS (New Out of the Box Software) is an easy-to-use operating system install manager for Raspberry Pi. You can download and install it on your SD card ver easily (for instructions check here).USB 2.0 Mini Microphone — Raspberry Pi does not have a built-in microphone; to interact with Alexa you’ll need an external one to plug in.External Speaker with 3.5mm audio cable.A USB Keyboard & Mouse, and an external HDMI Monitor.Internet connection (Ethernet or WiFi)
Raspberry Pi 3 (Recommended) or Pi 2 Model B (Supported).
Micro-USB power cable for Raspberry Pi.
Micro SD Card (Minimum 8 GB) — You need an operating system to get started. NOOBS (New Out of the Box Software) is an easy-to-use operating system install manager for Raspberry Pi. You can download and install it on your SD card ver easily (for instructions check here).
USB 2.0 Mini Microphone — Raspberry Pi does not have a built-in microphone; to interact with Alexa you’ll need an external one to plug in.
External Speaker with 3.5mm audio cable.
A USB Keyboard & Mouse, and an external HDMI Monitor.
Internet connection (Ethernet or WiFi)
After you collect all the ingredients (hardware) for this project, start following the below mentioned steps.
Note: Unless you already have Raspbian Stretch or Jessie installed on your Pi, please follow the guide — Setting up the Raspberry Pi which will walk you through downloading and installing Raspbian and connecting the hardware (if you’re unfamiliar with Raspberry Pi, I highly recommend you to follow the guide above to get your Pi up and ready before moving further).
If you have installed Raspbian Stretch Lite on your Pi, you will need to install Java in order to get the Java Sample App up and running. As long as you have an internet connection, you can use the following commands to do so:
sudo apt-get updatesudo apt-get install oracle-java8-jdk
Unless you already have one, go ahead and create a free developer account at developer.amazon.com. Make sure you review the AVS Terms and Agreements here.
Follow the steps here to register your product and create a security profile.
Make note of the following parameters. You’ll need these in Step 5 below.
ProductID,
ClientID, and
ClientSecret
Important: Make sure your Allowed Origins and Allowed Return URLs are set under Security Profile > Web (see Create a device and security profile):
Allowed Origins: https://localhost:3000
Allowed Return URLs: https://localhost:3000/authresponse
Open terminal, and type the following:
cd Desktop# (Information: Currently the GitHub link is down due to some maintenance issue)git clone https://github.com/alexa/alexa-avs-sample-app.git
Before you run the install script, you need to update the script with the credentials that you got in step 3 — ProductID, ClientID, ClientSecret. Type the following in terminal:
cd ~/Desktop/alexa-avs-sample-appnano automated_install.sh
Paste the values for ProductID, ClientID, and ClientSecret that you got from Step 3 above.
The changes should look like this:
ProductID="RaspberryPi3"
ClientID="amzn.xxxxx.xxxxxxxxx"
ClientSecret="4e8cb14xxxxxxxxxxxxxxxxxxxxxxxxxxxxx6b4f9"
Type ctrl-X and then Y, and then press Enter to save the changes to the file.
You are now ready to run the install script. This will install all dependencies, including the two wake word engines from Sensory and KITT.AI.
Note: The install script will install all project files in the folder that the script is run from.
To run the script, open terminal and navigate to the folder where the project was cloned. Then run the following command:
cd ~/Desktop/alexa-avs-sample-app. automated_install.sh
You’ll be prompted to answer a few simple questions, answer these questions and complete all necessary prerequisites before continuing.
When the wizard starts, it takes about 25-30 minutes to complete all the process so meanwhile go grab a Tea or a coffee to pass your time.
Now that installation is complete, you’ll need to run three commands in 3 separate terminal windows:
Terminal Window 1: to run the web service for authorizationTerminal Window 2: to run the sample app to communicate with AVSTerminal Window 3: to run the wake word engine which allows you to start an interaction using the phrase “Alexa”.
Terminal Window 1: to run the web service for authorization
Terminal Window 2: to run the sample app to communicate with AVS
Terminal Window 3: to run the wake word engine which allows you to start an interaction using the phrase “Alexa”.
Note: These commands must be run in order.
Open a new terminal window and type the following commands to bring up the web service which is used to authorize your sample app with AVS:
cd ~/Desktop/alexa-avs-sample-app/samplescd companionService && npm start
The server is now running on port 3000 and you are ready to start the client.
See API Overview > Authorization to learn more about authorization.
Let’s walk through the next few steps relevant to Window 2.
When you run the client, a window should pop up with a message that says -
When you run the client, a window should pop up with a message that says -
Please register your device by visiting the following URL in a web browser and following the instructions: https://localhost:3000/provision/d340f629bd685deeff28a917. Would you like to open the URL automatically in your default browser?
Click on “Yes” to open the URL in your default browser.
2. If you’re running Raspbian with Pixel desktop (and with Chromium browser), you may get a warning from the browser. You can get around it by clicking on Advanced -> Proceed to localhost(unsafe).
3. You’ll be taken to a Login with Amazon web page. Enter your Amazon credentials.
4. You’ll be taken to a Dev Authorization page, confirming that you’d like your device to access the Security Profile created earlier.
Click Okay.
5. You will now be redirected to a URL beginning with https://localhost:3000/authresponsefollowed by a query string. The body of the web page will say device tokens ready.
6. Return to the Java application and click the OK button. The client is now ready to accept Alexa requests.
Note: Skip this step to run the same app without a wake word engine.
This project supports two third-party wake word engines: Sensory’s TrulyHandsFree and KITT.AI’s Snowboy. The -e parameter is used to select the agent and supports two values for {{engine}}: kitt_ai and sensory.
Open a new terminal window and use the following commands to bring up a wake word engine from Sensory or KITT.AI. The wake word engine will allow you to initiate interactions using the phrase “Alexa”.
To use the Sensory wake word engine, type -
cd ~/Desktop/alexa-avs-sample-app/samplescd wakeWordAgent/src && ./wakeWordAgent -e sensory
or, type this to use KITT.AI’s wake word engine -
cd ~/Desktop/alexa-avs-sample-app/samplescd wakeWordAgent/src && ./wakeWordAgent -e kitt_ai
Now you have a working hands-free AVS prototype!
Use the following resources to learn more about available wake word engines:
Sensory
KITT.AI
You can now talk to Alexa by simply using the wake word “Alexa”. Try the following -
Say “Alexa”, then wait for the beep. Now say “what’s the time?”
If you prefer, you can also click on the “Listen” button, instead of using the wake word. Click once on the “Listen” button, after releasing the click, wait for the audio cue before beginning to speak. It may take a second or two before you hear the audio cue.
Follow these instructions to log out of the AVS java sample app:
Quit the AVS java sample app (CTRL + C).Open /samples/javaclient/config.json and clear your sessionId. It should look like this:
Quit the AVS java sample app (CTRL + C).
Open /samples/javaclient/config.json and clear your sessionId. It should look like this:
"sessionId": ""
3. Delete the refresh_tokens file in samples/companionService.
The next time you log in you will be prompted to authenticate.
Below are the videos with and without wake word “Alexa” so just sit back and enjoy:
Part 1: without wake word “Alexa”
https://www.youtube.com/watch?v=T1uyG9YNWbk (video 1)
Part 2: with wake word “Alexa”
https://www.youtube.com/watch?v=a2XvL1L65tM (video 2)
Since, now you all know each and every step from top to bottom to build your own hands-free Amazon Alexa with Raspberry pi 3, using Alexa Voice Service (AVS). Therefore I want to encourage all my fellow readers, Deep Learning / Machine Learning Practitioners, hobbyists and Enthusiast to come up with your own hands-free Amazon Alexa with Raspberry pi 3 and publish a LinkedIn or a twitter post on it (**but don’t forget to tag me :) . I’ll be eagerly waiting for your posts.
REFERENCES:
To know more about Alexa Voice Service check here.To learn more about Voice Assistant check here.The repository I used to bring this project into existence can be found here.(Information: Currently the GitHub link is down due to some maintenance issue)
To know more about Alexa Voice Service check here.
To learn more about Voice Assistant check here.
The repository I used to bring this project into existence can be found here.(Information: Currently the GitHub link is down due to some maintenance issue)
Thank you for your attention
You using your time to read my work means the world to me. I fully mean that.
If you liked this story, go crazy with the applaud( 👏) button! It will help other people find my work.
Also, follow me on Medium , Linkedin , Twitter if you want to! I would love that. | [
{
"code": null,
"e": 342,
"s": 172,
"text": "Motivation Monk: Read everyday something no one else is reading, Think everyday something no one else is thinking. It is bad for the mind to be always part of unanimity."
},
{
"code": null,
"e": 609,
"s": 342,
"text": "PiExa ?? I know you all must be wondering what this writer is upto, what is PiExa why would this term has anything to do with Amazon Alexa and Raspberry Pi. Well, my fellow readers all your explicit questions, doubts will be answered through the end of this article."
},
{
"code": null,
"e": 1066,
"s": 609,
"text": "Objective:This article is a step by step comprehensive guide to build your own hands-free Amazon Alexa with Raspberry Pi 3, using Alexa Voice Service (AVS). Through this article I’ll demonstrates how to access and test AVS using their Java sample app (running on a Raspberry Pi), a Node.js server, and a third-party wake word engine. So, by the end of this article if you follow along with me you might have your own hands free Alexa up and talking to you."
},
{
"code": null,
"e": 1193,
"s": 1066,
"text": "Nomenclature:Purposefully I coined the term “PiExa” which clearly reflects the amalgamation of Raspberry Pi with Amazon Alexa."
},
{
"code": null,
"e": 1514,
"s": 1193,
"text": "Flashback:Few weeks back when I built my own open source natural language processing based voice assistant Mycroft for Raspberry Pi — Picroft , I started thinking is it possible to make my own Alexa using Raspberry Pi, with a cheap speaker and an Universal Serial Bus (USB) microphone in the same way as I built Picroft."
},
{
"code": null,
"e": 1648,
"s": 1514,
"text": "My curious mind and few google searches took me to the Alexa repository which allowed me to convert my simple thought into a reality."
},
{
"code": null,
"e": 1773,
"s": 1648,
"text": "So, without any further diddle-daddle let’s start the step by step execution of building your own Alexa with Raspberry Pi 3."
},
{
"code": null,
"e": 1795,
"s": 1773,
"text": "Hardware Requirement:"
},
{
"code": null,
"e": 2431,
"s": 1795,
"text": "Raspberry Pi 3 (Recommended) or Pi 2 Model B (Supported).Micro-USB power cable for Raspberry Pi.Micro SD Card (Minimum 8 GB) — You need an operating system to get started. NOOBS (New Out of the Box Software) is an easy-to-use operating system install manager for Raspberry Pi. You can download and install it on your SD card ver easily (for instructions check here).USB 2.0 Mini Microphone — Raspberry Pi does not have a built-in microphone; to interact with Alexa you’ll need an external one to plug in.External Speaker with 3.5mm audio cable.A USB Keyboard & Mouse, and an external HDMI Monitor.Internet connection (Ethernet or WiFi)"
},
{
"code": null,
"e": 2489,
"s": 2431,
"text": "Raspberry Pi 3 (Recommended) or Pi 2 Model B (Supported)."
},
{
"code": null,
"e": 2529,
"s": 2489,
"text": "Micro-USB power cable for Raspberry Pi."
},
{
"code": null,
"e": 2800,
"s": 2529,
"text": "Micro SD Card (Minimum 8 GB) — You need an operating system to get started. NOOBS (New Out of the Box Software) is an easy-to-use operating system install manager for Raspberry Pi. You can download and install it on your SD card ver easily (for instructions check here)."
},
{
"code": null,
"e": 2939,
"s": 2800,
"text": "USB 2.0 Mini Microphone — Raspberry Pi does not have a built-in microphone; to interact with Alexa you’ll need an external one to plug in."
},
{
"code": null,
"e": 2980,
"s": 2939,
"text": "External Speaker with 3.5mm audio cable."
},
{
"code": null,
"e": 3034,
"s": 2980,
"text": "A USB Keyboard & Mouse, and an external HDMI Monitor."
},
{
"code": null,
"e": 3073,
"s": 3034,
"text": "Internet connection (Ethernet or WiFi)"
},
{
"code": null,
"e": 3183,
"s": 3073,
"text": "After you collect all the ingredients (hardware) for this project, start following the below mentioned steps."
},
{
"code": null,
"e": 3550,
"s": 3183,
"text": "Note: Unless you already have Raspbian Stretch or Jessie installed on your Pi, please follow the guide — Setting up the Raspberry Pi which will walk you through downloading and installing Raspbian and connecting the hardware (if you’re unfamiliar with Raspberry Pi, I highly recommend you to follow the guide above to get your Pi up and ready before moving further)."
},
{
"code": null,
"e": 3777,
"s": 3550,
"text": "If you have installed Raspbian Stretch Lite on your Pi, you will need to install Java in order to get the Java Sample App up and running. As long as you have an internet connection, you can use the following commands to do so:"
},
{
"code": null,
"e": 3834,
"s": 3777,
"text": "sudo apt-get updatesudo apt-get install oracle-java8-jdk"
},
{
"code": null,
"e": 3989,
"s": 3834,
"text": "Unless you already have one, go ahead and create a free developer account at developer.amazon.com. Make sure you review the AVS Terms and Agreements here."
},
{
"code": null,
"e": 4067,
"s": 3989,
"text": "Follow the steps here to register your product and create a security profile."
},
{
"code": null,
"e": 4141,
"s": 4067,
"text": "Make note of the following parameters. You’ll need these in Step 5 below."
},
{
"code": null,
"e": 4152,
"s": 4141,
"text": "ProductID,"
},
{
"code": null,
"e": 4166,
"s": 4152,
"text": "ClientID, and"
},
{
"code": null,
"e": 4179,
"s": 4166,
"text": "ClientSecret"
},
{
"code": null,
"e": 4326,
"s": 4179,
"text": "Important: Make sure your Allowed Origins and Allowed Return URLs are set under Security Profile > Web (see Create a device and security profile):"
},
{
"code": null,
"e": 4366,
"s": 4326,
"text": "Allowed Origins: https://localhost:3000"
},
{
"code": null,
"e": 4423,
"s": 4366,
"text": "Allowed Return URLs: https://localhost:3000/authresponse"
},
{
"code": null,
"e": 4462,
"s": 4423,
"text": "Open terminal, and type the following:"
},
{
"code": null,
"e": 4612,
"s": 4462,
"text": "cd Desktop# (Information: Currently the GitHub link is down due to some maintenance issue)git clone https://github.com/alexa/alexa-avs-sample-app.git"
},
{
"code": null,
"e": 4790,
"s": 4612,
"text": "Before you run the install script, you need to update the script with the credentials that you got in step 3 — ProductID, ClientID, ClientSecret. Type the following in terminal:"
},
{
"code": null,
"e": 4849,
"s": 4790,
"text": "cd ~/Desktop/alexa-avs-sample-appnano automated_install.sh"
},
{
"code": null,
"e": 4940,
"s": 4849,
"text": "Paste the values for ProductID, ClientID, and ClientSecret that you got from Step 3 above."
},
{
"code": null,
"e": 4975,
"s": 4940,
"text": "The changes should look like this:"
},
{
"code": null,
"e": 5000,
"s": 4975,
"text": "ProductID=\"RaspberryPi3\""
},
{
"code": null,
"e": 5032,
"s": 5000,
"text": "ClientID=\"amzn.xxxxx.xxxxxxxxx\""
},
{
"code": null,
"e": 5089,
"s": 5032,
"text": "ClientSecret=\"4e8cb14xxxxxxxxxxxxxxxxxxxxxxxxxxxxx6b4f9\""
},
{
"code": null,
"e": 5167,
"s": 5089,
"text": "Type ctrl-X and then Y, and then press Enter to save the changes to the file."
},
{
"code": null,
"e": 5310,
"s": 5167,
"text": "You are now ready to run the install script. This will install all dependencies, including the two wake word engines from Sensory and KITT.AI."
},
{
"code": null,
"e": 5409,
"s": 5310,
"text": "Note: The install script will install all project files in the folder that the script is run from."
},
{
"code": null,
"e": 5531,
"s": 5409,
"text": "To run the script, open terminal and navigate to the folder where the project was cloned. Then run the following command:"
},
{
"code": null,
"e": 5587,
"s": 5531,
"text": "cd ~/Desktop/alexa-avs-sample-app. automated_install.sh"
},
{
"code": null,
"e": 5723,
"s": 5587,
"text": "You’ll be prompted to answer a few simple questions, answer these questions and complete all necessary prerequisites before continuing."
},
{
"code": null,
"e": 5862,
"s": 5723,
"text": "When the wizard starts, it takes about 25-30 minutes to complete all the process so meanwhile go grab a Tea or a coffee to pass your time."
},
{
"code": null,
"e": 5963,
"s": 5862,
"text": "Now that installation is complete, you’ll need to run three commands in 3 separate terminal windows:"
},
{
"code": null,
"e": 6200,
"s": 5963,
"text": "Terminal Window 1: to run the web service for authorizationTerminal Window 2: to run the sample app to communicate with AVSTerminal Window 3: to run the wake word engine which allows you to start an interaction using the phrase “Alexa”."
},
{
"code": null,
"e": 6260,
"s": 6200,
"text": "Terminal Window 1: to run the web service for authorization"
},
{
"code": null,
"e": 6325,
"s": 6260,
"text": "Terminal Window 2: to run the sample app to communicate with AVS"
},
{
"code": null,
"e": 6439,
"s": 6325,
"text": "Terminal Window 3: to run the wake word engine which allows you to start an interaction using the phrase “Alexa”."
},
{
"code": null,
"e": 6482,
"s": 6439,
"text": "Note: These commands must be run in order."
},
{
"code": null,
"e": 6622,
"s": 6482,
"text": "Open a new terminal window and type the following commands to bring up the web service which is used to authorize your sample app with AVS:"
},
{
"code": null,
"e": 6696,
"s": 6622,
"text": "cd ~/Desktop/alexa-avs-sample-app/samplescd companionService && npm start"
},
{
"code": null,
"e": 6774,
"s": 6696,
"text": "The server is now running on port 3000 and you are ready to start the client."
},
{
"code": null,
"e": 6842,
"s": 6774,
"text": "See API Overview > Authorization to learn more about authorization."
},
{
"code": null,
"e": 6902,
"s": 6842,
"text": "Let’s walk through the next few steps relevant to Window 2."
},
{
"code": null,
"e": 6977,
"s": 6902,
"text": "When you run the client, a window should pop up with a message that says -"
},
{
"code": null,
"e": 7052,
"s": 6977,
"text": "When you run the client, a window should pop up with a message that says -"
},
{
"code": null,
"e": 7288,
"s": 7052,
"text": "Please register your device by visiting the following URL in a web browser and following the instructions: https://localhost:3000/provision/d340f629bd685deeff28a917. Would you like to open the URL automatically in your default browser?"
},
{
"code": null,
"e": 7344,
"s": 7288,
"text": "Click on “Yes” to open the URL in your default browser."
},
{
"code": null,
"e": 7541,
"s": 7344,
"text": "2. If you’re running Raspbian with Pixel desktop (and with Chromium browser), you may get a warning from the browser. You can get around it by clicking on Advanced -> Proceed to localhost(unsafe)."
},
{
"code": null,
"e": 7624,
"s": 7541,
"text": "3. You’ll be taken to a Login with Amazon web page. Enter your Amazon credentials."
},
{
"code": null,
"e": 7759,
"s": 7624,
"text": "4. You’ll be taken to a Dev Authorization page, confirming that you’d like your device to access the Security Profile created earlier."
},
{
"code": null,
"e": 7771,
"s": 7759,
"text": "Click Okay."
},
{
"code": null,
"e": 7943,
"s": 7771,
"text": "5. You will now be redirected to a URL beginning with https://localhost:3000/authresponsefollowed by a query string. The body of the web page will say device tokens ready."
},
{
"code": null,
"e": 8052,
"s": 7943,
"text": "6. Return to the Java application and click the OK button. The client is now ready to accept Alexa requests."
},
{
"code": null,
"e": 8121,
"s": 8052,
"text": "Note: Skip this step to run the same app without a wake word engine."
},
{
"code": null,
"e": 8332,
"s": 8121,
"text": "This project supports two third-party wake word engines: Sensory’s TrulyHandsFree and KITT.AI’s Snowboy. The -e parameter is used to select the agent and supports two values for {{engine}}: kitt_ai and sensory."
},
{
"code": null,
"e": 8533,
"s": 8332,
"text": "Open a new terminal window and use the following commands to bring up a wake word engine from Sensory or KITT.AI. The wake word engine will allow you to initiate interactions using the phrase “Alexa”."
},
{
"code": null,
"e": 8577,
"s": 8533,
"text": "To use the Sensory wake word engine, type -"
},
{
"code": null,
"e": 8669,
"s": 8577,
"text": "cd ~/Desktop/alexa-avs-sample-app/samplescd wakeWordAgent/src && ./wakeWordAgent -e sensory"
},
{
"code": null,
"e": 8719,
"s": 8669,
"text": "or, type this to use KITT.AI’s wake word engine -"
},
{
"code": null,
"e": 8811,
"s": 8719,
"text": "cd ~/Desktop/alexa-avs-sample-app/samplescd wakeWordAgent/src && ./wakeWordAgent -e kitt_ai"
},
{
"code": null,
"e": 8860,
"s": 8811,
"text": "Now you have a working hands-free AVS prototype!"
},
{
"code": null,
"e": 8937,
"s": 8860,
"text": "Use the following resources to learn more about available wake word engines:"
},
{
"code": null,
"e": 8945,
"s": 8937,
"text": "Sensory"
},
{
"code": null,
"e": 8953,
"s": 8945,
"text": "KITT.AI"
},
{
"code": null,
"e": 9038,
"s": 8953,
"text": "You can now talk to Alexa by simply using the wake word “Alexa”. Try the following -"
},
{
"code": null,
"e": 9102,
"s": 9038,
"text": "Say “Alexa”, then wait for the beep. Now say “what’s the time?”"
},
{
"code": null,
"e": 9363,
"s": 9102,
"text": "If you prefer, you can also click on the “Listen” button, instead of using the wake word. Click once on the “Listen” button, after releasing the click, wait for the audio cue before beginning to speak. It may take a second or two before you hear the audio cue."
},
{
"code": null,
"e": 9428,
"s": 9363,
"text": "Follow these instructions to log out of the AVS java sample app:"
},
{
"code": null,
"e": 9557,
"s": 9428,
"text": "Quit the AVS java sample app (CTRL + C).Open /samples/javaclient/config.json and clear your sessionId. It should look like this:"
},
{
"code": null,
"e": 9598,
"s": 9557,
"text": "Quit the AVS java sample app (CTRL + C)."
},
{
"code": null,
"e": 9687,
"s": 9598,
"text": "Open /samples/javaclient/config.json and clear your sessionId. It should look like this:"
},
{
"code": null,
"e": 9703,
"s": 9687,
"text": "\"sessionId\": \"\""
},
{
"code": null,
"e": 9766,
"s": 9703,
"text": "3. Delete the refresh_tokens file in samples/companionService."
},
{
"code": null,
"e": 9829,
"s": 9766,
"text": "The next time you log in you will be prompted to authenticate."
},
{
"code": null,
"e": 9913,
"s": 9829,
"text": "Below are the videos with and without wake word “Alexa” so just sit back and enjoy:"
},
{
"code": null,
"e": 9947,
"s": 9913,
"text": "Part 1: without wake word “Alexa”"
},
{
"code": null,
"e": 10001,
"s": 9947,
"text": "https://www.youtube.com/watch?v=T1uyG9YNWbk (video 1)"
},
{
"code": null,
"e": 10032,
"s": 10001,
"text": "Part 2: with wake word “Alexa”"
},
{
"code": null,
"e": 10086,
"s": 10032,
"text": "https://www.youtube.com/watch?v=a2XvL1L65tM (video 2)"
},
{
"code": null,
"e": 10562,
"s": 10086,
"text": "Since, now you all know each and every step from top to bottom to build your own hands-free Amazon Alexa with Raspberry pi 3, using Alexa Voice Service (AVS). Therefore I want to encourage all my fellow readers, Deep Learning / Machine Learning Practitioners, hobbyists and Enthusiast to come up with your own hands-free Amazon Alexa with Raspberry pi 3 and publish a LinkedIn or a twitter post on it (**but don’t forget to tag me :) . I’ll be eagerly waiting for your posts."
},
{
"code": null,
"e": 10574,
"s": 10562,
"text": "REFERENCES:"
},
{
"code": null,
"e": 10827,
"s": 10574,
"text": "To know more about Alexa Voice Service check here.To learn more about Voice Assistant check here.The repository I used to bring this project into existence can be found here.(Information: Currently the GitHub link is down due to some maintenance issue)"
},
{
"code": null,
"e": 10878,
"s": 10827,
"text": "To know more about Alexa Voice Service check here."
},
{
"code": null,
"e": 10926,
"s": 10878,
"text": "To learn more about Voice Assistant check here."
},
{
"code": null,
"e": 11082,
"s": 10926,
"text": "The repository I used to bring this project into existence can be found here.(Information: Currently the GitHub link is down due to some maintenance issue)"
},
{
"code": null,
"e": 11111,
"s": 11082,
"text": "Thank you for your attention"
},
{
"code": null,
"e": 11189,
"s": 11111,
"text": "You using your time to read my work means the world to me. I fully mean that."
},
{
"code": null,
"e": 11292,
"s": 11189,
"text": "If you liked this story, go crazy with the applaud( 👏) button! It will help other people find my work."
}
] |
Turn Excel Into a Beautiful Web Application Using Streamlit | by Manfye Goh | Towards Data Science | Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science projects [1]
One of the main features of Streamlit is it provides you a Jupyter Notebook-like environment where your code is updated live as you save your script. This helps a lot, especially for the initial app development stage.
The problem that exists with excel and data science projects is the lack of an easy way to present the results (a.k.a production deployment). For an excel file to be presented, you will either need to link it with visualization tools such as Power BI, Tableau, or Powerpoint.
Whereas for a data science project to be implemented, you will need to implement a backend server such as Django, Flask, and a front-end UI such as React and Vue.js.
These complications make data sharing with excels and data science projects extremely BORING and TEDIOUS.
Luckily with the help of Streamlit, we can easily create an interactive web application out of Excel spreadsheets and deploy data science projects easily. 🙌
At the end of this article, you will be able to create an interactive excel dashboard web application which enable user to filter the data, visualize graph and access easily using URL. Alternatively, you can visit the web application here and the repository here
We will be using the World Happiness Report 2021 from Kaggle as our dataset for this article, feel free to download it below:
2021
World Happiness Reportwww.kaggle.com
Install Streamlit via pip install
pip install streamlit
Verify your install via type in Streamlit CLI in command prompt
streamlit hello
That’s it! In the next few seconds, the sample app will open in a new tab in your default browse.
To make your own apps, create a blank python file app.py, and run it with streamlit CLI. Then, click the localhost URL to enter your first streamlit web apps!
streamlit run app.py
By default Streamlit already have 2 places to put your code and widget in, which are the sidebar and content. You can add elements and widget in the content area simply using:
import streamlit as stst.[element_name]
You can add elements and widget in the sidebar simply using:
import streamlit as stst.sidebar.[element_name]
You can put any element in the sidebar as per content area, the only elements that aren’t supported are st.echo and st.spinner at the time of writing.
Loading data from Excel and CSV can be done using pandas:
import pandas as pd#For Excel Filedf = pd.read_excel("world-happiness-report-2021.xlxs")#For CSV Filedf = pd.read_csv("world-happiness-report-2021.csv")
Display widget is pretty straightforward, you want a Text, just write it as:
st.title(“World Happiness Index 2021:”)
If you want it to appear in the sidebar, just write the code as:
st.sidebar.title(“World Happiness Index 2021:”)
If you want an image, just write:
st.image(“https://images.pexels.com/photos/573259/pexels-photo-573259.jpeg?cs=srgb&dl=pexels-matheus-bertelli-573259.jpg&fm=jpg", caption=’World Happiness Dataset’)
If you want to display a data frame, just write:
st.write(filtered_df)
That's how simple it works in Streamlit!
Streamlit has a “State-like” component function where the interaction of the user with the widget will change the state of the variable. And then, the new value of the variable will be used to rerender the components of the whole project.
In this project, we will create a select box widget that can be used to filter the country and a slider to filter the ladder score in the sidebar as an example.
#Country Select Filtercountry_list = ["All","Western Europe", "South Asia", "Southeast Asia", "East Asia", "North America and ANZ","Middle East and North Africa", "Latin America and Caribbean","Central and Eastern Europe","Commonwealth of Independent States","Sub-Saharan Africa"]select = st.sidebar.selectbox('Filter the region here:', country_list, key='1')if select =="All":filtered_df = dfelse:filtered_df = df[df['Regional indicator']==select]#Ladder Score Sliderscore = st.sidebar.slider('Select min Ladder Score', min_value=5, max_value=10, value = 10) # Getting the input.df = df[df['Ladder score'] <= score] # Filtering the dataframe.
You will get the widget that can filter the data frame as below:
Streamlit supports several different charting libraries such as Matplotlib, Seaborns, Ploty, Altair charts. It also provides a few native charts such as line chart and area chart which can be called by a line of code, for example:
#Line Chartst.line_chart(data=None, width=0, height=0, use_container_width=True)#Area Chartst.area_chart(data=None, width=0, height=0, use_container_width=True)
However, in this tutorial, we will be using Plotly express for the scatter chart and bar chart. Then, we use seaborn for the heatmap chart as below:
import plotly.express as pximport seaborn as sns#Scatter Chartfig = px.scatter(filtered_df,x="Logged GDP per capita",y="Healthy life expectancy",size="Ladder score",color="Regional indicator",hover_name="Country name",size_max=10)st.write(fig)#Bar Chart, you can write in this way toost.write(px.bar(filtered_df, y='Ladder score', x='Country name'))#Seaborn Heatmap#correlate datacorr = filtered_df.corr()#using matplotlib to define the sizeplt.figure(figsize=(8, 8))#creating the heatmap with seabornfig1 = plt.figure()ax = sns.heatmap(corr,vmin=-1, vmax=1, center=0,cmap=sns.diverging_palette(20, 220, n=200),square=True)ax.set_xticklabels(ax.get_xticklabels(),rotation=45,horizontalalignment='right');st.pyplot(fig1)
Note: Notice that for Seaborn it is an axes component, so you cannot directly use st.write to render the chart, whereas you must use st.pyplot to render the components.
Streamlit has another unique feature called streamlit sharing, where they help you to host your streamlit app on their website. Simply prepare a requirements.txt file in the same folder as app.py will do the magic.
The requirements.txt file tells the system what python package the app will be using, in our case, it will be:
streamlit==0.83.0numpy==1.18.5pandas==1.2.4matplotlib==3.4.2plotly-express==0.4.1seaborn==0.11.1
Click deploy and you will get the URL of your web apps. 🎉🎉
*At the time of writing, Streamlit Sharing required an invitation from Streamlit. It took around 2 working days for them to approve my account
Alternative to the recommended feature, you can host your apps at Heroku or any other custom host like digital ocean, AWS, or google cloud. I will show the method of hosting in Heroku as it is a Free solution.
To host in Heroku, you will need the exact same requirement.txt as above in the exact same location. Besides that, you will need 2 additional files which are:
a) Procfile:
web: sh setup.sh && streamlit run app.py
b) setup.sh:
mkdir -p ~/.streamlit/echo "\[general]\n\email = \"<youremail>\"\n\" > ~/.streamlit/credentials.tomlecho "\[server]\n\headless = true\n\port = $PORT\n\enableCORS = false\n\\n\" > ~/.streamlit/config.toml
Copy exactly the same setup as above and you will have the folder structure as below:
I had hosted the same project both in Heroku and Streamlit Sharing, you can check on it and compare the speed and functionality yourself. In my opinion, both ways have their pro and cons, Streamlit Sharing offers free hosting and Hosting in Heroku have a limitation of 2 Free hosting per account.
In this article, we had covered the basics of Streamlit which include installation, the basic concept of scripting in Streamlit, dashboard design, chart visualization, and deployment of the web app.
Streamlit is a new paradigm of data presentation tools that have enormous potential. It solves the last-mile problem in data science which is to deliver the project easily to end-users regardless of layman or peer data scientist. It took me less than 1 hour to understand the Streamlit concept and fall in ❤️ with it, I hope my sharing can spark your interest in Streamlit too!
Lastly, Thank you very much for reading my article.
Here’s a video to introduce what is Streamlit in under 100 seconds:
If you are interested in excel automation, this article is a must-read:
towardsdatascience.com
My other articles included: | [
{
"code": null,
"e": 332,
"s": 172,
"text": "Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science projects [1]"
},
{
"code": null,
"e": 550,
"s": 332,
"text": "One of the main features of Streamlit is it provides you a Jupyter Notebook-like environment where your code is updated live as you save your script. This helps a lot, especially for the initial app development stage."
},
{
"code": null,
"e": 826,
"s": 550,
"text": "The problem that exists with excel and data science projects is the lack of an easy way to present the results (a.k.a production deployment). For an excel file to be presented, you will either need to link it with visualization tools such as Power BI, Tableau, or Powerpoint."
},
{
"code": null,
"e": 992,
"s": 826,
"text": "Whereas for a data science project to be implemented, you will need to implement a backend server such as Django, Flask, and a front-end UI such as React and Vue.js."
},
{
"code": null,
"e": 1098,
"s": 992,
"text": "These complications make data sharing with excels and data science projects extremely BORING and TEDIOUS."
},
{
"code": null,
"e": 1255,
"s": 1098,
"text": "Luckily with the help of Streamlit, we can easily create an interactive web application out of Excel spreadsheets and deploy data science projects easily. 🙌"
},
{
"code": null,
"e": 1518,
"s": 1255,
"text": "At the end of this article, you will be able to create an interactive excel dashboard web application which enable user to filter the data, visualize graph and access easily using URL. Alternatively, you can visit the web application here and the repository here"
},
{
"code": null,
"e": 1644,
"s": 1518,
"text": "We will be using the World Happiness Report 2021 from Kaggle as our dataset for this article, feel free to download it below:"
},
{
"code": null,
"e": 1686,
"s": 1644,
"text": "2021\nWorld Happiness Reportwww.kaggle.com"
},
{
"code": null,
"e": 1720,
"s": 1686,
"text": "Install Streamlit via pip install"
},
{
"code": null,
"e": 1742,
"s": 1720,
"text": "pip install streamlit"
},
{
"code": null,
"e": 1806,
"s": 1742,
"text": "Verify your install via type in Streamlit CLI in command prompt"
},
{
"code": null,
"e": 1822,
"s": 1806,
"text": "streamlit hello"
},
{
"code": null,
"e": 1920,
"s": 1822,
"text": "That’s it! In the next few seconds, the sample app will open in a new tab in your default browse."
},
{
"code": null,
"e": 2079,
"s": 1920,
"text": "To make your own apps, create a blank python file app.py, and run it with streamlit CLI. Then, click the localhost URL to enter your first streamlit web apps!"
},
{
"code": null,
"e": 2100,
"s": 2079,
"text": "streamlit run app.py"
},
{
"code": null,
"e": 2276,
"s": 2100,
"text": "By default Streamlit already have 2 places to put your code and widget in, which are the sidebar and content. You can add elements and widget in the content area simply using:"
},
{
"code": null,
"e": 2316,
"s": 2276,
"text": "import streamlit as stst.[element_name]"
},
{
"code": null,
"e": 2377,
"s": 2316,
"text": "You can add elements and widget in the sidebar simply using:"
},
{
"code": null,
"e": 2425,
"s": 2377,
"text": "import streamlit as stst.sidebar.[element_name]"
},
{
"code": null,
"e": 2576,
"s": 2425,
"text": "You can put any element in the sidebar as per content area, the only elements that aren’t supported are st.echo and st.spinner at the time of writing."
},
{
"code": null,
"e": 2634,
"s": 2576,
"text": "Loading data from Excel and CSV can be done using pandas:"
},
{
"code": null,
"e": 2787,
"s": 2634,
"text": "import pandas as pd#For Excel Filedf = pd.read_excel(\"world-happiness-report-2021.xlxs\")#For CSV Filedf = pd.read_csv(\"world-happiness-report-2021.csv\")"
},
{
"code": null,
"e": 2864,
"s": 2787,
"text": "Display widget is pretty straightforward, you want a Text, just write it as:"
},
{
"code": null,
"e": 2904,
"s": 2864,
"text": "st.title(“World Happiness Index 2021:”)"
},
{
"code": null,
"e": 2969,
"s": 2904,
"text": "If you want it to appear in the sidebar, just write the code as:"
},
{
"code": null,
"e": 3017,
"s": 2969,
"text": "st.sidebar.title(“World Happiness Index 2021:”)"
},
{
"code": null,
"e": 3051,
"s": 3017,
"text": "If you want an image, just write:"
},
{
"code": null,
"e": 3216,
"s": 3051,
"text": "st.image(“https://images.pexels.com/photos/573259/pexels-photo-573259.jpeg?cs=srgb&dl=pexels-matheus-bertelli-573259.jpg&fm=jpg\", caption=’World Happiness Dataset’)"
},
{
"code": null,
"e": 3265,
"s": 3216,
"text": "If you want to display a data frame, just write:"
},
{
"code": null,
"e": 3287,
"s": 3265,
"text": "st.write(filtered_df)"
},
{
"code": null,
"e": 3328,
"s": 3287,
"text": "That's how simple it works in Streamlit!"
},
{
"code": null,
"e": 3567,
"s": 3328,
"text": "Streamlit has a “State-like” component function where the interaction of the user with the widget will change the state of the variable. And then, the new value of the variable will be used to rerender the components of the whole project."
},
{
"code": null,
"e": 3728,
"s": 3567,
"text": "In this project, we will create a select box widget that can be used to filter the country and a slider to filter the ladder score in the sidebar as an example."
},
{
"code": null,
"e": 4372,
"s": 3728,
"text": "#Country Select Filtercountry_list = [\"All\",\"Western Europe\", \"South Asia\", \"Southeast Asia\", \"East Asia\", \"North America and ANZ\",\"Middle East and North Africa\", \"Latin America and Caribbean\",\"Central and Eastern Europe\",\"Commonwealth of Independent States\",\"Sub-Saharan Africa\"]select = st.sidebar.selectbox('Filter the region here:', country_list, key='1')if select ==\"All\":filtered_df = dfelse:filtered_df = df[df['Regional indicator']==select]#Ladder Score Sliderscore = st.sidebar.slider('Select min Ladder Score', min_value=5, max_value=10, value = 10) # Getting the input.df = df[df['Ladder score'] <= score] # Filtering the dataframe."
},
{
"code": null,
"e": 4437,
"s": 4372,
"text": "You will get the widget that can filter the data frame as below:"
},
{
"code": null,
"e": 4668,
"s": 4437,
"text": "Streamlit supports several different charting libraries such as Matplotlib, Seaborns, Ploty, Altair charts. It also provides a few native charts such as line chart and area chart which can be called by a line of code, for example:"
},
{
"code": null,
"e": 4829,
"s": 4668,
"text": "#Line Chartst.line_chart(data=None, width=0, height=0, use_container_width=True)#Area Chartst.area_chart(data=None, width=0, height=0, use_container_width=True)"
},
{
"code": null,
"e": 4978,
"s": 4829,
"text": "However, in this tutorial, we will be using Plotly express for the scatter chart and bar chart. Then, we use seaborn for the heatmap chart as below:"
},
{
"code": null,
"e": 5698,
"s": 4978,
"text": "import plotly.express as pximport seaborn as sns#Scatter Chartfig = px.scatter(filtered_df,x=\"Logged GDP per capita\",y=\"Healthy life expectancy\",size=\"Ladder score\",color=\"Regional indicator\",hover_name=\"Country name\",size_max=10)st.write(fig)#Bar Chart, you can write in this way toost.write(px.bar(filtered_df, y='Ladder score', x='Country name'))#Seaborn Heatmap#correlate datacorr = filtered_df.corr()#using matplotlib to define the sizeplt.figure(figsize=(8, 8))#creating the heatmap with seabornfig1 = plt.figure()ax = sns.heatmap(corr,vmin=-1, vmax=1, center=0,cmap=sns.diverging_palette(20, 220, n=200),square=True)ax.set_xticklabels(ax.get_xticklabels(),rotation=45,horizontalalignment='right');st.pyplot(fig1)"
},
{
"code": null,
"e": 5867,
"s": 5698,
"text": "Note: Notice that for Seaborn it is an axes component, so you cannot directly use st.write to render the chart, whereas you must use st.pyplot to render the components."
},
{
"code": null,
"e": 6082,
"s": 5867,
"text": "Streamlit has another unique feature called streamlit sharing, where they help you to host your streamlit app on their website. Simply prepare a requirements.txt file in the same folder as app.py will do the magic."
},
{
"code": null,
"e": 6193,
"s": 6082,
"text": "The requirements.txt file tells the system what python package the app will be using, in our case, it will be:"
},
{
"code": null,
"e": 6290,
"s": 6193,
"text": "streamlit==0.83.0numpy==1.18.5pandas==1.2.4matplotlib==3.4.2plotly-express==0.4.1seaborn==0.11.1"
},
{
"code": null,
"e": 6349,
"s": 6290,
"text": "Click deploy and you will get the URL of your web apps. 🎉🎉"
},
{
"code": null,
"e": 6492,
"s": 6349,
"text": "*At the time of writing, Streamlit Sharing required an invitation from Streamlit. It took around 2 working days for them to approve my account"
},
{
"code": null,
"e": 6702,
"s": 6492,
"text": "Alternative to the recommended feature, you can host your apps at Heroku or any other custom host like digital ocean, AWS, or google cloud. I will show the method of hosting in Heroku as it is a Free solution."
},
{
"code": null,
"e": 6861,
"s": 6702,
"text": "To host in Heroku, you will need the exact same requirement.txt as above in the exact same location. Besides that, you will need 2 additional files which are:"
},
{
"code": null,
"e": 6874,
"s": 6861,
"text": "a) Procfile:"
},
{
"code": null,
"e": 6915,
"s": 6874,
"text": "web: sh setup.sh && streamlit run app.py"
},
{
"code": null,
"e": 6928,
"s": 6915,
"text": "b) setup.sh:"
},
{
"code": null,
"e": 7132,
"s": 6928,
"text": "mkdir -p ~/.streamlit/echo \"\\[general]\\n\\email = \\\"<youremail>\\\"\\n\\\" > ~/.streamlit/credentials.tomlecho \"\\[server]\\n\\headless = true\\n\\port = $PORT\\n\\enableCORS = false\\n\\\\n\\\" > ~/.streamlit/config.toml"
},
{
"code": null,
"e": 7218,
"s": 7132,
"text": "Copy exactly the same setup as above and you will have the folder structure as below:"
},
{
"code": null,
"e": 7515,
"s": 7218,
"text": "I had hosted the same project both in Heroku and Streamlit Sharing, you can check on it and compare the speed and functionality yourself. In my opinion, both ways have their pro and cons, Streamlit Sharing offers free hosting and Hosting in Heroku have a limitation of 2 Free hosting per account."
},
{
"code": null,
"e": 7714,
"s": 7515,
"text": "In this article, we had covered the basics of Streamlit which include installation, the basic concept of scripting in Streamlit, dashboard design, chart visualization, and deployment of the web app."
},
{
"code": null,
"e": 8092,
"s": 7714,
"text": "Streamlit is a new paradigm of data presentation tools that have enormous potential. It solves the last-mile problem in data science which is to deliver the project easily to end-users regardless of layman or peer data scientist. It took me less than 1 hour to understand the Streamlit concept and fall in ❤️ with it, I hope my sharing can spark your interest in Streamlit too!"
},
{
"code": null,
"e": 8144,
"s": 8092,
"text": "Lastly, Thank you very much for reading my article."
},
{
"code": null,
"e": 8212,
"s": 8144,
"text": "Here’s a video to introduce what is Streamlit in under 100 seconds:"
},
{
"code": null,
"e": 8284,
"s": 8212,
"text": "If you are interested in excel automation, this article is a must-read:"
},
{
"code": null,
"e": 8307,
"s": 8284,
"text": "towardsdatascience.com"
}
] |
How to define and query json columns in PostgreSQL? | The ability to define JSON columns in PostgreSQL makes it very powerful and helps PostgreSQL users experience the best of both worlds: SQL and NoSQL.
Creating JSON columns is quite straightforward. You just have to create/ define it like any other column and use the data type as JSON.
Let us create a new table in PostgreSQL, called json_test −
CREATE TABLE json_test(
serial_no SERIAL PRIMARY KEY,
name VARCHAR,
metadata JSON
);
Now, let us populate it with some data −
INSERT INTO json_test(name, metadata)
VALUES ('Yash','{"marks_scored":{"science":50,"maths":65}}'),
('Isha', '{"marks_scored":{"science":70,"maths":45}}');
As you can see, the JSON values are added within single quotes, just like we add VARCHAR/TEXT values.
Now, if you query the table (SELECT * from json_test), you will see the following output −
However, we can do better than this. Suppose I want to know the marks scored in science by both Yash and Isha. All I need to do is use the -> operator. See the example below −
SELECT name, metadata->'marks_scored'->'science' as science_marks
from json_test
The output will be
Please note that over here, the output column science_marks is of type JSON and not INTEGER. This is because → operator always returns a json. Apart from the → operator, the->> operator is also commonly used. The difference between the two is that while → returns a json, ->> returns a text.
Thus,
metadata→'marks_scored'→'science' will return a JSON, even though we have integers for science_marks
metadata→'marks_scored'→'science' will return a JSON, even though we have integers for science_marks
metadata→'marks_scored'->>' science' will return text
metadata→'marks_scored'->>' science' will return text
metadata->>'marks_scored'→'science' will give an error. Because the 'marks_scored' output is no longer JSON, and thus, the → operator doesn’t work on it.
metadata->>'marks_scored'→'science' will give an error. Because the 'marks_scored' output is no longer JSON, and thus, the → operator doesn’t work on it.
If you explicitly want the science_marks in integer format, you first get the result in text format, and then cast it to an integer, as shown below −
SELECT name, CAST(metadata->'marks_scored'->>'science' as integer)
as science_marks from json_test
Note that you cannot cast JSON to an integer. You need to use the ->> operator at the last step to get text output, and only then can you cast the text to an integer.
Just like you can use the JSON columns in the select part of the query, you can also use them in the WHERE part of the query. If we wish to find out the students who have scored > 60 marks in Science, your query would look like
SELECT name from json_test
WHERE CAST(metadata->'marks_scored'->>'science' as integer) > 60
And the output would be | [
{
"code": null,
"e": 1212,
"s": 1062,
"text": "The ability to define JSON columns in PostgreSQL makes it very powerful and helps PostgreSQL users experience the best of both worlds: SQL and NoSQL."
},
{
"code": null,
"e": 1348,
"s": 1212,
"text": "Creating JSON columns is quite straightforward. You just have to create/ define it like any other column and use the data type as JSON."
},
{
"code": null,
"e": 1408,
"s": 1348,
"text": "Let us create a new table in PostgreSQL, called json_test −"
},
{
"code": null,
"e": 1502,
"s": 1408,
"text": "CREATE TABLE json_test(\n serial_no SERIAL PRIMARY KEY,\n name VARCHAR,\n metadata JSON\n);"
},
{
"code": null,
"e": 1543,
"s": 1502,
"text": "Now, let us populate it with some data −"
},
{
"code": null,
"e": 1699,
"s": 1543,
"text": "INSERT INTO json_test(name, metadata)\nVALUES ('Yash','{\"marks_scored\":{\"science\":50,\"maths\":65}}'),\n('Isha', '{\"marks_scored\":{\"science\":70,\"maths\":45}}');"
},
{
"code": null,
"e": 1801,
"s": 1699,
"text": "As you can see, the JSON values are added within single quotes, just like we add VARCHAR/TEXT values."
},
{
"code": null,
"e": 1892,
"s": 1801,
"text": "Now, if you query the table (SELECT * from json_test), you will see the following output −"
},
{
"code": null,
"e": 2068,
"s": 1892,
"text": "However, we can do better than this. Suppose I want to know the marks scored in science by both Yash and Isha. All I need to do is use the -> operator. See the example below −"
},
{
"code": null,
"e": 2149,
"s": 2068,
"text": "SELECT name, metadata->'marks_scored'->'science' as science_marks\nfrom json_test"
},
{
"code": null,
"e": 2168,
"s": 2149,
"text": "The output will be"
},
{
"code": null,
"e": 2460,
"s": 2168,
"text": "Please note that over here, the output column science_marks is of type JSON and not INTEGER. This is because → operator always returns a json. Apart from the → operator, the->> operator is also commonly used. The difference between the two is that while → returns a json, ->> returns a text."
},
{
"code": null,
"e": 2466,
"s": 2460,
"text": "Thus,"
},
{
"code": null,
"e": 2567,
"s": 2466,
"text": "metadata→'marks_scored'→'science' will return a JSON, even though we have integers for science_marks"
},
{
"code": null,
"e": 2668,
"s": 2567,
"text": "metadata→'marks_scored'→'science' will return a JSON, even though we have integers for science_marks"
},
{
"code": null,
"e": 2722,
"s": 2668,
"text": "metadata→'marks_scored'->>' science' will return text"
},
{
"code": null,
"e": 2776,
"s": 2722,
"text": "metadata→'marks_scored'->>' science' will return text"
},
{
"code": null,
"e": 2930,
"s": 2776,
"text": "metadata->>'marks_scored'→'science' will give an error. Because the 'marks_scored' output is no longer JSON, and thus, the → operator doesn’t work on it."
},
{
"code": null,
"e": 3084,
"s": 2930,
"text": "metadata->>'marks_scored'→'science' will give an error. Because the 'marks_scored' output is no longer JSON, and thus, the → operator doesn’t work on it."
},
{
"code": null,
"e": 3234,
"s": 3084,
"text": "If you explicitly want the science_marks in integer format, you first get the result in text format, and then cast it to an integer, as shown below −"
},
{
"code": null,
"e": 3333,
"s": 3234,
"text": "SELECT name, CAST(metadata->'marks_scored'->>'science' as integer)\nas science_marks from json_test"
},
{
"code": null,
"e": 3500,
"s": 3333,
"text": "Note that you cannot cast JSON to an integer. You need to use the ->> operator at the last step to get text output, and only then can you cast the text to an integer."
},
{
"code": null,
"e": 3728,
"s": 3500,
"text": "Just like you can use the JSON columns in the select part of the query, you can also use them in the WHERE part of the query. If we wish to find out the students who have scored > 60 marks in Science, your query would look like"
},
{
"code": null,
"e": 3820,
"s": 3728,
"text": "SELECT name from json_test\nWHERE CAST(metadata->'marks_scored'->>'science' as integer) > 60"
},
{
"code": null,
"e": 3844,
"s": 3820,
"text": "And the output would be"
}
] |
What is the use of $ErrorView in PowerShell? | $Errorview variable determines the display format of the error message in PowerShell. Before PowerShell 7 there were mainly two views,
Normal View (Default view)
Normal View (Default view)
Category View
Category View
With PowerShell version 7, one new additional error view category is included and now there are 3 $ErrorView categories for version 7.
Concise View (Default)
Concise View (Default)
Normal View
Normal View
Category View
Category View
We will understand each view one by one.
It is the default view before PowerShell version 7 and it produces the detailed multiline errors and bit noisy. It includes the exception name, category, line number of the error, etc.
$ErrorView = 'NormalView'
Get-ChildItem C:\NoDirectory
Get-ChildItem : Cannot find path 'C:\NoDirectory' because it does not exist.
At line:1 char:1
+ Get-ChildItem C:\NoDirectory
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\NoDirectory:String) [Get-ChildItem],
ItemNotFoundException
+ FullyQualifiedErrorId :
PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Single liner and structured view, designed for the production environment. Its format is as below.
{Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}
$ErrorView = 'CategoryView'
Get-ChildItem C:\NoDirectory
ObjectNotFound: (C:\NoDirectory:String) [Get-ChildItem], ItemNotFoundException
The default view in PowerShell version 7. It provides a concise error message. If the error is from thecommand line it’s a single line error message.
$ErrorView = 'ConciseView'
Get-ChildItem C:\NoDirectory
Get-ChildItem: Cannot find path 'C:\NoDirectory' because it does not exist.
If the error is from the script then it is a multiline error message that contains the error message and the line number for the error.
$ErrorView = 'ConciseView'
PS C:\> C:\Temp\TestPS1.ps1
Error message in Concise view
Get-ChildItem: C:\Temp\TestPS1.ps1:2
Line |
2 | Get-ChildItem c:\nonDirectory
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot find path 'C:\nonDirectory' because it does not exist. | [
{
"code": null,
"e": 1197,
"s": 1062,
"text": "$Errorview variable determines the display format of the error message in PowerShell. Before PowerShell 7 there were mainly two views,"
},
{
"code": null,
"e": 1224,
"s": 1197,
"text": "Normal View (Default view)"
},
{
"code": null,
"e": 1251,
"s": 1224,
"text": "Normal View (Default view)"
},
{
"code": null,
"e": 1265,
"s": 1251,
"text": "Category View"
},
{
"code": null,
"e": 1279,
"s": 1265,
"text": "Category View"
},
{
"code": null,
"e": 1414,
"s": 1279,
"text": "With PowerShell version 7, one new additional error view category is included and now there are 3 $ErrorView categories for version 7."
},
{
"code": null,
"e": 1437,
"s": 1414,
"text": "Concise View (Default)"
},
{
"code": null,
"e": 1460,
"s": 1437,
"text": "Concise View (Default)"
},
{
"code": null,
"e": 1472,
"s": 1460,
"text": "Normal View"
},
{
"code": null,
"e": 1484,
"s": 1472,
"text": "Normal View"
},
{
"code": null,
"e": 1498,
"s": 1484,
"text": "Category View"
},
{
"code": null,
"e": 1512,
"s": 1498,
"text": "Category View"
},
{
"code": null,
"e": 1553,
"s": 1512,
"text": "We will understand each view one by one."
},
{
"code": null,
"e": 1738,
"s": 1553,
"text": "It is the default view before PowerShell version 7 and it produces the detailed multiline errors and bit noisy. It includes the exception name, category, line number of the error, etc."
},
{
"code": null,
"e": 1793,
"s": 1738,
"text": "$ErrorView = 'NormalView'\nGet-ChildItem C:\\NoDirectory"
},
{
"code": null,
"e": 2134,
"s": 1793,
"text": "Get-ChildItem : Cannot find path 'C:\\NoDirectory' because it does not exist.\nAt line:1 char:1\n+ Get-ChildItem C:\\NoDirectory\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : ObjectNotFound: (C:\\NoDirectory:String) [Get-ChildItem],\nItemNotFoundException\n+ FullyQualifiedErrorId :\nPathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand"
},
{
"code": null,
"e": 2233,
"s": 2134,
"text": "Single liner and structured view, designed for the production environment. Its format is as below."
},
{
"code": null,
"e": 2296,
"s": 2233,
"text": "{Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}"
},
{
"code": null,
"e": 2353,
"s": 2296,
"text": "$ErrorView = 'CategoryView'\nGet-ChildItem C:\\NoDirectory"
},
{
"code": null,
"e": 2432,
"s": 2353,
"text": "ObjectNotFound: (C:\\NoDirectory:String) [Get-ChildItem], ItemNotFoundException"
},
{
"code": null,
"e": 2582,
"s": 2432,
"text": "The default view in PowerShell version 7. It provides a concise error message. If the error is from thecommand line it’s a single line error message."
},
{
"code": null,
"e": 2638,
"s": 2582,
"text": "$ErrorView = 'ConciseView'\nGet-ChildItem C:\\NoDirectory"
},
{
"code": null,
"e": 2714,
"s": 2638,
"text": "Get-ChildItem: Cannot find path 'C:\\NoDirectory' because it does not exist."
},
{
"code": null,
"e": 2850,
"s": 2714,
"text": "If the error is from the script then it is a multiline error message that contains the error message and the line number for the error."
},
{
"code": null,
"e": 2905,
"s": 2850,
"text": "$ErrorView = 'ConciseView'\nPS C:\\> C:\\Temp\\TestPS1.ps1"
},
{
"code": null,
"e": 3109,
"s": 2905,
"text": "Error message in Concise view\nGet-ChildItem: C:\\Temp\\TestPS1.ps1:2\nLine |\n2 | Get-ChildItem c:\\nonDirectory\n| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n| Cannot find path 'C:\\nonDirectory' because it does not exist."
}
] |
How to Work with Nested Data in BigQuery | by Christianlauer | Towards Data Science | Cloud data lakes and warehouses are on the rise — one example is Google’s BigQuery. BigQuery is the most powerful with denormalized data. Instead of working with traditional schemas like star or snowflake schemas, you should denormalize your data and use nested and recurring columns. These columns can preserve relationships without degrading performance as relational or normalized schemas do [1].
BigQuery supports loading and querying nested and recurring data from source formats that support object-based schemas for example JSON.
The address column contains an array of values. The different addresses in the array are the recurring data. The different fields within each address are the nested data.
For an example walkthrough with BigQuery I used the open dataset planet_features in the geo_openstreetmap dataset. Here, the data is stored in a nested format, so let’s take a look:
SELECT * FROM `bigquery-public-data.geo_openstreetmap.planet_features` LIMIT 1000
This is the result in the following output:
The result looks good at first sight. Unlike classical relational databases, I can use arrays and save additional columns. Furthermore, the whole thing works with a super performance. Now, I would like to find a certain supermarket in Germany — should be done with an easy where clause — right? Almost. Here, you need the magic of Unnest,
SELECT * FROM `bigquery-PUBLIC- data.geo_openstreetmap.planet_features` WHERE 'Netto' IN ( SELECT value FROM unnest(all_tags)) AND ( 'addr:country', 'DE') IN ( SELECT (KEY, value) FROM unnest(all_tags)) AND ( 'addr:city', 'Hamburg') IN ( SELECT (KEY, value) FROM unnest (all_tags));
which results in the desired output:
With the function of unnest you will also be able to flatten the data and so the output of the query:
SELECT osm_id,tagsFROM bigquery-public-data.geo_openstreetmap.planet_features,UNNEST(all_tags) as tags limit 100
This is probably almost the most important you have to know when working with nested data in BigQuery and want to query some data. But what if you want to use the data for further ETL processes, store the data in relational databases or need the key-value-pairs as attributes for your classifier? Here, you want the data not to flatten — because this will result in duplicate rows — here you want the key-value-pairs in the array as new columns:
SELECT ( SELECT osm_id) osmid, ( SELECT value FROM Unnest(all_tags) WHERE KEY = "Address") AS address, ( SELECT value FROM Unnest(all_tags) WHERE KEY = "name") AS NAME, ( SELECT value FROM Unnest(all_tags) WHERE KEY = "opening_hours") AS opening_hours, ( SELECT value FROM Unnest(all_tags) WHERE KEY = "organic") AS organic, ( SELECT geometry) AS geometry, FROM bigquery-PUBLIC-data.geo_openstreetmap.planet_features WHERE ( 'Edeka' IN ( SELECT value FROM unnest(all_tags)) OR 'Rewe' IN ( SELECT value FROM unnest(all_tags)) OR 'Netto' IN ( SELECT value FROM unnest(all_tags))) AND ( 'addr:country', 'DE') IN ( SELECT (KEY, value) FROM unnest(all_tags)) - AND ( 'addr:city', 'Hamburg') IN ( SELECT (KEY, value) FROM unnest(all_tags));
After I came into contact with nested data for the first time — I have to admit that I didn’t know what to do with it at first and probably had the same facial expression as Mark Wahlberg in the movie The Happening.
But I realized in the new world, such data formats are normal and the way to the world of unstructured data. New systems offer extremely high computing power and fast results through column-based databases. With the above examples, you should be able to query and process most of your nested data use cases very well.
[1] Google, Specifying nested and repeated columns | [
{
"code": null,
"e": 572,
"s": 172,
"text": "Cloud data lakes and warehouses are on the rise — one example is Google’s BigQuery. BigQuery is the most powerful with denormalized data. Instead of working with traditional schemas like star or snowflake schemas, you should denormalize your data and use nested and recurring columns. These columns can preserve relationships without degrading performance as relational or normalized schemas do [1]."
},
{
"code": null,
"e": 709,
"s": 572,
"text": "BigQuery supports loading and querying nested and recurring data from source formats that support object-based schemas for example JSON."
},
{
"code": null,
"e": 880,
"s": 709,
"text": "The address column contains an array of values. The different addresses in the array are the recurring data. The different fields within each address are the nested data."
},
{
"code": null,
"e": 1062,
"s": 880,
"text": "For an example walkthrough with BigQuery I used the open dataset planet_features in the geo_openstreetmap dataset. Here, the data is stored in a nested format, so let’s take a look:"
},
{
"code": null,
"e": 1144,
"s": 1062,
"text": "SELECT * FROM `bigquery-public-data.geo_openstreetmap.planet_features` LIMIT 1000"
},
{
"code": null,
"e": 1188,
"s": 1144,
"text": "This is the result in the following output:"
},
{
"code": null,
"e": 1527,
"s": 1188,
"text": "The result looks good at first sight. Unlike classical relational databases, I can use arrays and save additional columns. Furthermore, the whole thing works with a super performance. Now, I would like to find a certain supermarket in Germany — should be done with an easy where clause — right? Almost. Here, you need the magic of Unnest,"
},
{
"code": null,
"e": 1960,
"s": 1527,
"text": "SELECT * FROM `bigquery-PUBLIC- data.geo_openstreetmap.planet_features` WHERE 'Netto' IN ( SELECT value FROM unnest(all_tags)) AND ( 'addr:country', 'DE') IN ( SELECT (KEY, value) FROM unnest(all_tags)) AND ( 'addr:city', 'Hamburg') IN ( SELECT (KEY, value) FROM unnest (all_tags));"
},
{
"code": null,
"e": 1997,
"s": 1960,
"text": "which results in the desired output:"
},
{
"code": null,
"e": 2099,
"s": 1997,
"text": "With the function of unnest you will also be able to flatten the data and so the output of the query:"
},
{
"code": null,
"e": 2212,
"s": 2099,
"text": "SELECT osm_id,tagsFROM bigquery-public-data.geo_openstreetmap.planet_features,UNNEST(all_tags) as tags limit 100"
},
{
"code": null,
"e": 2658,
"s": 2212,
"text": "This is probably almost the most important you have to know when working with nested data in BigQuery and want to query some data. But what if you want to use the data for further ETL processes, store the data in relational databases or need the key-value-pairs as attributes for your classifier? Here, you want the data not to flatten — because this will result in duplicate rows — here you want the key-value-pairs in the array as new columns:"
},
{
"code": null,
"e": 3963,
"s": 2658,
"text": "SELECT ( SELECT osm_id) osmid, ( SELECT value FROM Unnest(all_tags) WHERE KEY = \"Address\") AS address, ( SELECT value FROM Unnest(all_tags) WHERE KEY = \"name\") AS NAME, ( SELECT value FROM Unnest(all_tags) WHERE KEY = \"opening_hours\") AS opening_hours, ( SELECT value FROM Unnest(all_tags) WHERE KEY = \"organic\") AS organic, ( SELECT geometry) AS geometry, FROM bigquery-PUBLIC-data.geo_openstreetmap.planet_features WHERE ( 'Edeka' IN ( SELECT value FROM unnest(all_tags)) OR 'Rewe' IN ( SELECT value FROM unnest(all_tags)) OR 'Netto' IN ( SELECT value FROM unnest(all_tags))) AND ( 'addr:country', 'DE') IN ( SELECT (KEY, value) FROM unnest(all_tags)) - AND ( 'addr:city', 'Hamburg') IN ( SELECT (KEY, value) FROM unnest(all_tags));"
},
{
"code": null,
"e": 4179,
"s": 3963,
"text": "After I came into contact with nested data for the first time — I have to admit that I didn’t know what to do with it at first and probably had the same facial expression as Mark Wahlberg in the movie The Happening."
},
{
"code": null,
"e": 4497,
"s": 4179,
"text": "But I realized in the new world, such data formats are normal and the way to the world of unstructured data. New systems offer extremely high computing power and fast results through column-based databases. With the above examples, you should be able to query and process most of your nested data use cases very well."
}
] |
Download webpage in Java | We can download a web page using its URL in Java. Following are the steps needed.
Create URL object using url string.Download webpage in Java
Create URL object using url string.
Download webpage in Java
Create a BufferReader object using url.openStream() method.BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
Create a BufferReader object using url.openStream() method.
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
Create a BufferWriter object to write to a file.BufferedWriter writer = new BufferedWriter(new FileWriter("page.html"));
Create a BufferWriter object to write to a file.
BufferedWriter writer = new BufferedWriter(new FileWriter("page.html"));
Read each line using BufferReader and write using BufferWriter.String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
}
Read each line using BufferReader and write using BufferWriter.
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
}
Following is the complete program to download a given URL page at current location.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Tester {
public static void main(String args[]) throws IOException {
download("http://www.google.com");
}
public static void download(String urlString) throws IOException {
URL url = new URL(urlString);
try(
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter("page.html"));
) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
}
System.out.println("Page downloaded.");
}
}
}
Page downloaded. | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "We can download a web page using its URL in Java. Following are the steps needed."
},
{
"code": null,
"e": 1204,
"s": 1144,
"text": "Create URL object using url string.Download webpage in Java"
},
{
"code": null,
"e": 1240,
"s": 1204,
"text": "Create URL object using url string."
},
{
"code": null,
"e": 1265,
"s": 1240,
"text": "Download webpage in Java"
},
{
"code": null,
"e": 1409,
"s": 1265,
"text": "Create a BufferReader object using url.openStream() method.BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));"
},
{
"code": null,
"e": 1469,
"s": 1409,
"text": "Create a BufferReader object using url.openStream() method."
},
{
"code": null,
"e": 1554,
"s": 1469,
"text": "BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));"
},
{
"code": null,
"e": 1675,
"s": 1554,
"text": "Create a BufferWriter object to write to a file.BufferedWriter writer = new BufferedWriter(new FileWriter(\"page.html\"));"
},
{
"code": null,
"e": 1724,
"s": 1675,
"text": "Create a BufferWriter object to write to a file."
},
{
"code": null,
"e": 1797,
"s": 1724,
"text": "BufferedWriter writer = new BufferedWriter(new FileWriter(\"page.html\"));"
},
{
"code": null,
"e": 1940,
"s": 1797,
"text": "Read each line using BufferReader and write using BufferWriter.String line;\nwhile ((line = reader.readLine()) != null) {\nwriter.write(line);\n}"
},
{
"code": null,
"e": 2004,
"s": 1940,
"text": "Read each line using BufferReader and write using BufferWriter."
},
{
"code": null,
"e": 2084,
"s": 2004,
"text": "String line;\nwhile ((line = reader.readLine()) != null) {\nwriter.write(line);\n}"
},
{
"code": null,
"e": 2168,
"s": 2084,
"text": "Following is the complete program to download a given URL page at current location."
},
{
"code": null,
"e": 2958,
"s": 2168,
"text": "import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URL;\n\npublic class Tester {\n public static void main(String args[]) throws IOException {\n download(\"http://www.google.com\");\n }\n public static void download(String urlString) throws IOException {\n URL url = new URL(urlString);\n try(\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n BufferedWriter writer = new BufferedWriter(new FileWriter(\"page.html\"));\n ) {\n String line;\n while ((line = reader.readLine()) != null) {\n writer.write(line);\n }\n System.out.println(\"Page downloaded.\");\n }\n }\n}"
},
{
"code": null,
"e": 2975,
"s": 2958,
"text": "Page downloaded."
}
] |
IntStream map() method in Java | The IntStream map() method returns the new stream consisting of the results of applying the given function to the elements of this stream.
The syntax is as follows
IntStream map(IntUnaryOperator mapper)
Here, mapper parameter is a non-interfering, stateless function to apply to each element
Create an IntStream and add some elements
IntStream intStream1 = IntStream.of(20, 35, 40, 55, 60);
Now, map it with the new IntStream and display the updated stream elements applying the condition in the map() function
IntStream intStream2 = intStream1.map(a -> (a + a));
The following is an example to implement IntStream map() method in Java
Live Demo
import java.util.*;
import java.util.stream.IntStream;
public class Demo {
public static void main(String[] args) {
IntStream intStream1 = IntStream.of(20, 35, 40, 55, 60);
IntStream intStream2 = intStream1.map(a -> (a + a));
System.out.println("Updated Stream...");
intStream2.forEach(System.out::println);
}
}
Updated Stream...
40
70
80
110
120 | [
{
"code": null,
"e": 1201,
"s": 1062,
"text": "The IntStream map() method returns the new stream consisting of the results of applying the given function to the elements of this stream."
},
{
"code": null,
"e": 1226,
"s": 1201,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1265,
"s": 1226,
"text": "IntStream map(IntUnaryOperator mapper)"
},
{
"code": null,
"e": 1354,
"s": 1265,
"text": "Here, mapper parameter is a non-interfering, stateless function to apply to each element"
},
{
"code": null,
"e": 1396,
"s": 1354,
"text": "Create an IntStream and add some elements"
},
{
"code": null,
"e": 1453,
"s": 1396,
"text": "IntStream intStream1 = IntStream.of(20, 35, 40, 55, 60);"
},
{
"code": null,
"e": 1573,
"s": 1453,
"text": "Now, map it with the new IntStream and display the updated stream elements applying the condition in the map() function"
},
{
"code": null,
"e": 1626,
"s": 1573,
"text": "IntStream intStream2 = intStream1.map(a -> (a + a));"
},
{
"code": null,
"e": 1698,
"s": 1626,
"text": "The following is an example to implement IntStream map() method in Java"
},
{
"code": null,
"e": 1709,
"s": 1698,
"text": " Live Demo"
},
{
"code": null,
"e": 2051,
"s": 1709,
"text": "import java.util.*;\nimport java.util.stream.IntStream;\npublic class Demo {\n public static void main(String[] args) {\n IntStream intStream1 = IntStream.of(20, 35, 40, 55, 60);\n IntStream intStream2 = intStream1.map(a -> (a + a));\n System.out.println(\"Updated Stream...\");\n intStream2.forEach(System.out::println);\n }\n}"
},
{
"code": null,
"e": 2086,
"s": 2051,
"text": "Updated Stream...\n40\n70\n80\n110\n120"
}
] |
Merge k Sorted Arrays | Practice | GeeksforGeeks | Given K sorted arrays arranged in the form of a matrix of size K*K. The task is to merge them into one sorted array.
Example 1:
Input:
K = 3
arr[][] = {{1,2,3},{4,5,6},{7,8,9}}
Output: 1 2 3 4 5 6 7 8 9
Explanation:Above test case has 3 sorted
arrays of size 3, 3, 3
arr[][] = [[1, 2, 3],[4, 5, 6],
[7, 8, 9]]
The merged list will be
[1, 2, 3, 4, 5, 6, 7, 8, 9].
Example 2:
Input:
K = 4
arr[][]={{1,2,3,4}{2,2,3,4},
{5,5,6,6},{7,8,9,9}}
Output:
1 2 2 2 3 3 4 4 5 5 6 6 7 8 9 9
Explanation: Above test case has 4 sorted
arrays of size 4, 4, 4, 4
arr[][] = [[1, 2, 2, 2], [3, 3, 4, 4],
[5, 5, 6, 6] [7, 8, 9, 9 ]]
The merged list will be
[1, 2, 2, 2, 3, 3, 4, 4, 5, 5,
6, 6, 7, 8, 9, 9 ].
Your Task:
You do not need to read input or print anything. Your task is to complete mergeKArrays() function which takes 2 arguments, an arr[K][K] 2D Matrix containing K sorted arrays and an integer K denoting the number of sorted arrays, as input and returns the merged sorted array ( as a pointer to the merged sorted arrays in cpp, as an ArrayList in java, and list in python)
Expected Time Complexity: O(K2*Log(K))
Expected Auxiliary Space: O(K)
Constraints:
1 <= K <= 100
0
shreyash9779665 days ago
SIMPLEST SOLUTION EVER!!
vector<int> mergeKArrays(vector<vector<int>> a, int n)
{
//code here
vector<int>v;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
v.push_back(a[i][j]);
}
}
sort(v.begin(),v.end());
return v;
}
0
velspace015 days ago
Java trivial sol TC-->O(K^2) SC-->O(K)
ArrayList<Integer> ans=new ArrayList<>();
for(int i=0;i<k;i++){
for(int j=0;j<k;j++){
ans.add(arr[i][j]);
}
}
Collections.sort(ans);
return ans;
0
shandlikamal2481 week ago
O(KLOGK) java soln.
static class Pair { int n; int row; int col; Pair(int i,int j,int k) { n=i; row=j; col=k; } } public static ArrayList<Integer> mergeKArrays(int[][] arr,int K) { // Write your code here. ArrayList<Integer> array=new ArrayList<>(); PriorityQueue<Pair> pq=new PriorityQueue<>(new Comparator<Pair>() { public int compare(Pair a,Pair b) { return Integer.compare(a.n,b.n); } }); for(int i=0;i<K;i++) { pq.add(new Pair(arr[i][0],i,0)); } while(!pq.isEmpty()) { Pair next=pq.poll(); array.add(next.n); int row=next.row; int col=next.col; if(col+1<K) pq.add(new Pair(arr[row][col+1],row,col+1)); } return array;
0
baviral1 week ago
class Solution
{
public:
class node{
public:
int data;
int i;
int j;
node(int data, int row, int col){
this->data = data;
this->i = row;
this->j = col;
}
};
class compare{
public:
bool operator()(node* a, node* b){
return a->data > b->data;
}
};
vector<int> mergeKArrays(vector<vector<int>> arr, int K)
{
priority_queue<node*, vector<node*>, compare> pq;
vector<int> ans;
for(int i=0; i<K; i++){
node* temp = new node(arr[i][0],i,0);
pq.push(temp);
}
while(!pq.empty()){
node* temp = pq.top();
ans.push_back(temp->data);
pq.pop();
int i = temp->i;
int j = temp->j;
if(j+1 < arr[i].size())
{
node* next = new node(arr[i][j+1], i, j+1);
pq.push(next);
}
}
return ans;
}
};
0
mayank_nigam2 weeks ago
Java Solution -
public static class pair implements Comparable<pair>{ int li; int di; int val; public pair(int li,int di,int val){ this.li=li; this.di=di; this.val=val; } public int compareTo(pair o){ return this.val-o.val; }
} public static ArrayList<Integer> mergeKArrays(int[][] arr,int K) { ArrayList<Integer> res= new ArrayList<>(); PriorityQueue<pair> pq= new PriorityQueue<>(); for(int i=0;i<arr.length;i++){ pair p = new pair(i,0,arr[i][0]); pq.add(p); } while(pq.size()>0){ pair p = pq.remove(); res.add(p.val); p.di++; // di - data index , li - list index , val - value if(p.di<arr[p.li].length){ p.val=arr[p.li][p.di]; pq.add(p); } } return res; }
-3
rishabh21cse2 weeks ago
MOST EASY C++ SOLUTION.....
vector<int> v; for(int i=0;i<K;i++){ for(int j=0;j<K;j++) v.push_back(arr[i][j]); } sort(v.begin(),v.end()); return v;
0
amarrajsmart1972 weeks ago
C++ Solution...
vector<int> mergeKArrays(vector<vector<int>> arr, int K) { //code here vector<int> v; for(int i=0;i<K;i++) { for(int j=0;j<K;j++) { v.push_back(arr[i][j]); } } sort(v.begin(),v.end()); return v; }
0
bhaskarmaheshwari82 weeks ago
vector<int> merge(vector<int>&a,vector<int> &b) { int n1=a.size(); int n2=b.size(); vector<int> v(n1+n2); int i=0,j=0,k=0; while(i<n1&&j<n2) { if(a[i]<=b[j]) { v[k++]=a[i++]; } else { v[k++]=b[j++]; } } while(i<n1) { v[k++]=a[i++]; } while(j<n2) { v[k++]=b[j++]; } return v; } vector<int> mergeKArrays(vector<vector<int>> arr, int k) { //code here vector<int> ans=arr[0]; for(int i=1;i<k;i++) { ans=merge(ans,arr[i]); } return ans; }
0
mohitraj27412 weeks ago
time- 0.56 seconds
complexity- O(K^2)
class Solution{ public: //write a func to merge 2 sorted arrays first vector<int> merge(vector<int>a,vector<int>b,int m,int n) { vector<int>ans; int i=0; int j=0; while(i<m && j<n) { if(a[i]<=b[j]) {ans.push_back(a[i]);i++;} else {ans.push_back(b[j]);j++;} } while(i<m) {ans.push_back(a[i]);i++; } while(j<n) {ans.push_back(b[j]);j++; } return ans; } // apply the above function in final function vector<int> mergeKArrays(vector<vector<int>> arr, int K) { //code here if(K==1) return arr[0]; vector<int> res; res= merge(arr[0],arr[1],K,K);
for(int i=2;i<=K-1;i++) { res= merge(res,arr[i],K*i,K); } return res; }};
0
akashmarkad22102 weeks ago
JAVA Solution
public static ArrayList<Integer> mergeKArrays(int[][] arr,int K) { // Write your code here. ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0 ; i < K ; i++) { for(int j = 0 ; j < K ; j++) { ans.add(arr[i][j]); } } Collections.sort(ans); return ans; }
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": 367,
"s": 238,
"text": "Given K sorted arrays arranged in the form of a matrix of size K*K. The task is to merge them into one sorted array.\nExample 1: "
},
{
"code": null,
"e": 604,
"s": 367,
"text": "Input:\nK = 3\narr[][] = {{1,2,3},{4,5,6},{7,8,9}}\nOutput: 1 2 3 4 5 6 7 8 9\nExplanation:Above test case has 3 sorted\narrays of size 3, 3, 3\narr[][] = [[1, 2, 3],[4, 5, 6], \n[7, 8, 9]]\nThe merged list will be \n[1, 2, 3, 4, 5, 6, 7, 8, 9]."
},
{
"code": null,
"e": 616,
"s": 604,
"text": "Example 2: "
},
{
"code": null,
"e": 942,
"s": 616,
"text": "Input:\nK = 4\narr[][]={{1,2,3,4}{2,2,3,4},\n {5,5,6,6},{7,8,9,9}}\nOutput:\n1 2 2 2 3 3 4 4 5 5 6 6 7 8 9 9 \nExplanation: Above test case has 4 sorted\narrays of size 4, 4, 4, 4\narr[][] = [[1, 2, 2, 2], [3, 3, 4, 4],\n[5, 5, 6, 6] [7, 8, 9, 9 ]]\nThe merged list will be \n[1, 2, 2, 2, 3, 3, 4, 4, 5, 5, \n6, 6, 7, 8, 9, 9 ]."
},
{
"code": null,
"e": 1322,
"s": 942,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete mergeKArrays() function which takes 2 arguments, an arr[K][K] 2D Matrix containing K sorted arrays and an integer K denoting the number of sorted arrays, as input and returns the merged sorted array ( as a pointer to the merged sorted arrays in cpp, as an ArrayList in java, and list in python)"
},
{
"code": null,
"e": 1392,
"s": 1322,
"text": "Expected Time Complexity: O(K2*Log(K))\nExpected Auxiliary Space: O(K)"
},
{
"code": null,
"e": 1419,
"s": 1392,
"text": "Constraints:\n1 <= K <= 100"
},
{
"code": null,
"e": 1421,
"s": 1419,
"text": "0"
},
{
"code": null,
"e": 1446,
"s": 1421,
"text": "shreyash9779665 days ago"
},
{
"code": null,
"e": 1758,
"s": 1446,
"text": "SIMPLEST SOLUTION EVER!!\n vector<int> mergeKArrays(vector<vector<int>> a, int n)\n {\n //code here\n vector<int>v;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n v.push_back(a[i][j]);\n }\n }\n sort(v.begin(),v.end());\n return v;\n }"
},
{
"code": null,
"e": 1764,
"s": 1762,
"text": "0"
},
{
"code": null,
"e": 1785,
"s": 1764,
"text": "velspace015 days ago"
},
{
"code": null,
"e": 2042,
"s": 1785,
"text": "Java trivial sol TC-->O(K^2) SC-->O(K)\n ArrayList<Integer> ans=new ArrayList<>();\n for(int i=0;i<k;i++){\n for(int j=0;j<k;j++){\n ans.add(arr[i][j]);\n }\n }\n Collections.sort(ans);\n return ans;"
},
{
"code": null,
"e": 2044,
"s": 2042,
"text": "0"
},
{
"code": null,
"e": 2070,
"s": 2044,
"text": "shandlikamal2481 week ago"
},
{
"code": null,
"e": 2090,
"s": 2070,
"text": "O(KLOGK) java soln."
},
{
"code": null,
"e": 3005,
"s": 2090,
"text": "static class Pair { int n; int row; int col; Pair(int i,int j,int k) { n=i; row=j; col=k; } } public static ArrayList<Integer> mergeKArrays(int[][] arr,int K) { // Write your code here. ArrayList<Integer> array=new ArrayList<>(); PriorityQueue<Pair> pq=new PriorityQueue<>(new Comparator<Pair>() { public int compare(Pair a,Pair b) { return Integer.compare(a.n,b.n); } }); for(int i=0;i<K;i++) { pq.add(new Pair(arr[i][0],i,0)); } while(!pq.isEmpty()) { Pair next=pq.poll(); array.add(next.n); int row=next.row; int col=next.col; if(col+1<K) pq.add(new Pair(arr[row][col+1],row,col+1)); } return array;"
},
{
"code": null,
"e": 3009,
"s": 3007,
"text": "0"
},
{
"code": null,
"e": 3027,
"s": 3009,
"text": "baviral1 week ago"
},
{
"code": null,
"e": 4126,
"s": 3027,
"text": "class Solution\n{\n public:\n \n class node{\n public:\n int data;\n int i;\n int j;\n \n node(int data, int row, int col){\n this->data = data;\n this->i = row;\n this->j = col;\n }\n };\n \n class compare{\n public:\n bool operator()(node* a, node* b){\n return a->data > b->data;\n }\n };\n \n vector<int> mergeKArrays(vector<vector<int>> arr, int K)\n {\n priority_queue<node*, vector<node*>, compare> pq;\n vector<int> ans;\n \n for(int i=0; i<K; i++){\n node* temp = new node(arr[i][0],i,0);\n pq.push(temp);\n }\n \n while(!pq.empty()){\n node* temp = pq.top();\n ans.push_back(temp->data);\n pq.pop();\n \n int i = temp->i;\n int j = temp->j;\n \n if(j+1 < arr[i].size())\n {\n node* next = new node(arr[i][j+1], i, j+1);\n pq.push(next);\n }\n }\n return ans;\n }\n};"
},
{
"code": null,
"e": 4128,
"s": 4126,
"text": "0"
},
{
"code": null,
"e": 4152,
"s": 4128,
"text": "mayank_nigam2 weeks ago"
},
{
"code": null,
"e": 4170,
"s": 4152,
"text": " Java Solution - "
},
{
"code": null,
"e": 4494,
"s": 4170,
"text": "public static class pair implements Comparable<pair>{ int li; int di; int val; public pair(int li,int di,int val){ this.li=li; this.di=di; this.val=val; } public int compareTo(pair o){ return this.val-o.val; }"
},
{
"code": null,
"e": 5108,
"s": 4494,
"text": " } public static ArrayList<Integer> mergeKArrays(int[][] arr,int K) { ArrayList<Integer> res= new ArrayList<>(); PriorityQueue<pair> pq= new PriorityQueue<>(); for(int i=0;i<arr.length;i++){ pair p = new pair(i,0,arr[i][0]); pq.add(p); } while(pq.size()>0){ pair p = pq.remove(); res.add(p.val); p.di++; // di - data index , li - list index , val - value if(p.di<arr[p.li].length){ p.val=arr[p.li][p.di]; pq.add(p); } } return res; }"
},
{
"code": null,
"e": 5111,
"s": 5108,
"text": "-3"
},
{
"code": null,
"e": 5135,
"s": 5111,
"text": "rishabh21cse2 weeks ago"
},
{
"code": null,
"e": 5163,
"s": 5135,
"text": "MOST EASY C++ SOLUTION....."
},
{
"code": null,
"e": 5341,
"s": 5163,
"text": " vector<int> v; for(int i=0;i<K;i++){ for(int j=0;j<K;j++) v.push_back(arr[i][j]); } sort(v.begin(),v.end()); return v; "
},
{
"code": null,
"e": 5343,
"s": 5341,
"text": "0"
},
{
"code": null,
"e": 5370,
"s": 5343,
"text": "amarrajsmart1972 weeks ago"
},
{
"code": null,
"e": 5386,
"s": 5370,
"text": "C++ Solution..."
},
{
"code": null,
"e": 5680,
"s": 5386,
"text": "vector<int> mergeKArrays(vector<vector<int>> arr, int K) { //code here vector<int> v; for(int i=0;i<K;i++) { for(int j=0;j<K;j++) { v.push_back(arr[i][j]); } } sort(v.begin(),v.end()); return v; }"
},
{
"code": null,
"e": 5682,
"s": 5680,
"text": "0"
},
{
"code": null,
"e": 5712,
"s": 5682,
"text": "bhaskarmaheshwari82 weeks ago"
},
{
"code": null,
"e": 6415,
"s": 5712,
"text": "vector<int> merge(vector<int>&a,vector<int> &b) { int n1=a.size(); int n2=b.size(); vector<int> v(n1+n2); int i=0,j=0,k=0; while(i<n1&&j<n2) { if(a[i]<=b[j]) { v[k++]=a[i++]; } else { v[k++]=b[j++]; } } while(i<n1) { v[k++]=a[i++]; } while(j<n2) { v[k++]=b[j++]; } return v; } vector<int> mergeKArrays(vector<vector<int>> arr, int k) { //code here vector<int> ans=arr[0]; for(int i=1;i<k;i++) { ans=merge(ans,arr[i]); } return ans; }"
},
{
"code": null,
"e": 6417,
"s": 6415,
"text": "0"
},
{
"code": null,
"e": 6441,
"s": 6417,
"text": "mohitraj27412 weeks ago"
},
{
"code": null,
"e": 6460,
"s": 6441,
"text": "time- 0.56 seconds"
},
{
"code": null,
"e": 6479,
"s": 6460,
"text": "complexity- O(K^2)"
},
{
"code": null,
"e": 7206,
"s": 6481,
"text": "class Solution{ public: //write a func to merge 2 sorted arrays first vector<int> merge(vector<int>a,vector<int>b,int m,int n) { vector<int>ans; int i=0; int j=0; while(i<m && j<n) { if(a[i]<=b[j]) {ans.push_back(a[i]);i++;} else {ans.push_back(b[j]);j++;} } while(i<m) {ans.push_back(a[i]);i++; } while(j<n) {ans.push_back(b[j]);j++; } return ans; } // apply the above function in final function vector<int> mergeKArrays(vector<vector<int>> arr, int K) { //code here if(K==1) return arr[0]; vector<int> res; res= merge(arr[0],arr[1],K,K);"
},
{
"code": null,
"e": 7315,
"s": 7206,
"text": " for(int i=2;i<=K-1;i++) { res= merge(res,arr[i],K*i,K); } return res; }};"
},
{
"code": null,
"e": 7317,
"s": 7315,
"text": "0"
},
{
"code": null,
"e": 7344,
"s": 7317,
"text": "akashmarkad22102 weeks ago"
},
{
"code": null,
"e": 7358,
"s": 7344,
"text": "JAVA Solution"
},
{
"code": null,
"e": 7740,
"s": 7360,
"text": " public static ArrayList<Integer> mergeKArrays(int[][] arr,int K) { // Write your code here. ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0 ; i < K ; i++) { for(int j = 0 ; j < K ; j++) { ans.add(arr[i][j]); } } Collections.sort(ans); return ans; }"
},
{
"code": null,
"e": 7886,
"s": 7740,
"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": 7922,
"s": 7886,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7932,
"s": 7922,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7942,
"s": 7932,
"text": "\nContest\n"
},
{
"code": null,
"e": 8005,
"s": 7942,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8153,
"s": 8005,
"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": 8361,
"s": 8153,
"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": 8467,
"s": 8361,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Random Forest for prediction. Using Random Forest to predict... | by Aditya Kumar | Towards Data Science | It’s a process that operates among multiple decision trees to get the optimum result by choosing the majority among them as the best value.
Consider the above image as a representation of multiple decision trees with different results. Out of 4 decision trees, 3 has the same output as 1 while one decision tree has output as 0. Applying the definition mentioned above Random forest is operating four decision trees and to get the best result it's choosing the result which majority i.e 3 of the decision trees are providing. Hence, in this case, the optimum result will be 1.
For the Decision Tree, you can visit the earlier story by clicking on the link https://towardsdatascience.com/decision-tree-ba64f977f7c3
Uses
Remote Sensing: Random Forest (RF) is commonly used in remote sensing to predict the accuracy/classification of data.Object Detection: RF plays a major role in object detection in less time.
Remote Sensing: Random Forest (RF) is commonly used in remote sensing to predict the accuracy/classification of data.
Object Detection: RF plays a major role in object detection in less time.
Why?
Since we are working on multiple decision trees there is a chance of less over-fitting.Greater Accuracy: Since it runs on a larger data set, the accuracy is higher.Estimate Missing data: Since it runs on a larger data set, you can estimate the missing values as well.
Since we are working on multiple decision trees there is a chance of less over-fitting.
Greater Accuracy: Since it runs on a larger data set, the accuracy is higher.
Estimate Missing data: Since it runs on a larger data set, you can estimate the missing values as well.
How does Random Forest work?
In the above diagram, we have the same classification using 3 different decision trees. Tree 1 classifies the data using Color, Tree 2 using Petal Size and Color, and Tree 3 using Petal lifespan and color.
The model is well-trained now. Considering we have a flower with color data missing. Tree 1 will not be able to recognize this data as it classified everything in color so it will bring it to the tulip flower category.
Tree 2: It works on color and petal size. As per the petal size, it will go to a false i.e. not small followed by color i.e., not yellow. So here is the prediction that it’s a rose.
Tree 3: It works on lifespan and color. The first classification will be in a false category followed by non-yellow color. So here as per prediction it’s a rose.
Let’s try to use Random Forest with Python. First, we will import the python library needed.
import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline
We are importing pandas, NumPy, and matplotlib. Next, we will consume the data and view it.
df.head() will give us the details of the top 5 rows of every column. We can use df.tail() to get the last 5 rows and similar df.head(10) to get to the top 10 rows.
The data is about cars, and we need to predict the price of cars using the above data
We will be using Random Forest to get the price of the car.
df.dtypessymboling int64normalized-losses int64make objectaspiration objectnum-of-doors objectbody-style objectdrive-wheels objectengine-location objectwheel-base float64length float64width float64height float64curb-weight int64engine-type objectnum-of-cylinders objectengine-size int64fuel-system objectbore float64stroke float64compression-ratio float64horsepower float64peak-rpm float64city-mpg int64highway-mpg int64price float64city-L/100km float64horsepower-binned objectdiesel int64gas int64dtype: object
dtypes give the data type of column.
df.describe()
In the above data-frame, all the columns are not numeric. So we will consider only those columns whose values are in numeric and will make all numeric to float.
df.dtypesfor x in df: if df[x].dtypes == "int64": df[x] = df[x].astype(float) print (df[x].dtypes)
Preparing the Data As with the classification task, in this section, we will divide our data into attributes and labels and consequently into training and test sets. We will create 2 data sets, one for the price while the other (df-price). Since our data-frame has a lot of data in object format, for this analysis we are removing all the columns with object type and for all NaN values, we are removing that row.
df = df.select_dtypes(exclude=['object'])df=df.fillna(df.mean())X = df.drop('price',axis=1)y = df['price']
Here the X variable contains all the columns from the data-set, except the ‘Price’ column, which is the label. The y variable contains values from the ‘Price’ column, which means that the X variable contains the attribute set and y variable contains the corresponding labels.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
To train the tree, we will use the Random Forest class and call it with the fit method. We will have a random forest with 1000 decision trees.
from sklearn.ensemble import RandomForestRegressorregressor = RandomForestRegressor(n_estimators = 1000, random_state = 42)regressor.fit(X_train, y_train)
Let's predict the price.
y_pred = regressor.predict(X_test)
Let’s check the difference between the actual and predicted values.
df=pd.DataFrame({'Actual':y_test, 'Predicted':y_pred})df
from sklearn import metricsprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))Mean Absolute Error: 1993.2901175839186Mean Squared Error: 9668487.223350348Root Mean Squared Error: 3109.4191134921566
The mean absolute error for our algorithm is 1993.2901175839186, which is less than 20 percent of the mean of all the values in the ‘Price’ column. This means that our algorithm made a prediction, but it needs a lot of improvement.
Let’s check the accuracy of our prediction.
# Calculate the absolute errorserrors = abs(y_pred - y_test)# Print out the mean absolute error (mae)print('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')# Calculate mean absolute percentage error (MAPE)mape = 100 * (errors / y_test)# Calculate and display accuracyaccuracy = 100 - np.mean(mape)print('Accuracy:', round(accuracy, 2), '%.')Mean Absolute Error: 1993.29 degrees.Accuracy: 87.87 %.
Accuracy of 87.8% is not a very great score and there is a lot of scope for improvement.
Let’s plot the difference between the actual and the predicted value.
import seaborn as snsplt.figure(figsize=(5, 7))ax = sns.distplot(y, hist=False, color="r", label="Actual Value")sns.distplot(y_pred, hist=False, color="b", label="Fitted Values" , ax=ax)plt.title('Actual vs Fitted Values for Price')plt.show()plt.close()
The above is the graph between the actual and predicted values. Let’s visualize the Random Forest tree.
import pydot# Pull out one tree from the forestTree = regressor.estimators_[5]# Export the image to a dot filefrom sklearn import treeplt.figure(figsize=(25,15))tree.plot_tree(Tree,filled=True, rounded=True, fontsize=14);
The code can be checked at https://www.kaggle.com/adityakumar529/random-forest. | [
{
"code": null,
"e": 312,
"s": 172,
"text": "It’s a process that operates among multiple decision trees to get the optimum result by choosing the majority among them as the best value."
},
{
"code": null,
"e": 749,
"s": 312,
"text": "Consider the above image as a representation of multiple decision trees with different results. Out of 4 decision trees, 3 has the same output as 1 while one decision tree has output as 0. Applying the definition mentioned above Random forest is operating four decision trees and to get the best result it's choosing the result which majority i.e 3 of the decision trees are providing. Hence, in this case, the optimum result will be 1."
},
{
"code": null,
"e": 886,
"s": 749,
"text": "For the Decision Tree, you can visit the earlier story by clicking on the link https://towardsdatascience.com/decision-tree-ba64f977f7c3"
},
{
"code": null,
"e": 891,
"s": 886,
"text": "Uses"
},
{
"code": null,
"e": 1082,
"s": 891,
"text": "Remote Sensing: Random Forest (RF) is commonly used in remote sensing to predict the accuracy/classification of data.Object Detection: RF plays a major role in object detection in less time."
},
{
"code": null,
"e": 1200,
"s": 1082,
"text": "Remote Sensing: Random Forest (RF) is commonly used in remote sensing to predict the accuracy/classification of data."
},
{
"code": null,
"e": 1274,
"s": 1200,
"text": "Object Detection: RF plays a major role in object detection in less time."
},
{
"code": null,
"e": 1279,
"s": 1274,
"text": "Why?"
},
{
"code": null,
"e": 1547,
"s": 1279,
"text": "Since we are working on multiple decision trees there is a chance of less over-fitting.Greater Accuracy: Since it runs on a larger data set, the accuracy is higher.Estimate Missing data: Since it runs on a larger data set, you can estimate the missing values as well."
},
{
"code": null,
"e": 1635,
"s": 1547,
"text": "Since we are working on multiple decision trees there is a chance of less over-fitting."
},
{
"code": null,
"e": 1713,
"s": 1635,
"text": "Greater Accuracy: Since it runs on a larger data set, the accuracy is higher."
},
{
"code": null,
"e": 1817,
"s": 1713,
"text": "Estimate Missing data: Since it runs on a larger data set, you can estimate the missing values as well."
},
{
"code": null,
"e": 1846,
"s": 1817,
"text": "How does Random Forest work?"
},
{
"code": null,
"e": 2052,
"s": 1846,
"text": "In the above diagram, we have the same classification using 3 different decision trees. Tree 1 classifies the data using Color, Tree 2 using Petal Size and Color, and Tree 3 using Petal lifespan and color."
},
{
"code": null,
"e": 2271,
"s": 2052,
"text": "The model is well-trained now. Considering we have a flower with color data missing. Tree 1 will not be able to recognize this data as it classified everything in color so it will bring it to the tulip flower category."
},
{
"code": null,
"e": 2453,
"s": 2271,
"text": "Tree 2: It works on color and petal size. As per the petal size, it will go to a false i.e. not small followed by color i.e., not yellow. So here is the prediction that it’s a rose."
},
{
"code": null,
"e": 2615,
"s": 2453,
"text": "Tree 3: It works on lifespan and color. The first classification will be in a false category followed by non-yellow color. So here as per prediction it’s a rose."
},
{
"code": null,
"e": 2708,
"s": 2615,
"text": "Let’s try to use Random Forest with Python. First, we will import the python library needed."
},
{
"code": null,
"e": 2795,
"s": 2708,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 2887,
"s": 2795,
"text": "We are importing pandas, NumPy, and matplotlib. Next, we will consume the data and view it."
},
{
"code": null,
"e": 3052,
"s": 2887,
"text": "df.head() will give us the details of the top 5 rows of every column. We can use df.tail() to get the last 5 rows and similar df.head(10) to get to the top 10 rows."
},
{
"code": null,
"e": 3138,
"s": 3052,
"text": "The data is about cars, and we need to predict the price of cars using the above data"
},
{
"code": null,
"e": 3198,
"s": 3138,
"text": "We will be using Random Forest to get the price of the car."
},
{
"code": null,
"e": 4033,
"s": 3198,
"text": "df.dtypessymboling int64normalized-losses int64make objectaspiration objectnum-of-doors objectbody-style objectdrive-wheels objectengine-location objectwheel-base float64length float64width float64height float64curb-weight int64engine-type objectnum-of-cylinders objectengine-size int64fuel-system objectbore float64stroke float64compression-ratio float64horsepower float64peak-rpm float64city-mpg int64highway-mpg int64price float64city-L/100km float64horsepower-binned objectdiesel int64gas int64dtype: object"
},
{
"code": null,
"e": 4070,
"s": 4033,
"text": "dtypes give the data type of column."
},
{
"code": null,
"e": 4084,
"s": 4070,
"text": "df.describe()"
},
{
"code": null,
"e": 4245,
"s": 4084,
"text": "In the above data-frame, all the columns are not numeric. So we will consider only those columns whose values are in numeric and will make all numeric to float."
},
{
"code": null,
"e": 4361,
"s": 4245,
"text": "df.dtypesfor x in df: if df[x].dtypes == \"int64\": df[x] = df[x].astype(float) print (df[x].dtypes)"
},
{
"code": null,
"e": 4775,
"s": 4361,
"text": "Preparing the Data As with the classification task, in this section, we will divide our data into attributes and labels and consequently into training and test sets. We will create 2 data sets, one for the price while the other (df-price). Since our data-frame has a lot of data in object format, for this analysis we are removing all the columns with object type and for all NaN values, we are removing that row."
},
{
"code": null,
"e": 4882,
"s": 4775,
"text": "df = df.select_dtypes(exclude=['object'])df=df.fillna(df.mean())X = df.drop('price',axis=1)y = df['price']"
},
{
"code": null,
"e": 5158,
"s": 4882,
"text": "Here the X variable contains all the columns from the data-set, except the ‘Price’ column, which is the label. The y variable contains values from the ‘Price’ column, which means that the X variable contains the attribute set and y variable contains the corresponding labels."
},
{
"code": null,
"e": 5299,
"s": 5158,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)"
},
{
"code": null,
"e": 5442,
"s": 5299,
"text": "To train the tree, we will use the Random Forest class and call it with the fit method. We will have a random forest with 1000 decision trees."
},
{
"code": null,
"e": 5597,
"s": 5442,
"text": "from sklearn.ensemble import RandomForestRegressorregressor = RandomForestRegressor(n_estimators = 1000, random_state = 42)regressor.fit(X_train, y_train)"
},
{
"code": null,
"e": 5622,
"s": 5597,
"text": "Let's predict the price."
},
{
"code": null,
"e": 5657,
"s": 5622,
"text": "y_pred = regressor.predict(X_test)"
},
{
"code": null,
"e": 5725,
"s": 5657,
"text": "Let’s check the difference between the actual and predicted values."
},
{
"code": null,
"e": 5782,
"s": 5725,
"text": "df=pd.DataFrame({'Actual':y_test, 'Predicted':y_pred})df"
},
{
"code": null,
"e": 6161,
"s": 5782,
"text": "from sklearn import metricsprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))Mean Absolute Error: 1993.2901175839186Mean Squared Error: 9668487.223350348Root Mean Squared Error: 3109.4191134921566"
},
{
"code": null,
"e": 6393,
"s": 6161,
"text": "The mean absolute error for our algorithm is 1993.2901175839186, which is less than 20 percent of the mean of all the values in the ‘Price’ column. This means that our algorithm made a prediction, but it needs a lot of improvement."
},
{
"code": null,
"e": 6437,
"s": 6393,
"text": "Let’s check the accuracy of our prediction."
},
{
"code": null,
"e": 6847,
"s": 6437,
"text": "# Calculate the absolute errorserrors = abs(y_pred - y_test)# Print out the mean absolute error (mae)print('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')# Calculate mean absolute percentage error (MAPE)mape = 100 * (errors / y_test)# Calculate and display accuracyaccuracy = 100 - np.mean(mape)print('Accuracy:', round(accuracy, 2), '%.')Mean Absolute Error: 1993.29 degrees.Accuracy: 87.87 %."
},
{
"code": null,
"e": 6936,
"s": 6847,
"text": "Accuracy of 87.8% is not a very great score and there is a lot of scope for improvement."
},
{
"code": null,
"e": 7006,
"s": 6936,
"text": "Let’s plot the difference between the actual and the predicted value."
},
{
"code": null,
"e": 7260,
"s": 7006,
"text": "import seaborn as snsplt.figure(figsize=(5, 7))ax = sns.distplot(y, hist=False, color=\"r\", label=\"Actual Value\")sns.distplot(y_pred, hist=False, color=\"b\", label=\"Fitted Values\" , ax=ax)plt.title('Actual vs Fitted Values for Price')plt.show()plt.close()"
},
{
"code": null,
"e": 7364,
"s": 7260,
"text": "The above is the graph between the actual and predicted values. Let’s visualize the Random Forest tree."
},
{
"code": null,
"e": 7614,
"s": 7364,
"text": "import pydot# Pull out one tree from the forestTree = regressor.estimators_[5]# Export the image to a dot filefrom sklearn import treeplt.figure(figsize=(25,15))tree.plot_tree(Tree,filled=True, rounded=True, fontsize=14);"
}
] |
ReactJS - Animation | Animation is an exciting feature of modern web application. It gives a refreshing feel to the application. React community provides many excellent react based animation library like React Motion, React Reveal, react-animations, etc., React itself provides an animation library, React Transition Group as an add-on option earlier. It is an independent library enhancing the earlier version of the library. Let us learn React Transition Group animation library in this chapter.
React Transition Group library is a simple implementation of animation. It does not do any animation out of the box. Instead, it exposes the core animation related information. Every animation is basically transition of an element from one state to another. The library exposes minimum possible state of every element and they are given below −
Entering
Entered
Exiting
Exited
The library provides options to set CSS style for each state and animate the element based on the style when the element moves from one state to another. The library provides in props to set the current state of the element. If in props value is true, then it means the element is moving from entering state to exiting state. If in props value is false, then it means the element is moving from exiting to exited.
Transition is the basic component provided by the React Transition Group to animate an element. Let us create a simple application and try to fade in / fade out an element using Transition element.
First, create a new react application, react-animation-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter.
Next, install React Transition Group library.
cd /go/to/project
npm install react-transition-group --save
Next, open the application in your favorite editor.
Next, create src folder under the root directory of the application.
Next, create components folder under src folder.
Next, create a file, HelloWorld.js under src/components folder and start editing.
Next, import React and animation library.
import React from 'react';
import { Transition } from 'react-transition-group'
Next, create the HelloWorld component.
class HelloWorld extends React.Component {
constructor(props) {
super(props);
}
}
Next, define transition related styles as JavaScript objects in the constructor.
this.duration = 2000;
this.defaultStyle = {
transition: `opacity ${this.duration}ms ease-in-out`,
opacity: 0,
}
this.transitionStyles = {
entering: { opacity: 1 },
entered: { opacity: 1 },
exiting: { opacity: 0 },
exited: { opacity: 0 },
};
Here,
defaultStyles sets the transition animation
defaultStyles sets the transition animation
transitionStyles set the styles for various states
transitionStyles set the styles for various states
Next, set the initial state for the element in the constructor.
this.state = {
inProp: true
}
Next, simulate the animation by changing the inProp values every 3 seconds.
setInterval(() => {
this.setState((state, props) => {
let newState = {
inProp: !state.inProp
};
return newState;
})
}, 3000);
Next, create a render function.
render() {
return (
);
}
Next, add Transition component. Use this.state.inProp for in prop and this.duration for timeout prop. Transition component expects a function, which returns the user interface. It is basically a Render props.
render() {
return (
<Transition in={this.state.inProp} timeout={this.duration}>
{state => ({
... component's user interface.
})
</Transition>
);
}
Next, write the components user interface inside a container and set the defaultStyle and transitionStyles for the container.
render() {
return (
<Transition in={this.state.inProp} timeout={this.duration}>
{state => (
<div style={{
...this.defaultStyle,
...this.transitionStyles[state]
}}>
<h1>Hello World!</h1>
</div>
)}
</Transition>
);
}
Finally, expose the component.
export default HelloWorld
The complete source code of the component is as follows −
import React from "react";
import { Transition } from 'react-transition-group';
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.duration = 2000;
this.defaultStyle = {
transition: `opacity ${this.duration}ms ease-in-out`,
opacity: 0,
}
this.transitionStyles = {
entering: { opacity: 1 },
entered: { opacity: 1 },
exiting: { opacity: 0 },
exited: { opacity: 0 },
};
this.state = {
inProp: true
}
setInterval(() => {
this.setState((state, props) => {
let newState = {
inProp: !state.inProp
};
return newState;
})
}, 3000);
}
render() {
return (
<Transition in={this.state.inProp} timeout={this.duration}>
{state => (
<div style={{
...this.defaultStyle,
...this.transitionStyles[state]
}}>
<h1>Hello World!</h1>
</div>
)}
</Transition>
);
}
}
export default HelloWorld;
Next, create a file, index.js under the src folder and use HelloWorld component.
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './components/HelloWorld';
ReactDOM.render(
<React.StrictMode
<HelloWorld /
</React.StrictMode ,
document.getElementById('root')
);
Finally, create a public folder under the root folder and create index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React Containment App</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
Clicking the remove link will remove the item from redux store.
CSSTransition is built on top of Transition component and it improves Transition component by introducing classNames prop. classNames prop refers the css class name used for various state of the element.
For example, classNames=hello prop refers below css classes.
.hello-enter {
opacity: 0;
}
.hello-enter-active {
opacity: 1;
transition: opacity 200ms;
}
.hello-exit {
opacity: 1;
}
.hello-exit-active {
opacity: 0;
transition: opacity 200ms;
}
Let us create a new component HelloWorldCSSTransition using CSSTransition component.
First, open our react-animation-app application in your favorite editor.
Next, create a new file, HelloWorldCSSTransition.css under src/components folder and enter transition classes.
.hello-enter {
opacity: 1;
transition: opacity 2000ms ease-in-out;
}
.hello-enter-active {
opacity: 1;
transition: opacity 2000ms ease-in-out;
}
.hello-exit {
opacity: 0;
transition: opacity 2000ms ease-in-out;
}
.hello-exit-active {
opacity: 0;
transition: opacity 2000ms ease-in-out;
}
Next, create a new file, HelloWorldCSSTransition.js under src/components folder and start editing.
Next, import React and animation library.
import React from 'react';
import { CSSTransition } from 'react-transition-group'
Next, import HelloWorldCSSTransition.css.
import './HelloWorldCSSTransition.css'
Next, create the HelloWorld component.
class HelloWorldCSSTransition extends React.Component {
constructor(props) {
super(props);
}
}
Next, define duration of the transition in the constructor.
this.duration = 2000;
Next, set the initial state for the element in the constructor.
this.state = {
inProp: true
}
Next, simulate the animation by changing the inProp values every 3 seconds.
setInterval(() => {
this.setState((state, props) => {
let newState = {
inProp: !state.inProp
};
return newState;
})
}, 3000);
Next, create a render function.
render() {
return (
);
}
Next, add CSSTransition component. Use this.state.inProp for in prop, this.duration for timeout prop and hello for classNames prop. CSSTransition component expects user interface as child prop.
render() {
return (
<CSSTransition in={this.state.inProp} timeout={this.duration}
classNames="hello">
// ... user interface code ...
</CSSTransition>
);
}
Next, write the components user interface.
render() {
return (
<CSSTransition in={this.state.inProp} timeout={this.duration}
classNames="hello">
<div>
<h1>Hello World!</h1>
</div>
</CSSTransition>
);
}
Finally, expose the component.
export default HelloWorldCSSTransition;
The complete source code of the component is given below −
import React from 'react';
import { CSSTransition } from 'react-transition-group'
import './HelloWorldCSSTransition.css'
class HelloWorldCSSTransition extends React.Component {
constructor(props) {
super(props);
this.duration = 2000;
this.state = {
inProp: true
}
setInterval(() => {
this.setState((state, props) => {
let newState = {
inProp: !state.inProp
};
return newState;
})
}, 3000);
}
render() {
return (
<CSSTransition in={this.state.inProp} timeout={this.duration}
classNames="hello">
<div>
<h1>Hello World!</h1>
</div>
</CSSTransition>
);
}
}
export default HelloWorldCSSTransition;
Next, create a file, index.js under the src folder and use HelloWorld component.
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorldCSSTransition from './components/HelloWorldCSSTransition';
ReactDOM.render(
<React.StrictMode>
<HelloWorldCSSTransition />
</React.StrictMode>,
document.getElementById('root')
);
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
The message will fade in and out for every 3 seconds.
TransitionGroup is a container component, which manages multiple transition component in a list. For example, while each item in a list use CSSTransition, TransitionGroup can be used to group all the item for proper animation.
<TransitionGroup>
{items.map(({ id, text }) => (
<CSSTransition key={id} timeout={500} classNames="item" >
<Button
onClick={() =>
setItems(items =>
items.filter(item => item.id !== id)
)
}
>
×
</Button>
{text}
</CSSTransition>
))}
</TransitionGroup>
20 Lectures
1.5 hours
Anadi Sharma
60 Lectures
4.5 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
63 Lectures
9.5 hours
TELCOMA Global
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2509,
"s": 2033,
"text": "Animation is an exciting feature of modern web application. It gives a refreshing feel to the application. React community provides many excellent react based animation library like React Motion, React Reveal, react-animations, etc., React itself provides an animation library, React Transition Group as an add-on option earlier. It is an independent library enhancing the earlier version of the library. Let us learn React Transition Group animation library in this chapter."
},
{
"code": null,
"e": 2854,
"s": 2509,
"text": "React Transition Group library is a simple implementation of animation. It does not do any animation out of the box. Instead, it exposes the core animation related information. Every animation is basically transition of an element from one state to another. The library exposes minimum possible state of every element and they are given below −"
},
{
"code": null,
"e": 2863,
"s": 2854,
"text": "Entering"
},
{
"code": null,
"e": 2871,
"s": 2863,
"text": "Entered"
},
{
"code": null,
"e": 2879,
"s": 2871,
"text": "Exiting"
},
{
"code": null,
"e": 2886,
"s": 2879,
"text": "Exited"
},
{
"code": null,
"e": 3300,
"s": 2886,
"text": "The library provides options to set CSS style for each state and animate the element based on the style when the element moves from one state to another. The library provides in props to set the current state of the element. If in props value is true, then it means the element is moving from entering state to exiting state. If in props value is false, then it means the element is moving from exiting to exited."
},
{
"code": null,
"e": 3498,
"s": 3300,
"text": "Transition is the basic component provided by the React Transition Group to animate an element. Let us create a simple application and try to fade in / fade out an element using Transition element."
},
{
"code": null,
"e": 3664,
"s": 3498,
"text": "First, create a new react application, react-animation-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter."
},
{
"code": null,
"e": 3710,
"s": 3664,
"text": "Next, install React Transition Group library."
},
{
"code": null,
"e": 3772,
"s": 3710,
"text": "cd /go/to/project \nnpm install react-transition-group --save\n"
},
{
"code": null,
"e": 3824,
"s": 3772,
"text": "Next, open the application in your favorite editor."
},
{
"code": null,
"e": 3893,
"s": 3824,
"text": "Next, create src folder under the root directory of the application."
},
{
"code": null,
"e": 3942,
"s": 3893,
"text": "Next, create components folder under src folder."
},
{
"code": null,
"e": 4024,
"s": 3942,
"text": "Next, create a file, HelloWorld.js under src/components folder and start editing."
},
{
"code": null,
"e": 4066,
"s": 4024,
"text": "Next, import React and animation library."
},
{
"code": null,
"e": 4147,
"s": 4066,
"text": "import React from 'react'; \nimport { Transition } from 'react-transition-group'\n"
},
{
"code": null,
"e": 4186,
"s": 4147,
"text": "Next, create the HelloWorld component."
},
{
"code": null,
"e": 4280,
"s": 4186,
"text": "class HelloWorld extends React.Component {\n constructor(props) {\n super(props);\n }\n}"
},
{
"code": null,
"e": 4361,
"s": 4280,
"text": "Next, define transition related styles as JavaScript objects in the constructor."
},
{
"code": null,
"e": 4620,
"s": 4361,
"text": "this.duration = 2000;\nthis.defaultStyle = {\n transition: `opacity ${this.duration}ms ease-in-out`,\n opacity: 0,\n}\nthis.transitionStyles = {\n entering: { opacity: 1 },\n entered: { opacity: 1 },\n exiting: { opacity: 0 },\n exited: { opacity: 0 },\n};"
},
{
"code": null,
"e": 4626,
"s": 4620,
"text": "Here,"
},
{
"code": null,
"e": 4670,
"s": 4626,
"text": "defaultStyles sets the transition animation"
},
{
"code": null,
"e": 4714,
"s": 4670,
"text": "defaultStyles sets the transition animation"
},
{
"code": null,
"e": 4765,
"s": 4714,
"text": "transitionStyles set the styles for various states"
},
{
"code": null,
"e": 4816,
"s": 4765,
"text": "transitionStyles set the styles for various states"
},
{
"code": null,
"e": 4880,
"s": 4816,
"text": "Next, set the initial state for the element in the constructor."
},
{
"code": null,
"e": 4915,
"s": 4880,
"text": "this.state = { \n inProp: true \n}"
},
{
"code": null,
"e": 4991,
"s": 4915,
"text": "Next, simulate the animation by changing the inProp values every 3 seconds."
},
{
"code": null,
"e": 5150,
"s": 4991,
"text": "setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n}, 3000);"
},
{
"code": null,
"e": 5182,
"s": 5150,
"text": "Next, create a render function."
},
{
"code": null,
"e": 5216,
"s": 5182,
"text": "render() { \n return ( \n ); \n}"
},
{
"code": null,
"e": 5425,
"s": 5216,
"text": "Next, add Transition component. Use this.state.inProp for in prop and this.duration for timeout prop. Transition component expects a function, which returns the user interface. It is basically a Render props."
},
{
"code": null,
"e": 5620,
"s": 5425,
"text": "render() {\n return (\n <Transition in={this.state.inProp} timeout={this.duration}>\n {state => ({\n ... component's user interface.\n })\n </Transition>\n );\n}"
},
{
"code": null,
"e": 5746,
"s": 5620,
"text": "Next, write the components user interface inside a container and set the defaultStyle and transitionStyles for the container."
},
{
"code": null,
"e": 6078,
"s": 5746,
"text": "render() {\n return (\n <Transition in={this.state.inProp} timeout={this.duration}>\n {state => (\n <div style={{\n ...this.defaultStyle,\n ...this.transitionStyles[state]\n }}>\n <h1>Hello World!</h1>\n </div>\n )}\n </Transition>\n );\n}"
},
{
"code": null,
"e": 6109,
"s": 6078,
"text": "Finally, expose the component."
},
{
"code": null,
"e": 6136,
"s": 6109,
"text": "export default HelloWorld\n"
},
{
"code": null,
"e": 6194,
"s": 6136,
"text": "The complete source code of the component is as follows −"
},
{
"code": null,
"e": 7353,
"s": 6194,
"text": "import React from \"react\";\nimport { Transition } from 'react-transition-group';\n\nclass HelloWorld extends React.Component {\n constructor(props) {\n super(props);\n this.duration = 2000;\n this.defaultStyle = {\n transition: `opacity ${this.duration}ms ease-in-out`,\n opacity: 0,\n }\n this.transitionStyles = {\n entering: { opacity: 1 },\n entered: { opacity: 1 },\n exiting: { opacity: 0 },\n exited: { opacity: 0 },\n };\n this.state = {\n inProp: true\n }\n setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n }, 3000);\n }\n render() {\n return (\n <Transition in={this.state.inProp} timeout={this.duration}>\n {state => (\n <div style={{\n ...this.defaultStyle,\n ...this.transitionStyles[state]\n }}>\n <h1>Hello World!</h1>\n </div>\n )}\n </Transition>\n );\n }\n}\nexport default HelloWorld;"
},
{
"code": null,
"e": 7434,
"s": 7353,
"text": "Next, create a file, index.js under the src folder and use HelloWorld component."
},
{
"code": null,
"e": 7674,
"s": 7434,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorld from './components/HelloWorld';\n\nReactDOM.render(\n <React.StrictMode \n <HelloWorld / \n </React.StrictMode ,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 7756,
"s": 7674,
"text": "Finally, create a public folder under the root folder and create index.html file."
},
{
"code": null,
"e": 8003,
"s": 7756,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React Containment App</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 8050,
"s": 8003,
"text": "Next, serve the application using npm command."
},
{
"code": null,
"e": 8061,
"s": 8050,
"text": "npm start\n"
},
{
"code": null,
"e": 8152,
"s": 8061,
"text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter."
},
{
"code": null,
"e": 8216,
"s": 8152,
"text": "Clicking the remove link will remove the item from redux store."
},
{
"code": null,
"e": 8420,
"s": 8216,
"text": "CSSTransition is built on top of Transition component and it improves Transition component by introducing classNames prop. classNames prop refers the css class name used for various state of the element."
},
{
"code": null,
"e": 8481,
"s": 8420,
"text": "For example, classNames=hello prop refers below css classes."
},
{
"code": null,
"e": 8681,
"s": 8481,
"text": ".hello-enter {\n opacity: 0;\n}\n.hello-enter-active {\n opacity: 1;\n transition: opacity 200ms;\n}\n.hello-exit {\n opacity: 1;\n}\n.hello-exit-active {\n opacity: 0;\n transition: opacity 200ms;\n}"
},
{
"code": null,
"e": 8766,
"s": 8681,
"text": "Let us create a new component HelloWorldCSSTransition using CSSTransition component."
},
{
"code": null,
"e": 8839,
"s": 8766,
"text": "First, open our react-animation-app application in your favorite editor."
},
{
"code": null,
"e": 8950,
"s": 8839,
"text": "Next, create a new file, HelloWorldCSSTransition.css under src/components folder and enter transition classes."
},
{
"code": null,
"e": 9262,
"s": 8950,
"text": ".hello-enter {\n opacity: 1;\n transition: opacity 2000ms ease-in-out;\n}\n.hello-enter-active {\n opacity: 1;\n transition: opacity 2000ms ease-in-out;\n}\n.hello-exit {\n opacity: 0;\n transition: opacity 2000ms ease-in-out;\n}\n.hello-exit-active {\n opacity: 0;\n transition: opacity 2000ms ease-in-out;\n}"
},
{
"code": null,
"e": 9361,
"s": 9262,
"text": "Next, create a new file, HelloWorldCSSTransition.js under src/components folder and start editing."
},
{
"code": null,
"e": 9403,
"s": 9361,
"text": "Next, import React and animation library."
},
{
"code": null,
"e": 9486,
"s": 9403,
"text": "import React from 'react'; \nimport { CSSTransition } from 'react-transition-group'"
},
{
"code": null,
"e": 9528,
"s": 9486,
"text": "Next, import HelloWorldCSSTransition.css."
},
{
"code": null,
"e": 9567,
"s": 9528,
"text": "import './HelloWorldCSSTransition.css'"
},
{
"code": null,
"e": 9606,
"s": 9567,
"text": "Next, create the HelloWorld component."
},
{
"code": null,
"e": 9713,
"s": 9606,
"text": "class HelloWorldCSSTransition extends React.Component {\n constructor(props) {\n super(props);\n }\n}"
},
{
"code": null,
"e": 9773,
"s": 9713,
"text": "Next, define duration of the transition in the constructor."
},
{
"code": null,
"e": 9796,
"s": 9773,
"text": "this.duration = 2000;\n"
},
{
"code": null,
"e": 9860,
"s": 9796,
"text": "Next, set the initial state for the element in the constructor."
},
{
"code": null,
"e": 9895,
"s": 9860,
"text": "this.state = { \n inProp: true \n}"
},
{
"code": null,
"e": 9971,
"s": 9895,
"text": "Next, simulate the animation by changing the inProp values every 3 seconds."
},
{
"code": null,
"e": 10130,
"s": 9971,
"text": "setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n}, 3000);"
},
{
"code": null,
"e": 10162,
"s": 10130,
"text": "Next, create a render function."
},
{
"code": null,
"e": 10195,
"s": 10162,
"text": "render() { \n return (\n ); \n}"
},
{
"code": null,
"e": 10389,
"s": 10195,
"text": "Next, add CSSTransition component. Use this.state.inProp for in prop, this.duration for timeout prop and hello for classNames prop. CSSTransition component expects user interface as child prop."
},
{
"code": null,
"e": 10584,
"s": 10389,
"text": "render() {\n return (\n <CSSTransition in={this.state.inProp} timeout={this.duration} \n classNames=\"hello\">\n // ... user interface code ... \n </CSSTransition>\n );\n}"
},
{
"code": null,
"e": 10627,
"s": 10584,
"text": "Next, write the components user interface."
},
{
"code": null,
"e": 10835,
"s": 10627,
"text": "render() {\n return (\n <CSSTransition in={this.state.inProp} timeout={this.duration} \n classNames=\"hello\">\n <div>\n <h1>Hello World!</h1>\n </div>\n </CSSTransition>\n );\n}"
},
{
"code": null,
"e": 10866,
"s": 10835,
"text": "Finally, expose the component."
},
{
"code": null,
"e": 10907,
"s": 10866,
"text": "export default HelloWorldCSSTransition;\n"
},
{
"code": null,
"e": 10966,
"s": 10907,
"text": "The complete source code of the component is given below −"
},
{
"code": null,
"e": 11769,
"s": 10966,
"text": "import React from 'react';\nimport { CSSTransition } from 'react-transition-group'\nimport './HelloWorldCSSTransition.css' \n\nclass HelloWorldCSSTransition extends React.Component {\n constructor(props) {\n super(props);\n this.duration = 2000;\n this.state = {\n inProp: true\n }\n setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n }, 3000);\n }\n render() {\n return (\n <CSSTransition in={this.state.inProp} timeout={this.duration} \n classNames=\"hello\">\n <div>\n <h1>Hello World!</h1>\n </div>\n </CSSTransition>\n );\n }\n}\nexport default HelloWorldCSSTransition;"
},
{
"code": null,
"e": 11850,
"s": 11769,
"text": "Next, create a file, index.js under the src folder and use HelloWorld component."
},
{
"code": null,
"e": 12123,
"s": 11850,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorldCSSTransition from './components/HelloWorldCSSTransition';\n\nReactDOM.render(\n <React.StrictMode>\n <HelloWorldCSSTransition />\n </React.StrictMode>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 12170,
"s": 12123,
"text": "Next, serve the application using npm command."
},
{
"code": null,
"e": 12181,
"s": 12170,
"text": "npm start\n"
},
{
"code": null,
"e": 12272,
"s": 12181,
"text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter."
},
{
"code": null,
"e": 12326,
"s": 12272,
"text": "The message will fade in and out for every 3 seconds."
},
{
"code": null,
"e": 12553,
"s": 12326,
"text": "TransitionGroup is a container component, which manages multiple transition component in a list. For example, while each item in a list use CSSTransition, TransitionGroup can be used to group all the item for proper animation."
},
{
"code": null,
"e": 12950,
"s": 12553,
"text": "<TransitionGroup>\n {items.map(({ id, text }) => (\n <CSSTransition key={id} timeout={500} classNames=\"item\" >\n <Button\n onClick={() =>\n setItems(items =>\n items.filter(item => item.id !== id)\n )\n }\n >\n ×\n </Button>\n {text}\n </CSSTransition>\n ))}\n</TransitionGroup>"
},
{
"code": null,
"e": 12985,
"s": 12950,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12999,
"s": 12985,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 13034,
"s": 12999,
"text": "\n 60 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13054,
"s": 13034,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 13089,
"s": 13054,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 13112,
"s": 13089,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 13147,
"s": 13112,
"text": "\n 63 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 13163,
"s": 13147,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 13196,
"s": 13163,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13214,
"s": 13196,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 13221,
"s": 13214,
"text": " Print"
},
{
"code": null,
"e": 13232,
"s": 13221,
"text": " Add Notes"
}
] |
Check if any King is unsafe on the Chessboard or not - GeeksforGeeks | 18 Oct, 2021
Given a matrix board[][] consisting of the characters K or k, Q or q, B or b, N or n, R or r, and P or p (Upper case white and lower case black) representing the King, the Queen, the Bishop, the Knight, the Rook, and Pawns of Black and White color respectively, and empty spaces indicated by ‘-‘, the task is to check which king (black of white) is unsafe, i.e. if it is under attack (can be eliminated) by any of the other pieces and print the answer accordingly. Note: If both kings are safe then output “No King in danger”.Examples:
Input:
board[][] = {{- - - k - - - -},
{p p p - p p p p},
{- - - - - b - -},
{- - - R - - - -},
{- - - - - - - -},
{- - - - - - - -},
{P - P P P P P P},
{K - - - - - - - }}
Output:White King in danger
Explanation: Black bishop can attack the white king.
Input:
board[][] = {{- - k - - - - -},
{p p p - p p p p},
{- - - - - - b -},
{- - - R - - - -},
{- - - - - - - -},
{- - - - - - - -}
{P - P P P P P P},
{K - - - - - - -}}
Output: No King in danger
Approach: The approach is to check the moves of each and every piece on the chessboard:
Check for the position of both white and black kings.For each king, check Rook, bishops, knight, king, Queen, Pawn of the opposite color, whether they are attacking the king or not.Checking for attack by the queen is a combination of checking attacks by rooks and bishops. If any of the conditions are true then the queen will attack.If none of the attack conditions are satisfied for any of the two kings, then there is no danger to both the king.Otherwise, print the answer for the king whose unsafe condition is satisfied.
Check for the position of both white and black kings.
For each king, check Rook, bishops, knight, king, Queen, Pawn of the opposite color, whether they are attacking the king or not.
Checking for attack by the queen is a combination of checking attacks by rooks and bishops. If any of the conditions are true then the queen will attack.
If none of the attack conditions are satisfied for any of the two kings, then there is no danger to both the king.
Otherwise, print the answer for the king whose unsafe condition is satisfied.
Below is the implementation of this approach.
C++
Java
Python3
C#
Javascript
// C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Check if the indices// are within the matrix// or notbool inBounds(int i, int j){ // Checking boundary // conditions return i >= 0 && i < 8 && j >= 0 && j < 8;} bool lookFork(char board[][8], char c, int i, int j){ // Store all possible moves // of the king int x[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int y[] = {-1, 0, 1, -1, 1, -1, 0, 1}; for (int k = 0; k < 8; k++) { // incrementing index // values int m = i + x[k]; int n = j + y[k]; // checking boundary // conditions and // character match if (inBounds(m, n) && board[m][n] == c) return true; } return false;} // Function to check if bishop// can attack the kingbool lookForb(char board[][8], char c, int i, int j){ // Check the lower right // diagonal int k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k][j + k] == c) return true; if (board[i + k][j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k][j - k] == c) return true; if (board[i + k][j - k] != '-') break; } // Check the upper right // diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k][j + k] == c) return true; if (board[i - k][j + k] != '-') break; } // Check the upper left // diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k][j - k] == c) return true; if (board[i - k][j - k] != '-') break; } return false;} // Check ifbool lookForr(char board[][8], char c, int i, int j){ // Check downwards int k = 0; while (inBounds(i + ++k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } return false;} // Function to check if Queen// can attack the Kingbool lookForq(char board[][8], char c, int i, int j){ // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false;} // Check if the knight can// attack the kingbool lookForn(char board[][8], char c, int i, int j){ // All possible moves of // the knight int x[] = {2, 2, -2, -2, 1, 1, -1, -1}; int y[] = {1, -1, 1, -1, 2, -2, 2, -2}; for (int k = 0; k < 8; k++) { // Incrementing index // values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false;} // Function to check if pawn// can attack the kingbool lookForp(char board[][8], char c, int i, int j){ char lookFor; if (isupper(c)) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1][j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1][j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1][j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1][j + 1] == lookFor) return true; } return false;} // Function to check if any// of the two kings is unsafe// or notint checkBoard(char board[][8]){ // Find the position of both // the kings for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i][j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i][j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0;} // Driver Codeint main(){ // Chessboard instance char board[][8] = {{'-', '-', '-', 'k', '-', '-', '-', '-'}, {'p', 'p', 'p', '-', 'p', 'p', 'p', 'p'}, {'-', '-', '-', '-', '-', 'b', '-', '-'}, { '-', '-', '-', 'R', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-', '-'}, {'P', '-', 'P', 'P', 'P', 'P', 'P', 'P'}, {'K', '-', '-', '-', '-', '-', '-', '-'}}; if (checkBoard(board) == 0) cout << ("No king in danger"); else if (checkBoard(board) == 1) cout << ("White king in danger"); else cout << ("Black king in danger");} // This code is contributed by Chitranyal
public class Gfg { // Function to check if any of the two // kings is unsafe or not private static int checkBoard(char[][] board) { // Find the position of both the kings for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i][j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i][j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0; } private static boolean lookFork(char[][] board, char c, int i, int j) { // Store all possible moves of the king int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 }; for (int k = 0; k < 8; k++) { // incrementing index values int m = i + x[k]; int n = j + y[k]; // checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if Queen can attack the King private static boolean lookForq(char[][] board, char c, int i, int j) { // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false; } // Function to check if bishop can attack the king private static boolean lookForb(char[][] board, char c, int i, int j) { // Check the lower right diagonal int k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k][j + k] == c) return true; if (board[i + k][j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k][j - k] == c) return true; if (board[i + k][j - k] != '-') break; } // Check the upper right diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k][j + k] == c) return true; if (board[i - k][j + k] != '-') break; } // Check the upper left diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k][j - k] == c) return true; if (board[i - k][j - k] != '-') break; } return false; } // Check if private static boolean lookForr(char[][] board, char c, int i, int j) { // Check downwards int k = 0; while (inBounds(i + ++k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } return false; } // Check if the knight can attack the king private static boolean lookForn(char[][] board, char c, int i, int j) { // All possible moves of the knight int[] x = { 2, 2, -2, -2, 1, 1, -1, -1 }; int[] y = { 1, -1, 1, -1, 2, -2, 2, -2 }; for (int k = 0; k < 8; k++) { // Incrementing index values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if pawn can attack the king private static boolean lookForp(char[][] board, char c, int i, int j) { char lookFor; if (Character.isUpperCase(c)) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1][j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1][j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1][j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1][j + 1] == lookFor) return true; } return false; } // Check if the indices are within // the matrix or not private static boolean inBounds(int i, int j) { // Checking boundary conditions return i >= 0 && i < 8 && j >= 0 && j < 8; } // Driver Code public static void main(String[] args) { // Chessboard instance char[][] board = { { '-', '-', '-', 'k', '-', '-', '-', '-' }, { 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' }, { '-', '-', '-', '-', '-', 'b', '-', '-' }, { '-', '-', '-', 'R', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' }, { 'K', '-', '-', '-', '-', '-', '-', '-' } }; if (checkBoard(board) == 0) System.out.println("No king in danger"); else if (checkBoard(board) == 1) System.out.println("White king in danger"); else System.out.println("Black king in danger"); }}
# Python3 program to implement the above approach # Function to check if any of the two# kings is unsafe or notdef checkBoard(board): # Find the position of both the kings for i in range(8): for j in range(8): # Check for all pieces which # can attack White King if board[i][j] == 'k': # Check for Knight if lookForn(board, 'N', i, j): return 1 # Check for Pawn if lookForp(board, 'P', i, j): return 1 # Check for Rook if lookForr(board, 'R', i, j): return 1 # Check for Bishop if lookForb(board, 'B', i, j): return 1 # Check for Queen if lookForq(board, 'Q', i, j): return 1 # Check for King if lookFork(board, 'K', i, j): return 1 # Check for all pieces which # can attack Black King if board[i][j] == 'K': # Check for Knight if lookForn(board, 'n', i, j): return 2 # Check for Pawn if lookForp(board, 'p', i, j): return 2 # Check for Rook if lookForr(board, 'r', i, j): return 2 # Check for Bishop if lookForb(board, 'b', i, j): return 2 # Check for Queen if lookForq(board, 'q', i, j): return 2 # Check for King if lookFork(board, 'k', i, j): return 2 return 1 def lookFork(board, c, i, j): # Store all possible moves of the king x = [ -1, -1, -1, 0, 0, 1, 1, 1 ] y = [ -1, 0, 1, -1, 1, -1, 0, 1 ] for k in range(8): # incrementing index values m = i + x[k] n = j + y[k] # checking boundary conditions # and character match if inBounds(m, n) and board[m][n] == c: return True return False # Function to check if Queen can attack the Kingdef lookForq(board, c, i, j): # Queen's moves are a combination # of both the Bishop and the Rook if lookForb(board, c, i, j) or lookForr(board, c, i, j): return True return False # Function to check if bishop can attack the kingdef lookForb(board, c, i, j): # Check the lower right diagonal k = 0 while inBounds(i + ++k, j + k): if board[i + k][j + k] == c: return True if board[i + k][j + k] != '-': break # Check the lower left diagonal k = 0 while inBounds(i + ++k, j - k): if board[i + k][j - k] == c: return True if board[i + k][j - k] != '-': break # Check the upper right diagonal k = 0 while inBounds(i - ++k, j + k): if board[i - k][j + k] == c: return True if board[i - k][j + k] != '-': break # Check the upper left diagonal k = 0 while inBounds(i - ++k, j - k): if board[i - k][j - k] == c: return True if board[i - k][j - k] != '-': break return False # Check ifdef lookForr(board, c, i, j): # Check downwards k = 0 while inBounds(i + ++k, j): if board[i + k][j] == c: return True if board[i + k][j] != '-': break # Check upwards k = 0 while inBounds(i + --k, j): if board[i + k][j] == c: return True if board[i + k][j] != '-': break # Check right k = 0 while inBounds(i, j + ++k): if board[i][j + k] == c: return True if board[i][j + k] != '-': break # Check left k = 0 while inBounds(i, j + --k): if board[i][j + k] == c: return True if board[i][j + k] != '-': break return False # Check if the knight can attack the kingdef lookForn(board, c, i, j): # All possible moves of the knight x = [ 2, 2, -2, -2, 1, 1, -1, -1 ] y = [ 1, -1, 1, -1, 2, -2, 2, -2 ] for k in range(8): # Incrementing index values m = i + x[k] n = j + y[k] # Checking boundary conditions # and character match if inBounds(m, n) and board[m][n] == c: return True return False # Function to check if pawn can attack the kingdef lookForp(board, c, i, j): if ord(c) >= 65 and ord(c) <= 90: # Check for white pawn lookFor = 'P' if inBounds(i + 1, j - 1) and board[i + 1][j - 1] == lookFor: return True if inBounds(i + 1, j + 1) and board[i + 1][j + 1] == lookFor: return True else: # Check for black pawn lookFor = 'p' if inBounds(i - 1, j - 1) and board[i - 1][j - 1] == lookFor: return True if inBounds(i - 1, j + 1) and board[i - 1][j + 1] == lookFor: return True return False # Check if the indices are within# the matrix or notdef inBounds(i, j): # Checking boundary conditions return i >= 0 and i < 8 and j >= 0 and j < 8 # Chessboard instanceboard = [ [ '-', '-', '-', 'k', '-', '-', '-', '-' ], [ 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' ], [ '-', '-', '-', '-', '-', 'b', '-', '-' ], [ '-', '-', '-', 'R', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' ], [ 'K', '-', '-', '-', '-', '-', '-', '-' ] ] if checkBoard(board) == 0: print("No king in danger")elif checkBoard(board) == 1: print("White king in danger")else: print("Black king in danger") # This code is contributed by divyeshrabadiya07.
using System; class GFG{ // Function to check if any of the two// kings is unsafe or notprivate static int checkBoard(char[,] board){ // Find the position of both the kings for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i, j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i, j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0;} private static bool lookFork(char[,] board, char c, int i, int j){ // Store all possible moves of the king int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 }; for(int k = 0; k < 8; k++) { // Incrementing index values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m, n] == c) return true; } return false;} // Function to check if Queen can attack the Kingprivate static bool lookForq(char[,] board, char c, int i, int j){ // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false;} // Function to check if bishop can attack the kingprivate static bool lookForb(char[,] board, char c, int i, int j){ // Check the lower right diagonal int k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k, j + k] == c) return true; if (board[i + k, j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k, j - k] == c) return true; if (board[i + k, j - k] != '-') break; } // Check the upper right diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k, j + k] == c) return true; if (board[i - k, j + k] != '-') break; } // Check the upper left diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k, j - k] == c) return true; if (board[i - k, j - k] != '-') break; } return false;} // Check ifprivate static bool lookForr(char[,] board, char c, int i, int j){ // Check downwards int k = 0; while (inBounds(i + ++k, j)) { if (board[i + k, j] == c) return true; if (board[i + k, j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k, j] == c) return true; if (board[i + k, j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i, j + k] == c) return true; if (board[i, j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i, j + k] == c) return true; if (board[i, j + k] != '-') break; } return false;} // Check if the knight can attack the kingprivate static bool lookForn(char[,] board, char c, int i, int j){ // All possible moves of the knight int[] x = { 2, 2, -2, -2, 1, 1, -1, -1 }; int[] y = { 1, -1, 1, -1, 2, -2, 2, -2 }; for(int k = 0; k < 8; k++) { // Incrementing index values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m, n] == c) return true; } return false;} // Function to check if pawn can attack the kingprivate static bool lookForp(char[,] board, char c, int i, int j){ char lookFor; if (char.IsUpper(c)) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1, j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1, j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1, j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1, j + 1] == lookFor) return true; } return false;} // Check if the indices are within// the matrix or notprivate static bool inBounds(int i, int j){ // Checking boundary conditions return i >= 0 && i < 8 && j >= 0 && j < 8;} // Driver Codepublic static void Main(String[] args){ // Chessboard instance char[,] board = { { '-', '-', '-', 'k', '-', '-', '-', '-' }, { 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' }, { '-', '-', '-', '-', '-', 'b', '-', '-' }, { '-', '-', '-', 'R', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' }, { 'K', '-', '-', '-', '-', '-', '-', '-' } }; if (checkBoard(board) == 0) Console.WriteLine("No king in danger"); else if (checkBoard(board) == 1) Console.WriteLine("White king in danger"); else Console.WriteLine("Black king in danger");}} // This code is contributed by 29AjayKumar
<script> // Javascript program to implement the above approach // Function to check if any of the two // kings is unsafe or not function checkBoard(board) { // Find the position of both the kings for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i][j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i][j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0; } function lookFork(board, c, i, j) { // Store all possible moves of the king let x = [ -1, -1, -1, 0, 0, 1, 1, 1 ]; let y = [ -1, 0, 1, -1, 1, -1, 0, 1 ]; for (let k = 0; k < 8; k++) { // incrementing index values let m = i + x[k]; let n = j + y[k]; // checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if Queen can attack the King function lookForq(board, c, i, j) { // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false; } // Function to check if bishop can attack the king function lookForb(board, c, i, j) { // Check the lower right diagonal let k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k][j + k] == c) return true; if (board[i + k][j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k][j - k] == c) return true; if (board[i + k][j - k] != '-') break; } // Check the upper right diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k][j + k] == c) return true; if (board[i - k][j + k] != '-') break; } // Check the upper left diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k][j - k] == c) return true; if (board[i - k][j - k] != '-') break; } return false; } // Check if function lookForr(board, c, i, j) { // Check downwards let k = 0; while (inBounds(i + ++k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } return false; } // Check if the knight can attack the king function lookForn(board, c, i, j) { // All possible moves of the knight let x = [ 2, 2, -2, -2, 1, 1, -1, -1 ]; let y = [ 1, -1, 1, -1, 2, -2, 2, -2 ]; for (let k = 0; k < 8; k++) { // Incrementing index values let m = i + x[k]; let n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if pawn can attack the king function lookForp(board, c, i, j) { let lookFor; if (c.charCodeAt() >= 65 && c.charCodeAt() <= 90) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1][j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1][j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1][j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1][j + 1] == lookFor) return true; } return false; } // Check if the indices are within // the matrix or not function inBounds(i, j) { // Checking boundary conditions return i >= 0 && i < 8 && j >= 0 && j < 8; } // Chessboard instance let board = [ [ '-', '-', '-', 'k', '-', '-', '-', '-' ], [ 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' ], [ '-', '-', '-', '-', '-', 'b', '-', '-' ], [ '-', '-', '-', 'R', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' ], [ 'K', '-', '-', '-', '-', '-', '-', '-' ] ]; if (checkBoard(board) == 0) document.write("No king in danger"); else if (checkBoard(board) == 1) document.write("White king in danger"); else document.write("Black king in danger"); // This code is contributed by divyesh072019.</script>
White king in danger
Time Complexity: O(N3) Auxiliary Space: O(1)
29AjayKumar
ukasp
divyesh072019
divyeshrabadiya07
BFS
chessboard-problems
Backtracking
Graph
Matrix
Recursion
Recursion
Matrix
Graph
Backtracking
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tug of War
Find if there is a path of more than k length from a source
Difference between Backtracking and Branch-N-Bound technique
Find shortest safe route in a path with landmines
Print all possible strings that can be made by placing spaces
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 | [
{
"code": null,
"e": 24982,
"s": 24954,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 25519,
"s": 24982,
"text": "Given a matrix board[][] consisting of the characters K or k, Q or q, B or b, N or n, R or r, and P or p (Upper case white and lower case black) representing the King, the Queen, the Bishop, the Knight, the Rook, and Pawns of Black and White color respectively, and empty spaces indicated by ‘-‘, the task is to check which king (black of white) is unsafe, i.e. if it is under attack (can be eliminated) by any of the other pieces and print the answer accordingly. Note: If both kings are safe then output “No King in danger”.Examples: "
},
{
"code": null,
"e": 26167,
"s": 25519,
"text": "Input: \nboard[][] = {{- - - k - - - -}, \n {p p p - p p p p}, \n {- - - - - b - -}, \n {- - - R - - - -}, \n {- - - - - - - -}, \n {- - - - - - - -}, \n {P - P P P P P P}, \n {K - - - - - - - }}\nOutput:White King in danger\nExplanation: Black bishop can attack the white king.\n\nInput:\nboard[][] = {{- - k - - - - -}, \n {p p p - p p p p}, \n {- - - - - - b -}, \n {- - - R - - - -}, \n {- - - - - - - -}, \n {- - - - - - - -}\n {P - P P P P P P}, \n {K - - - - - - -}}\nOutput: No King in danger"
},
{
"code": null,
"e": 26257,
"s": 26167,
"text": "Approach: The approach is to check the moves of each and every piece on the chessboard: "
},
{
"code": null,
"e": 26783,
"s": 26257,
"text": "Check for the position of both white and black kings.For each king, check Rook, bishops, knight, king, Queen, Pawn of the opposite color, whether they are attacking the king or not.Checking for attack by the queen is a combination of checking attacks by rooks and bishops. If any of the conditions are true then the queen will attack.If none of the attack conditions are satisfied for any of the two kings, then there is no danger to both the king.Otherwise, print the answer for the king whose unsafe condition is satisfied."
},
{
"code": null,
"e": 26837,
"s": 26783,
"text": "Check for the position of both white and black kings."
},
{
"code": null,
"e": 26966,
"s": 26837,
"text": "For each king, check Rook, bishops, knight, king, Queen, Pawn of the opposite color, whether they are attacking the king or not."
},
{
"code": null,
"e": 27120,
"s": 26966,
"text": "Checking for attack by the queen is a combination of checking attacks by rooks and bishops. If any of the conditions are true then the queen will attack."
},
{
"code": null,
"e": 27235,
"s": 27120,
"text": "If none of the attack conditions are satisfied for any of the two kings, then there is no danger to both the king."
},
{
"code": null,
"e": 27313,
"s": 27235,
"text": "Otherwise, print the answer for the king whose unsafe condition is satisfied."
},
{
"code": null,
"e": 27359,
"s": 27313,
"text": "Below is the implementation of this approach."
},
{
"code": null,
"e": 27363,
"s": 27359,
"text": "C++"
},
{
"code": null,
"e": 27368,
"s": 27363,
"text": "Java"
},
{
"code": null,
"e": 27376,
"s": 27368,
"text": "Python3"
},
{
"code": null,
"e": 27379,
"s": 27376,
"text": "C#"
},
{
"code": null,
"e": 27390,
"s": 27379,
"text": "Javascript"
},
{
"code": "// C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Check if the indices// are within the matrix// or notbool inBounds(int i, int j){ // Checking boundary // conditions return i >= 0 && i < 8 && j >= 0 && j < 8;} bool lookFork(char board[][8], char c, int i, int j){ // Store all possible moves // of the king int x[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int y[] = {-1, 0, 1, -1, 1, -1, 0, 1}; for (int k = 0; k < 8; k++) { // incrementing index // values int m = i + x[k]; int n = j + y[k]; // checking boundary // conditions and // character match if (inBounds(m, n) && board[m][n] == c) return true; } return false;} // Function to check if bishop// can attack the kingbool lookForb(char board[][8], char c, int i, int j){ // Check the lower right // diagonal int k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k][j + k] == c) return true; if (board[i + k][j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k][j - k] == c) return true; if (board[i + k][j - k] != '-') break; } // Check the upper right // diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k][j + k] == c) return true; if (board[i - k][j + k] != '-') break; } // Check the upper left // diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k][j - k] == c) return true; if (board[i - k][j - k] != '-') break; } return false;} // Check ifbool lookForr(char board[][8], char c, int i, int j){ // Check downwards int k = 0; while (inBounds(i + ++k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } return false;} // Function to check if Queen// can attack the Kingbool lookForq(char board[][8], char c, int i, int j){ // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false;} // Check if the knight can// attack the kingbool lookForn(char board[][8], char c, int i, int j){ // All possible moves of // the knight int x[] = {2, 2, -2, -2, 1, 1, -1, -1}; int y[] = {1, -1, 1, -1, 2, -2, 2, -2}; for (int k = 0; k < 8; k++) { // Incrementing index // values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false;} // Function to check if pawn// can attack the kingbool lookForp(char board[][8], char c, int i, int j){ char lookFor; if (isupper(c)) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1][j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1][j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1][j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1][j + 1] == lookFor) return true; } return false;} // Function to check if any// of the two kings is unsafe// or notint checkBoard(char board[][8]){ // Find the position of both // the kings for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i][j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i][j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0;} // Driver Codeint main(){ // Chessboard instance char board[][8] = {{'-', '-', '-', 'k', '-', '-', '-', '-'}, {'p', 'p', 'p', '-', 'p', 'p', 'p', 'p'}, {'-', '-', '-', '-', '-', 'b', '-', '-'}, { '-', '-', '-', 'R', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-', '-'}, {'P', '-', 'P', 'P', 'P', 'P', 'P', 'P'}, {'K', '-', '-', '-', '-', '-', '-', '-'}}; if (checkBoard(board) == 0) cout << (\"No king in danger\"); else if (checkBoard(board) == 1) cout << (\"White king in danger\"); else cout << (\"Black king in danger\");} // This code is contributed by Chitranyal",
"e": 33900,
"s": 27390,
"text": null
},
{
"code": "public class Gfg { // Function to check if any of the two // kings is unsafe or not private static int checkBoard(char[][] board) { // Find the position of both the kings for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i][j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i][j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0; } private static boolean lookFork(char[][] board, char c, int i, int j) { // Store all possible moves of the king int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 }; for (int k = 0; k < 8; k++) { // incrementing index values int m = i + x[k]; int n = j + y[k]; // checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if Queen can attack the King private static boolean lookForq(char[][] board, char c, int i, int j) { // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false; } // Function to check if bishop can attack the king private static boolean lookForb(char[][] board, char c, int i, int j) { // Check the lower right diagonal int k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k][j + k] == c) return true; if (board[i + k][j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k][j - k] == c) return true; if (board[i + k][j - k] != '-') break; } // Check the upper right diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k][j + k] == c) return true; if (board[i - k][j + k] != '-') break; } // Check the upper left diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k][j - k] == c) return true; if (board[i - k][j - k] != '-') break; } return false; } // Check if private static boolean lookForr(char[][] board, char c, int i, int j) { // Check downwards int k = 0; while (inBounds(i + ++k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } return false; } // Check if the knight can attack the king private static boolean lookForn(char[][] board, char c, int i, int j) { // All possible moves of the knight int[] x = { 2, 2, -2, -2, 1, 1, -1, -1 }; int[] y = { 1, -1, 1, -1, 2, -2, 2, -2 }; for (int k = 0; k < 8; k++) { // Incrementing index values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if pawn can attack the king private static boolean lookForp(char[][] board, char c, int i, int j) { char lookFor; if (Character.isUpperCase(c)) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1][j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1][j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1][j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1][j + 1] == lookFor) return true; } return false; } // Check if the indices are within // the matrix or not private static boolean inBounds(int i, int j) { // Checking boundary conditions return i >= 0 && i < 8 && j >= 0 && j < 8; } // Driver Code public static void main(String[] args) { // Chessboard instance char[][] board = { { '-', '-', '-', 'k', '-', '-', '-', '-' }, { 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' }, { '-', '-', '-', '-', '-', 'b', '-', '-' }, { '-', '-', '-', 'R', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' }, { 'K', '-', '-', '-', '-', '-', '-', '-' } }; if (checkBoard(board) == 0) System.out.println(\"No king in danger\"); else if (checkBoard(board) == 1) System.out.println(\"White king in danger\"); else System.out.println(\"Black king in danger\"); }}",
"e": 41668,
"s": 33900,
"text": null
},
{
"code": "# Python3 program to implement the above approach # Function to check if any of the two# kings is unsafe or notdef checkBoard(board): # Find the position of both the kings for i in range(8): for j in range(8): # Check for all pieces which # can attack White King if board[i][j] == 'k': # Check for Knight if lookForn(board, 'N', i, j): return 1 # Check for Pawn if lookForp(board, 'P', i, j): return 1 # Check for Rook if lookForr(board, 'R', i, j): return 1 # Check for Bishop if lookForb(board, 'B', i, j): return 1 # Check for Queen if lookForq(board, 'Q', i, j): return 1 # Check for King if lookFork(board, 'K', i, j): return 1 # Check for all pieces which # can attack Black King if board[i][j] == 'K': # Check for Knight if lookForn(board, 'n', i, j): return 2 # Check for Pawn if lookForp(board, 'p', i, j): return 2 # Check for Rook if lookForr(board, 'r', i, j): return 2 # Check for Bishop if lookForb(board, 'b', i, j): return 2 # Check for Queen if lookForq(board, 'q', i, j): return 2 # Check for King if lookFork(board, 'k', i, j): return 2 return 1 def lookFork(board, c, i, j): # Store all possible moves of the king x = [ -1, -1, -1, 0, 0, 1, 1, 1 ] y = [ -1, 0, 1, -1, 1, -1, 0, 1 ] for k in range(8): # incrementing index values m = i + x[k] n = j + y[k] # checking boundary conditions # and character match if inBounds(m, n) and board[m][n] == c: return True return False # Function to check if Queen can attack the Kingdef lookForq(board, c, i, j): # Queen's moves are a combination # of both the Bishop and the Rook if lookForb(board, c, i, j) or lookForr(board, c, i, j): return True return False # Function to check if bishop can attack the kingdef lookForb(board, c, i, j): # Check the lower right diagonal k = 0 while inBounds(i + ++k, j + k): if board[i + k][j + k] == c: return True if board[i + k][j + k] != '-': break # Check the lower left diagonal k = 0 while inBounds(i + ++k, j - k): if board[i + k][j - k] == c: return True if board[i + k][j - k] != '-': break # Check the upper right diagonal k = 0 while inBounds(i - ++k, j + k): if board[i - k][j + k] == c: return True if board[i - k][j + k] != '-': break # Check the upper left diagonal k = 0 while inBounds(i - ++k, j - k): if board[i - k][j - k] == c: return True if board[i - k][j - k] != '-': break return False # Check ifdef lookForr(board, c, i, j): # Check downwards k = 0 while inBounds(i + ++k, j): if board[i + k][j] == c: return True if board[i + k][j] != '-': break # Check upwards k = 0 while inBounds(i + --k, j): if board[i + k][j] == c: return True if board[i + k][j] != '-': break # Check right k = 0 while inBounds(i, j + ++k): if board[i][j + k] == c: return True if board[i][j + k] != '-': break # Check left k = 0 while inBounds(i, j + --k): if board[i][j + k] == c: return True if board[i][j + k] != '-': break return False # Check if the knight can attack the kingdef lookForn(board, c, i, j): # All possible moves of the knight x = [ 2, 2, -2, -2, 1, 1, -1, -1 ] y = [ 1, -1, 1, -1, 2, -2, 2, -2 ] for k in range(8): # Incrementing index values m = i + x[k] n = j + y[k] # Checking boundary conditions # and character match if inBounds(m, n) and board[m][n] == c: return True return False # Function to check if pawn can attack the kingdef lookForp(board, c, i, j): if ord(c) >= 65 and ord(c) <= 90: # Check for white pawn lookFor = 'P' if inBounds(i + 1, j - 1) and board[i + 1][j - 1] == lookFor: return True if inBounds(i + 1, j + 1) and board[i + 1][j + 1] == lookFor: return True else: # Check for black pawn lookFor = 'p' if inBounds(i - 1, j - 1) and board[i - 1][j - 1] == lookFor: return True if inBounds(i - 1, j + 1) and board[i - 1][j + 1] == lookFor: return True return False # Check if the indices are within# the matrix or notdef inBounds(i, j): # Checking boundary conditions return i >= 0 and i < 8 and j >= 0 and j < 8 # Chessboard instanceboard = [ [ '-', '-', '-', 'k', '-', '-', '-', '-' ], [ 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' ], [ '-', '-', '-', '-', '-', 'b', '-', '-' ], [ '-', '-', '-', 'R', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' ], [ 'K', '-', '-', '-', '-', '-', '-', '-' ] ] if checkBoard(board) == 0: print(\"No king in danger\")elif checkBoard(board) == 1: print(\"White king in danger\")else: print(\"Black king in danger\") # This code is contributed by divyeshrabadiya07.",
"e": 47475,
"s": 41668,
"text": null
},
{
"code": "using System; class GFG{ // Function to check if any of the two// kings is unsafe or notprivate static int checkBoard(char[,] board){ // Find the position of both the kings for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i, j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i, j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0;} private static bool lookFork(char[,] board, char c, int i, int j){ // Store all possible moves of the king int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 }; for(int k = 0; k < 8; k++) { // Incrementing index values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m, n] == c) return true; } return false;} // Function to check if Queen can attack the Kingprivate static bool lookForq(char[,] board, char c, int i, int j){ // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false;} // Function to check if bishop can attack the kingprivate static bool lookForb(char[,] board, char c, int i, int j){ // Check the lower right diagonal int k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k, j + k] == c) return true; if (board[i + k, j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k, j - k] == c) return true; if (board[i + k, j - k] != '-') break; } // Check the upper right diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k, j + k] == c) return true; if (board[i - k, j + k] != '-') break; } // Check the upper left diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k, j - k] == c) return true; if (board[i - k, j - k] != '-') break; } return false;} // Check ifprivate static bool lookForr(char[,] board, char c, int i, int j){ // Check downwards int k = 0; while (inBounds(i + ++k, j)) { if (board[i + k, j] == c) return true; if (board[i + k, j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k, j] == c) return true; if (board[i + k, j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i, j + k] == c) return true; if (board[i, j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i, j + k] == c) return true; if (board[i, j + k] != '-') break; } return false;} // Check if the knight can attack the kingprivate static bool lookForn(char[,] board, char c, int i, int j){ // All possible moves of the knight int[] x = { 2, 2, -2, -2, 1, 1, -1, -1 }; int[] y = { 1, -1, 1, -1, 2, -2, 2, -2 }; for(int k = 0; k < 8; k++) { // Incrementing index values int m = i + x[k]; int n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m, n] == c) return true; } return false;} // Function to check if pawn can attack the kingprivate static bool lookForp(char[,] board, char c, int i, int j){ char lookFor; if (char.IsUpper(c)) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1, j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1, j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1, j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1, j + 1] == lookFor) return true; } return false;} // Check if the indices are within// the matrix or notprivate static bool inBounds(int i, int j){ // Checking boundary conditions return i >= 0 && i < 8 && j >= 0 && j < 8;} // Driver Codepublic static void Main(String[] args){ // Chessboard instance char[,] board = { { '-', '-', '-', 'k', '-', '-', '-', '-' }, { 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' }, { '-', '-', '-', '-', '-', 'b', '-', '-' }, { '-', '-', '-', 'R', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { '-', '-', '-', '-', '-', '-', '-', '-' }, { 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' }, { 'K', '-', '-', '-', '-', '-', '-', '-' } }; if (checkBoard(board) == 0) Console.WriteLine(\"No king in danger\"); else if (checkBoard(board) == 1) Console.WriteLine(\"White king in danger\"); else Console.WriteLine(\"Black king in danger\");}} // This code is contributed by 29AjayKumar",
"e": 54606,
"s": 47475,
"text": null
},
{
"code": "<script> // Javascript program to implement the above approach // Function to check if any of the two // kings is unsafe or not function checkBoard(board) { // Find the position of both the kings for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) { // Check for all pieces which // can attack White King if (board[i][j] == 'k') { // Check for Knight if (lookForn(board, 'N', i, j)) return 1; // Check for Pawn if (lookForp(board, 'P', i, j)) return 1; // Check for Rook if (lookForr(board, 'R', i, j)) return 1; // Check for Bishop if (lookForb(board, 'B', i, j)) return 1; // Check for Queen if (lookForq(board, 'Q', i, j)) return 1; // Check for King if (lookFork(board, 'K', i, j)) return 1; } // Check for all pieces which // can attack Black King if (board[i][j] == 'K') { // Check for Knight if (lookForn(board, 'n', i, j)) return 2; // Check for Pawn if (lookForp(board, 'p', i, j)) return 2; // Check for Rook if (lookForr(board, 'r', i, j)) return 2; // Check for Bishop if (lookForb(board, 'b', i, j)) return 2; // Check for Queen if (lookForq(board, 'q', i, j)) return 2; // Check for King if (lookFork(board, 'k', i, j)) return 2; } } } return 0; } function lookFork(board, c, i, j) { // Store all possible moves of the king let x = [ -1, -1, -1, 0, 0, 1, 1, 1 ]; let y = [ -1, 0, 1, -1, 1, -1, 0, 1 ]; for (let k = 0; k < 8; k++) { // incrementing index values let m = i + x[k]; let n = j + y[k]; // checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if Queen can attack the King function lookForq(board, c, i, j) { // Queen's moves are a combination // of both the Bishop and the Rook if (lookForb(board, c, i, j) || lookForr(board, c, i, j)) return true; return false; } // Function to check if bishop can attack the king function lookForb(board, c, i, j) { // Check the lower right diagonal let k = 0; while (inBounds(i + ++k, j + k)) { if (board[i + k][j + k] == c) return true; if (board[i + k][j + k] != '-') break; } // Check the lower left diagonal k = 0; while (inBounds(i + ++k, j - k)) { if (board[i + k][j - k] == c) return true; if (board[i + k][j - k] != '-') break; } // Check the upper right diagonal k = 0; while (inBounds(i - ++k, j + k)) { if (board[i - k][j + k] == c) return true; if (board[i - k][j + k] != '-') break; } // Check the upper left diagonal k = 0; while (inBounds(i - ++k, j - k)) { if (board[i - k][j - k] == c) return true; if (board[i - k][j - k] != '-') break; } return false; } // Check if function lookForr(board, c, i, j) { // Check downwards let k = 0; while (inBounds(i + ++k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check upwards k = 0; while (inBounds(i + --k, j)) { if (board[i + k][j] == c) return true; if (board[i + k][j] != '-') break; } // Check right k = 0; while (inBounds(i, j + ++k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } // Check left k = 0; while (inBounds(i, j + --k)) { if (board[i][j + k] == c) return true; if (board[i][j + k] != '-') break; } return false; } // Check if the knight can attack the king function lookForn(board, c, i, j) { // All possible moves of the knight let x = [ 2, 2, -2, -2, 1, 1, -1, -1 ]; let y = [ 1, -1, 1, -1, 2, -2, 2, -2 ]; for (let k = 0; k < 8; k++) { // Incrementing index values let m = i + x[k]; let n = j + y[k]; // Checking boundary conditions // and character match if (inBounds(m, n) && board[m][n] == c) return true; } return false; } // Function to check if pawn can attack the king function lookForp(board, c, i, j) { let lookFor; if (c.charCodeAt() >= 65 && c.charCodeAt() <= 90) { // Check for white pawn lookFor = 'P'; if (inBounds(i + 1, j - 1) && board[i + 1][j - 1] == lookFor) return true; if (inBounds(i + 1, j + 1) && board[i + 1][j + 1] == lookFor) return true; } else { // Check for black pawn lookFor = 'p'; if (inBounds(i - 1, j - 1) && board[i - 1][j - 1] == lookFor) return true; if (inBounds(i - 1, j + 1) && board[i - 1][j + 1] == lookFor) return true; } return false; } // Check if the indices are within // the matrix or not function inBounds(i, j) { // Checking boundary conditions return i >= 0 && i < 8 && j >= 0 && j < 8; } // Chessboard instance let board = [ [ '-', '-', '-', 'k', '-', '-', '-', '-' ], [ 'p', 'p', 'p', '-', 'p', 'p', 'p', 'p' ], [ '-', '-', '-', '-', '-', 'b', '-', '-' ], [ '-', '-', '-', 'R', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ '-', '-', '-', '-', '-', '-', '-', '-' ], [ 'P', '-', 'P', 'P', 'P', 'P', 'P', 'P' ], [ 'K', '-', '-', '-', '-', '-', '-', '-' ] ]; if (checkBoard(board) == 0) document.write(\"No king in danger\"); else if (checkBoard(board) == 1) document.write(\"White king in danger\"); else document.write(\"Black king in danger\"); // This code is contributed by divyesh072019.</script>",
"e": 61883,
"s": 54606,
"text": null
},
{
"code": null,
"e": 61907,
"s": 61886,
"text": "White king in danger"
},
{
"code": null,
"e": 61954,
"s": 61909,
"text": "Time Complexity: O(N3) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 61966,
"s": 61954,
"text": "29AjayKumar"
},
{
"code": null,
"e": 61972,
"s": 61966,
"text": "ukasp"
},
{
"code": null,
"e": 61986,
"s": 61972,
"text": "divyesh072019"
},
{
"code": null,
"e": 62004,
"s": 61986,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 62008,
"s": 62004,
"text": "BFS"
},
{
"code": null,
"e": 62028,
"s": 62008,
"text": "chessboard-problems"
},
{
"code": null,
"e": 62041,
"s": 62028,
"text": "Backtracking"
},
{
"code": null,
"e": 62047,
"s": 62041,
"text": "Graph"
},
{
"code": null,
"e": 62054,
"s": 62047,
"text": "Matrix"
},
{
"code": null,
"e": 62064,
"s": 62054,
"text": "Recursion"
},
{
"code": null,
"e": 62074,
"s": 62064,
"text": "Recursion"
},
{
"code": null,
"e": 62081,
"s": 62074,
"text": "Matrix"
},
{
"code": null,
"e": 62087,
"s": 62081,
"text": "Graph"
},
{
"code": null,
"e": 62100,
"s": 62087,
"text": "Backtracking"
},
{
"code": null,
"e": 62104,
"s": 62100,
"text": "BFS"
},
{
"code": null,
"e": 62202,
"s": 62104,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 62213,
"s": 62202,
"text": "Tug of War"
},
{
"code": null,
"e": 62273,
"s": 62213,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 62334,
"s": 62273,
"text": "Difference between Backtracking and Branch-N-Bound technique"
},
{
"code": null,
"e": 62384,
"s": 62334,
"text": "Find shortest safe route in a path with landmines"
},
{
"code": null,
"e": 62446,
"s": 62384,
"text": "Print all possible strings that can be made by placing spaces"
},
{
"code": null,
"e": 62486,
"s": 62446,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 62537,
"s": 62486,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 62575,
"s": 62537,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 62633,
"s": 62575,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Collect maximum coins before hitting a dead end - GeeksforGeeks | 11 Oct, 2018
Given a character matrix where every cell has one of the following values.
'C' --> This cell has coin
'#' --> This cell is a blocking cell.
We can not go anywhere from this.
'E' --> This cell is empty. We don't get
a coin, but we can move from here.
Initial position is cell (0, 0) and initial direction is right.
Following are rules for movements across cells.
If face is Right, then we can move to below cells
Move one step ahead, i.e., cell (i, j+1) and direction remains right.Move one step down and face left, i.e., cell (i+1, j) and direction becomes left.If face is Left, then we can move to below cellsMove one step ahead, i.e., cell (i, j-1) and direction remains left.Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.Final position can be anywhere and final direction can also be anything. The target is to collect maximum coins.Example:We strongly recommend you to minimize your browser and try this yourself first.The above problem can be recursively defined as below:maxCoins(i, j, d): Maximum number of coins that can be
collected if we begin at cell (i, j)
and direction d.
d can be either 0 (left) or 1 (right)
// If this is a blocking cell, return 0. isValid() checks
// if i and j are valid row and column indexes.
If (arr[i][j] == '#' or isValid(i, j) == false)
return 0
// Initialize result
If (arr[i][j] == 'C')
result = 1;
Else
result = 0;
If (d == 0) // Left direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j-1, 0)); // Ahead in left
If (d == 1) // Right direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j+1, 0)); // Ahead in right
Below is C++ implementation of above recursive algorithm.C++Python3C++// A Naive Recursive C++ program to find maximum number of coins// that can be collected before hitting a dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for facing right. This function returns// number of maximum coins that can be collected starting from (i, j).int maxCoinsRec(char arr[R][C], int i, int j, int dir){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // Check if this cell contains the coin 'C' or if its empty 'E'. int result = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right in this cell if (dir == 1) // Direction is right return result + max(maxCoinsRec(arr, i+1, j, 0), // Down maxCoinsRec(arr, i, j+1, 1)); // Ahead in right // Direction is left // Get the maximum of two cases when you are facing left in this cell return result + max(maxCoinsRec(arr, i+1, j, 1), // Down maxCoinsRec(arr, i, j-1, 0)); // Ahead in left} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; // As per the question initial cell is (0, 0) and direction is // right cout << "Maximum number of collected coins is " << maxCoinsRec(arr, 0, 0, 1); return 0;}Python3# A Naive Recursive Python 3 program to # find maximum number of coins # that can be collected before hitting a dead end R= 5C= 5 # to check whether current cell is out of the grid or not def isValid( i, j): return (i >=0 and i < R and j >=0 and j < C) # dir = 0 for left, dir = 1 for facing right. # This function returns # number of maximum coins that can be collected# starting from (i, j). def maxCoinsRec(arr, i, j, dir): # If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == False or arr[i][j] == '#'): return 0 # Check if this cell contains the coin 'C' or if its empty 'E'. if (arr[i][j] == 'C'): result=1 else: result=0 # Get the maximum of two cases when you are facing right in this cell if (dir == 1): # Direction is right return (result + max(maxCoinsRec(arr, i+1, j, 0), maxCoinsRec(arr, i, j+1, 1))) # Direction is left # Get the maximum of two cases when you are facing left in this cell return (result + max(maxCoinsRec(arr, i+1, j, 1), maxCoinsRec(arr, i, j-1, 0))) # Driver program to test above function if __name__=='__main__': arr = [ ['E', 'C', 'C', 'C', 'C'], ['C', '#', 'C', '#', 'E'], ['#', 'C', 'C', '#', 'C'], ['C', 'E', 'E', 'C', 'E'], ['C', 'E', '#', 'C', 'E'] ] # As per the question initial cell is (0, 0) and direction is # right print("Maximum number of collected coins is ", maxCoinsRec(arr, 0, 0, 1)) # this code is contributed by ash264Output:Maximum number of collected coins is 8The time complexity of above solution recursive is exponential. We can solve this problem in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below is Dynamic Programming based C++ implementation.C++C++// A Dynamic Programming based C++ program to find maximum// number of coins that can be collected before hitting a// dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for right. This function returns// number of maximum coins that can be collected starting from// (i, j).int maxCoinsUtil(char arr[R][C], int i, int j, int dir, int dp[R][C][2]){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // If this subproblem is already solved than return the // already evaluated answer. if (dp[i][j][dir] != -1) return dp[i][j][dir]; // Check if this cell contains the coin 'C' or if its 'E'. dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right // in this cell if (dir == 1) // Direction is right dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught // Get the maximum of two cases when you are facing left // in this cell if (dir == 0) // Direction is left dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left // return the answer return dp[i][j][dir];} // This function mainly creates a lookup table and calls// maxCoinsUtil()int maxCoins(char arr[R][C]){ // Create lookup table and initialize all values as -1 int dp[R][C][2]; memset(dp, -1, sizeof dp); // As per the question initial cell is (0, 0) and direction // is right return maxCoinsUtil(arr, 0, 0, 1, dp);} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; cout << "Maximum number of collected coins is " << maxCoins(arr); return 0;}Output:Maximum number of collected coins is 8Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be written as O(R x C).Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
Move one step ahead, i.e., cell (i, j+1) and direction remains right.
Move one step down and face left, i.e., cell (i+1, j) and direction becomes left.If face is Left, then we can move to below cellsMove one step ahead, i.e., cell (i, j-1) and direction remains left.Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.Final position can be anywhere and final direction can also be anything. The target is to collect maximum coins.Example:We strongly recommend you to minimize your browser and try this yourself first.The above problem can be recursively defined as below:maxCoins(i, j, d): Maximum number of coins that can be
collected if we begin at cell (i, j)
and direction d.
d can be either 0 (left) or 1 (right)
// If this is a blocking cell, return 0. isValid() checks
// if i and j are valid row and column indexes.
If (arr[i][j] == '#' or isValid(i, j) == false)
return 0
// Initialize result
If (arr[i][j] == 'C')
result = 1;
Else
result = 0;
If (d == 0) // Left direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j-1, 0)); // Ahead in left
If (d == 1) // Right direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j+1, 0)); // Ahead in right
Below is C++ implementation of above recursive algorithm.C++Python3C++// A Naive Recursive C++ program to find maximum number of coins// that can be collected before hitting a dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for facing right. This function returns// number of maximum coins that can be collected starting from (i, j).int maxCoinsRec(char arr[R][C], int i, int j, int dir){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // Check if this cell contains the coin 'C' or if its empty 'E'. int result = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right in this cell if (dir == 1) // Direction is right return result + max(maxCoinsRec(arr, i+1, j, 0), // Down maxCoinsRec(arr, i, j+1, 1)); // Ahead in right // Direction is left // Get the maximum of two cases when you are facing left in this cell return result + max(maxCoinsRec(arr, i+1, j, 1), // Down maxCoinsRec(arr, i, j-1, 0)); // Ahead in left} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; // As per the question initial cell is (0, 0) and direction is // right cout << "Maximum number of collected coins is " << maxCoinsRec(arr, 0, 0, 1); return 0;}Python3# A Naive Recursive Python 3 program to # find maximum number of coins # that can be collected before hitting a dead end R= 5C= 5 # to check whether current cell is out of the grid or not def isValid( i, j): return (i >=0 and i < R and j >=0 and j < C) # dir = 0 for left, dir = 1 for facing right. # This function returns # number of maximum coins that can be collected# starting from (i, j). def maxCoinsRec(arr, i, j, dir): # If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == False or arr[i][j] == '#'): return 0 # Check if this cell contains the coin 'C' or if its empty 'E'. if (arr[i][j] == 'C'): result=1 else: result=0 # Get the maximum of two cases when you are facing right in this cell if (dir == 1): # Direction is right return (result + max(maxCoinsRec(arr, i+1, j, 0), maxCoinsRec(arr, i, j+1, 1))) # Direction is left # Get the maximum of two cases when you are facing left in this cell return (result + max(maxCoinsRec(arr, i+1, j, 1), maxCoinsRec(arr, i, j-1, 0))) # Driver program to test above function if __name__=='__main__': arr = [ ['E', 'C', 'C', 'C', 'C'], ['C', '#', 'C', '#', 'E'], ['#', 'C', 'C', '#', 'C'], ['C', 'E', 'E', 'C', 'E'], ['C', 'E', '#', 'C', 'E'] ] # As per the question initial cell is (0, 0) and direction is # right print("Maximum number of collected coins is ", maxCoinsRec(arr, 0, 0, 1)) # this code is contributed by ash264Output:Maximum number of collected coins is 8The time complexity of above solution recursive is exponential. We can solve this problem in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below is Dynamic Programming based C++ implementation.C++C++// A Dynamic Programming based C++ program to find maximum// number of coins that can be collected before hitting a// dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for right. This function returns// number of maximum coins that can be collected starting from// (i, j).int maxCoinsUtil(char arr[R][C], int i, int j, int dir, int dp[R][C][2]){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // If this subproblem is already solved than return the // already evaluated answer. if (dp[i][j][dir] != -1) return dp[i][j][dir]; // Check if this cell contains the coin 'C' or if its 'E'. dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right // in this cell if (dir == 1) // Direction is right dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught // Get the maximum of two cases when you are facing left // in this cell if (dir == 0) // Direction is left dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left // return the answer return dp[i][j][dir];} // This function mainly creates a lookup table and calls// maxCoinsUtil()int maxCoins(char arr[R][C]){ // Create lookup table and initialize all values as -1 int dp[R][C][2]; memset(dp, -1, sizeof dp); // As per the question initial cell is (0, 0) and direction // is right return maxCoinsUtil(arr, 0, 0, 1, dp);} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; cout << "Maximum number of collected coins is " << maxCoins(arr); return 0;}Output:Maximum number of collected coins is 8Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be written as O(R x C).Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
If face is Left, then we can move to below cells
Move one step ahead, i.e., cell (i, j-1) and direction remains left.Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.
Move one step ahead, i.e., cell (i, j-1) and direction remains left.
Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.
Final position can be anywhere and final direction can also be anything. The target is to collect maximum coins.
Example:
We strongly recommend you to minimize your browser and try this yourself first.
The above problem can be recursively defined as below:
maxCoins(i, j, d): Maximum number of coins that can be
collected if we begin at cell (i, j)
and direction d.
d can be either 0 (left) or 1 (right)
// If this is a blocking cell, return 0. isValid() checks
// if i and j are valid row and column indexes.
If (arr[i][j] == '#' or isValid(i, j) == false)
return 0
// Initialize result
If (arr[i][j] == 'C')
result = 1;
Else
result = 0;
If (d == 0) // Left direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j-1, 0)); // Ahead in left
If (d == 1) // Right direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j+1, 0)); // Ahead in right
Below is C++ implementation of above recursive algorithm.
C++
Python3
// A Naive Recursive C++ program to find maximum number of coins// that can be collected before hitting a dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for facing right. This function returns// number of maximum coins that can be collected starting from (i, j).int maxCoinsRec(char arr[R][C], int i, int j, int dir){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // Check if this cell contains the coin 'C' or if its empty 'E'. int result = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right in this cell if (dir == 1) // Direction is right return result + max(maxCoinsRec(arr, i+1, j, 0), // Down maxCoinsRec(arr, i, j+1, 1)); // Ahead in right // Direction is left // Get the maximum of two cases when you are facing left in this cell return result + max(maxCoinsRec(arr, i+1, j, 1), // Down maxCoinsRec(arr, i, j-1, 0)); // Ahead in left} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; // As per the question initial cell is (0, 0) and direction is // right cout << "Maximum number of collected coins is " << maxCoinsRec(arr, 0, 0, 1); return 0;}
# A Naive Recursive Python 3 program to # find maximum number of coins # that can be collected before hitting a dead end R= 5C= 5 # to check whether current cell is out of the grid or not def isValid( i, j): return (i >=0 and i < R and j >=0 and j < C) # dir = 0 for left, dir = 1 for facing right. # This function returns # number of maximum coins that can be collected# starting from (i, j). def maxCoinsRec(arr, i, j, dir): # If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == False or arr[i][j] == '#'): return 0 # Check if this cell contains the coin 'C' or if its empty 'E'. if (arr[i][j] == 'C'): result=1 else: result=0 # Get the maximum of two cases when you are facing right in this cell if (dir == 1): # Direction is right return (result + max(maxCoinsRec(arr, i+1, j, 0), maxCoinsRec(arr, i, j+1, 1))) # Direction is left # Get the maximum of two cases when you are facing left in this cell return (result + max(maxCoinsRec(arr, i+1, j, 1), maxCoinsRec(arr, i, j-1, 0))) # Driver program to test above function if __name__=='__main__': arr = [ ['E', 'C', 'C', 'C', 'C'], ['C', '#', 'C', '#', 'E'], ['#', 'C', 'C', '#', 'C'], ['C', 'E', 'E', 'C', 'E'], ['C', 'E', '#', 'C', 'E'] ] # As per the question initial cell is (0, 0) and direction is # right print("Maximum number of collected coins is ", maxCoinsRec(arr, 0, 0, 1)) # this code is contributed by ash264
Maximum number of collected coins is 8
The time complexity of above solution recursive is exponential. We can solve this problem in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below is Dynamic Programming based C++ implementation.
C++
// A Dynamic Programming based C++ program to find maximum// number of coins that can be collected before hitting a// dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for right. This function returns// number of maximum coins that can be collected starting from// (i, j).int maxCoinsUtil(char arr[R][C], int i, int j, int dir, int dp[R][C][2]){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // If this subproblem is already solved than return the // already evaluated answer. if (dp[i][j][dir] != -1) return dp[i][j][dir]; // Check if this cell contains the coin 'C' or if its 'E'. dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right // in this cell if (dir == 1) // Direction is right dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught // Get the maximum of two cases when you are facing left // in this cell if (dir == 0) // Direction is left dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left // return the answer return dp[i][j][dir];} // This function mainly creates a lookup table and calls// maxCoinsUtil()int maxCoins(char arr[R][C]){ // Create lookup table and initialize all values as -1 int dp[R][C][2]; memset(dp, -1, sizeof dp); // As per the question initial cell is (0, 0) and direction // is right return maxCoinsUtil(arr, 0, 0, 1, dp);} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; cout << "Maximum number of collected coins is " << maxCoins(arr); return 0;}
Output:
Maximum number of collected coins is 8
Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be written as O(R x C).
Thanks to Gaurav Ahirwar for suggesting above solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ash264
Dynamic Programming
Matrix
Dynamic Programming
Matrix
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
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Overlapping Subproblems Property in Dynamic Programming | DP-1
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Sudoku | Backtracking-7 | [
{
"code": null,
"e": 25214,
"s": 25186,
"text": "\n11 Oct, 2018"
},
{
"code": null,
"e": 25289,
"s": 25214,
"text": "Given a character matrix where every cell has one of the following values."
},
{
"code": null,
"e": 25490,
"s": 25289,
"text": "'C' --> This cell has coin\n\n'#' --> This cell is a blocking cell. \n We can not go anywhere from this.\n\n'E' --> This cell is empty. We don't get\n a coin, but we can move from here. "
},
{
"code": null,
"e": 25554,
"s": 25490,
"text": "Initial position is cell (0, 0) and initial direction is right."
},
{
"code": null,
"e": 25602,
"s": 25554,
"text": "Following are rules for movements across cells."
},
{
"code": null,
"e": 25652,
"s": 25602,
"text": "If face is Right, then we can move to below cells"
},
{
"code": null,
"e": 33484,
"s": 25652,
"text": "Move one step ahead, i.e., cell (i, j+1) and direction remains right.Move one step down and face left, i.e., cell (i+1, j) and direction becomes left.If face is Left, then we can move to below cellsMove one step ahead, i.e., cell (i, j-1) and direction remains left.Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.Final position can be anywhere and final direction can also be anything. The target is to collect maximum coins.Example:We strongly recommend you to minimize your browser and try this yourself first.The above problem can be recursively defined as below:maxCoins(i, j, d): Maximum number of coins that can be \n collected if we begin at cell (i, j)\n and direction d.\n d can be either 0 (left) or 1 (right)\n\n // If this is a blocking cell, return 0. isValid() checks\n // if i and j are valid row and column indexes.\n If (arr[i][j] == '#' or isValid(i, j) == false)\n return 0\n\n // Initialize result\n If (arr[i][j] == 'C')\n result = 1;\n Else \n result = 0;\n\n If (d == 0) // Left direction \n return result + max(maxCoins(i+1, j, 1), // Down\n maxCoins(i, j-1, 0)); // Ahead in left\n\n If (d == 1) // Right direction \n return result + max(maxCoins(i+1, j, 1), // Down\n maxCoins(i, j+1, 0)); // Ahead in right\nBelow is C++ implementation of above recursive algorithm.C++Python3C++// A Naive Recursive C++ program to find maximum number of coins// that can be collected before hitting a dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for facing right. This function returns// number of maximum coins that can be collected starting from (i, j).int maxCoinsRec(char arr[R][C], int i, int j, int dir){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // Check if this cell contains the coin 'C' or if its empty 'E'. int result = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right in this cell if (dir == 1) // Direction is right return result + max(maxCoinsRec(arr, i+1, j, 0), // Down maxCoinsRec(arr, i, j+1, 1)); // Ahead in right // Direction is left // Get the maximum of two cases when you are facing left in this cell return result + max(maxCoinsRec(arr, i+1, j, 1), // Down maxCoinsRec(arr, i, j-1, 0)); // Ahead in left} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; // As per the question initial cell is (0, 0) and direction is // right cout << \"Maximum number of collected coins is \" << maxCoinsRec(arr, 0, 0, 1); return 0;}Python3# A Naive Recursive Python 3 program to # find maximum number of coins # that can be collected before hitting a dead end R= 5C= 5 # to check whether current cell is out of the grid or not def isValid( i, j): return (i >=0 and i < R and j >=0 and j < C) # dir = 0 for left, dir = 1 for facing right. # This function returns # number of maximum coins that can be collected# starting from (i, j). def maxCoinsRec(arr, i, j, dir): # If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == False or arr[i][j] == '#'): return 0 # Check if this cell contains the coin 'C' or if its empty 'E'. if (arr[i][j] == 'C'): result=1 else: result=0 # Get the maximum of two cases when you are facing right in this cell if (dir == 1): # Direction is right return (result + max(maxCoinsRec(arr, i+1, j, 0), maxCoinsRec(arr, i, j+1, 1))) # Direction is left # Get the maximum of two cases when you are facing left in this cell return (result + max(maxCoinsRec(arr, i+1, j, 1), maxCoinsRec(arr, i, j-1, 0))) # Driver program to test above function if __name__=='__main__': arr = [ ['E', 'C', 'C', 'C', 'C'], ['C', '#', 'C', '#', 'E'], ['#', 'C', 'C', '#', 'C'], ['C', 'E', 'E', 'C', 'E'], ['C', 'E', '#', 'C', 'E'] ] # As per the question initial cell is (0, 0) and direction is # right print(\"Maximum number of collected coins is \", maxCoinsRec(arr, 0, 0, 1)) # this code is contributed by ash264Output:Maximum number of collected coins is 8The time complexity of above solution recursive is exponential. We can solve this problem in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below is Dynamic Programming based C++ implementation.C++C++// A Dynamic Programming based C++ program to find maximum// number of coins that can be collected before hitting a// dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for right. This function returns// number of maximum coins that can be collected starting from// (i, j).int maxCoinsUtil(char arr[R][C], int i, int j, int dir, int dp[R][C][2]){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // If this subproblem is already solved than return the // already evaluated answer. if (dp[i][j][dir] != -1) return dp[i][j][dir]; // Check if this cell contains the coin 'C' or if its 'E'. dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right // in this cell if (dir == 1) // Direction is right dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught // Get the maximum of two cases when you are facing left // in this cell if (dir == 0) // Direction is left dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left // return the answer return dp[i][j][dir];} // This function mainly creates a lookup table and calls// maxCoinsUtil()int maxCoins(char arr[R][C]){ // Create lookup table and initialize all values as -1 int dp[R][C][2]; memset(dp, -1, sizeof dp); // As per the question initial cell is (0, 0) and direction // is right return maxCoinsUtil(arr, 0, 0, 1, dp);} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; cout << \"Maximum number of collected coins is \" << maxCoins(arr); return 0;}Output:Maximum number of collected coins is 8Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be written as O(R x C).Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 33554,
"s": 33484,
"text": "Move one step ahead, i.e., cell (i, j+1) and direction remains right."
},
{
"code": null,
"e": 41317,
"s": 33554,
"text": "Move one step down and face left, i.e., cell (i+1, j) and direction becomes left.If face is Left, then we can move to below cellsMove one step ahead, i.e., cell (i, j-1) and direction remains left.Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.Final position can be anywhere and final direction can also be anything. The target is to collect maximum coins.Example:We strongly recommend you to minimize your browser and try this yourself first.The above problem can be recursively defined as below:maxCoins(i, j, d): Maximum number of coins that can be \n collected if we begin at cell (i, j)\n and direction d.\n d can be either 0 (left) or 1 (right)\n\n // If this is a blocking cell, return 0. isValid() checks\n // if i and j are valid row and column indexes.\n If (arr[i][j] == '#' or isValid(i, j) == false)\n return 0\n\n // Initialize result\n If (arr[i][j] == 'C')\n result = 1;\n Else \n result = 0;\n\n If (d == 0) // Left direction \n return result + max(maxCoins(i+1, j, 1), // Down\n maxCoins(i, j-1, 0)); // Ahead in left\n\n If (d == 1) // Right direction \n return result + max(maxCoins(i+1, j, 1), // Down\n maxCoins(i, j+1, 0)); // Ahead in right\nBelow is C++ implementation of above recursive algorithm.C++Python3C++// A Naive Recursive C++ program to find maximum number of coins// that can be collected before hitting a dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for facing right. This function returns// number of maximum coins that can be collected starting from (i, j).int maxCoinsRec(char arr[R][C], int i, int j, int dir){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // Check if this cell contains the coin 'C' or if its empty 'E'. int result = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right in this cell if (dir == 1) // Direction is right return result + max(maxCoinsRec(arr, i+1, j, 0), // Down maxCoinsRec(arr, i, j+1, 1)); // Ahead in right // Direction is left // Get the maximum of two cases when you are facing left in this cell return result + max(maxCoinsRec(arr, i+1, j, 1), // Down maxCoinsRec(arr, i, j-1, 0)); // Ahead in left} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; // As per the question initial cell is (0, 0) and direction is // right cout << \"Maximum number of collected coins is \" << maxCoinsRec(arr, 0, 0, 1); return 0;}Python3# A Naive Recursive Python 3 program to # find maximum number of coins # that can be collected before hitting a dead end R= 5C= 5 # to check whether current cell is out of the grid or not def isValid( i, j): return (i >=0 and i < R and j >=0 and j < C) # dir = 0 for left, dir = 1 for facing right. # This function returns # number of maximum coins that can be collected# starting from (i, j). def maxCoinsRec(arr, i, j, dir): # If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == False or arr[i][j] == '#'): return 0 # Check if this cell contains the coin 'C' or if its empty 'E'. if (arr[i][j] == 'C'): result=1 else: result=0 # Get the maximum of two cases when you are facing right in this cell if (dir == 1): # Direction is right return (result + max(maxCoinsRec(arr, i+1, j, 0), maxCoinsRec(arr, i, j+1, 1))) # Direction is left # Get the maximum of two cases when you are facing left in this cell return (result + max(maxCoinsRec(arr, i+1, j, 1), maxCoinsRec(arr, i, j-1, 0))) # Driver program to test above function if __name__=='__main__': arr = [ ['E', 'C', 'C', 'C', 'C'], ['C', '#', 'C', '#', 'E'], ['#', 'C', 'C', '#', 'C'], ['C', 'E', 'E', 'C', 'E'], ['C', 'E', '#', 'C', 'E'] ] # As per the question initial cell is (0, 0) and direction is # right print(\"Maximum number of collected coins is \", maxCoinsRec(arr, 0, 0, 1)) # this code is contributed by ash264Output:Maximum number of collected coins is 8The time complexity of above solution recursive is exponential. We can solve this problem in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below is Dynamic Programming based C++ implementation.C++C++// A Dynamic Programming based C++ program to find maximum// number of coins that can be collected before hitting a// dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for right. This function returns// number of maximum coins that can be collected starting from// (i, j).int maxCoinsUtil(char arr[R][C], int i, int j, int dir, int dp[R][C][2]){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // If this subproblem is already solved than return the // already evaluated answer. if (dp[i][j][dir] != -1) return dp[i][j][dir]; // Check if this cell contains the coin 'C' or if its 'E'. dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right // in this cell if (dir == 1) // Direction is right dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught // Get the maximum of two cases when you are facing left // in this cell if (dir == 0) // Direction is left dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left // return the answer return dp[i][j][dir];} // This function mainly creates a lookup table and calls// maxCoinsUtil()int maxCoins(char arr[R][C]){ // Create lookup table and initialize all values as -1 int dp[R][C][2]; memset(dp, -1, sizeof dp); // As per the question initial cell is (0, 0) and direction // is right return maxCoinsUtil(arr, 0, 0, 1, dp);} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; cout << \"Maximum number of collected coins is \" << maxCoins(arr); return 0;}Output:Maximum number of collected coins is 8Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be written as O(R x C).Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 41366,
"s": 41317,
"text": "If face is Left, then we can move to below cells"
},
{
"code": null,
"e": 41518,
"s": 41366,
"text": "Move one step ahead, i.e., cell (i, j-1) and direction remains left.Move one step down and face right, i.e., cell (i+1, j) and direction becomes right."
},
{
"code": null,
"e": 41587,
"s": 41518,
"text": "Move one step ahead, i.e., cell (i, j-1) and direction remains left."
},
{
"code": null,
"e": 41671,
"s": 41587,
"text": "Move one step down and face right, i.e., cell (i+1, j) and direction becomes right."
},
{
"code": null,
"e": 41784,
"s": 41671,
"text": "Final position can be anywhere and final direction can also be anything. The target is to collect maximum coins."
},
{
"code": null,
"e": 41793,
"s": 41784,
"text": "Example:"
},
{
"code": null,
"e": 41873,
"s": 41793,
"text": "We strongly recommend you to minimize your browser and try this yourself first."
},
{
"code": null,
"e": 41928,
"s": 41873,
"text": "The above problem can be recursively defined as below:"
},
{
"code": null,
"e": 42737,
"s": 41928,
"text": "maxCoins(i, j, d): Maximum number of coins that can be \n collected if we begin at cell (i, j)\n and direction d.\n d can be either 0 (left) or 1 (right)\n\n // If this is a blocking cell, return 0. isValid() checks\n // if i and j are valid row and column indexes.\n If (arr[i][j] == '#' or isValid(i, j) == false)\n return 0\n\n // Initialize result\n If (arr[i][j] == 'C')\n result = 1;\n Else \n result = 0;\n\n If (d == 0) // Left direction \n return result + max(maxCoins(i+1, j, 1), // Down\n maxCoins(i, j-1, 0)); // Ahead in left\n\n If (d == 1) // Right direction \n return result + max(maxCoins(i+1, j, 1), // Down\n maxCoins(i, j+1, 0)); // Ahead in right\n"
},
{
"code": null,
"e": 42795,
"s": 42737,
"text": "Below is C++ implementation of above recursive algorithm."
},
{
"code": null,
"e": 42799,
"s": 42795,
"text": "C++"
},
{
"code": null,
"e": 42807,
"s": 42799,
"text": "Python3"
},
{
"code": "// A Naive Recursive C++ program to find maximum number of coins// that can be collected before hitting a dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for facing right. This function returns// number of maximum coins that can be collected starting from (i, j).int maxCoinsRec(char arr[R][C], int i, int j, int dir){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // Check if this cell contains the coin 'C' or if its empty 'E'. int result = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right in this cell if (dir == 1) // Direction is right return result + max(maxCoinsRec(arr, i+1, j, 0), // Down maxCoinsRec(arr, i, j+1, 1)); // Ahead in right // Direction is left // Get the maximum of two cases when you are facing left in this cell return result + max(maxCoinsRec(arr, i+1, j, 1), // Down maxCoinsRec(arr, i, j-1, 0)); // Ahead in left} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; // As per the question initial cell is (0, 0) and direction is // right cout << \"Maximum number of collected coins is \" << maxCoinsRec(arr, 0, 0, 1); return 0;}",
"e": 44561,
"s": 42807,
"text": null
},
{
"code": "# A Naive Recursive Python 3 program to # find maximum number of coins # that can be collected before hitting a dead end R= 5C= 5 # to check whether current cell is out of the grid or not def isValid( i, j): return (i >=0 and i < R and j >=0 and j < C) # dir = 0 for left, dir = 1 for facing right. # This function returns # number of maximum coins that can be collected# starting from (i, j). def maxCoinsRec(arr, i, j, dir): # If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == False or arr[i][j] == '#'): return 0 # Check if this cell contains the coin 'C' or if its empty 'E'. if (arr[i][j] == 'C'): result=1 else: result=0 # Get the maximum of two cases when you are facing right in this cell if (dir == 1): # Direction is right return (result + max(maxCoinsRec(arr, i+1, j, 0), maxCoinsRec(arr, i, j+1, 1))) # Direction is left # Get the maximum of two cases when you are facing left in this cell return (result + max(maxCoinsRec(arr, i+1, j, 1), maxCoinsRec(arr, i, j-1, 0))) # Driver program to test above function if __name__=='__main__': arr = [ ['E', 'C', 'C', 'C', 'C'], ['C', '#', 'C', '#', 'E'], ['#', 'C', 'C', '#', 'C'], ['C', 'E', 'E', 'C', 'E'], ['C', 'E', '#', 'C', 'E'] ] # As per the question initial cell is (0, 0) and direction is # right print(\"Maximum number of collected coins is \", maxCoinsRec(arr, 0, 0, 1)) # this code is contributed by ash264",
"e": 46142,
"s": 44561,
"text": null
},
{
"code": null,
"e": 46181,
"s": 46142,
"text": "Maximum number of collected coins is 8"
},
{
"code": null,
"e": 46495,
"s": 46181,
"text": "The time complexity of above solution recursive is exponential. We can solve this problem in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below is Dynamic Programming based C++ implementation."
},
{
"code": null,
"e": 46499,
"s": 46495,
"text": "C++"
},
{
"code": "// A Dynamic Programming based C++ program to find maximum// number of coins that can be collected before hitting a// dead end#include<bits/stdc++.h>using namespace std;#define R 5#define C 5 // to check whether current cell is out of the grid or notbool isValid(int i, int j){ return (i >=0 && i < R && j >=0 && j < C);} // dir = 0 for left, dir = 1 for right. This function returns// number of maximum coins that can be collected starting from// (i, j).int maxCoinsUtil(char arr[R][C], int i, int j, int dir, int dp[R][C][2]){ // If this is a invalid cell or if cell is a blocking cell if (isValid(i,j) == false || arr[i][j] == '#') return 0; // If this subproblem is already solved than return the // already evaluated answer. if (dp[i][j][dir] != -1) return dp[i][j][dir]; // Check if this cell contains the coin 'C' or if its 'E'. dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0; // Get the maximum of two cases when you are facing right // in this cell if (dir == 1) // Direction is right dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught // Get the maximum of two cases when you are facing left // in this cell if (dir == 0) // Direction is left dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left // return the answer return dp[i][j][dir];} // This function mainly creates a lookup table and calls// maxCoinsUtil()int maxCoins(char arr[R][C]){ // Create lookup table and initialize all values as -1 int dp[R][C][2]; memset(dp, -1, sizeof dp); // As per the question initial cell is (0, 0) and direction // is right return maxCoinsUtil(arr, 0, 0, 1, dp);} // Driver program to test above functionint main(){ char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'}, {'C', '#', 'C', '#', 'E'}, {'#', 'C', 'C', '#', 'C'}, {'C', 'E', 'E', 'C', 'E'}, {'C', 'E', '#', 'C', 'E'} }; cout << \"Maximum number of collected coins is \" << maxCoins(arr); return 0;}",
"e": 48780,
"s": 46499,
"text": null
},
{
"code": null,
"e": 48788,
"s": 48780,
"text": "Output:"
},
{
"code": null,
"e": 48827,
"s": 48788,
"text": "Maximum number of collected coins is 8"
},
{
"code": null,
"e": 48936,
"s": 48827,
"text": "Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be written as O(R x C)."
},
{
"code": null,
"e": 48992,
"s": 48936,
"text": "Thanks to Gaurav Ahirwar for suggesting above solution."
},
{
"code": null,
"e": 49117,
"s": 48992,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 49124,
"s": 49117,
"text": "ash264"
},
{
"code": null,
"e": 49144,
"s": 49124,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 49151,
"s": 49144,
"text": "Matrix"
},
{
"code": null,
"e": 49171,
"s": 49151,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 49178,
"s": 49171,
"text": "Matrix"
},
{
"code": null,
"e": 49276,
"s": 49178,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49307,
"s": 49276,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 49340,
"s": 49307,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 49408,
"s": 49340,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 49429,
"s": 49408,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 49492,
"s": 49429,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 49536,
"s": 49492,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 49572,
"s": 49536,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 49603,
"s": 49572,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 49665,
"s": 49603,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
}
] |
How to draw a rectangle in OpenCV using Java? | The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. To draw a rectangle you need to invoke the rectangle() method of this class. This method accepts the following parameters −
A Mat object representing the image on which the rectangle is to be drawn.
A Mat object representing the image on which the rectangle is to be drawn.
Two Point objects representing the vertices of the rectangle that is to be
drawn.
Two Point objects representing the vertices of the rectangle that is to be
drawn.
A Scalar object representing the color of the rectangle(BGR).
A Scalar object representing the color of the rectangle(BGR).
An integer representing the thickness of the rectangle(default:1).
An integer representing the thickness of the rectangle(default:1).
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class DrawingRectangle {
public static void main(String args[]) {
// Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the source image in to a Mat object
Mat src = Imgcodecs.imread("D:\\images\\blank.jpg");
//Drawing a Rectangle
Point point1 = new Point(100, 100);
Point point2 = new Point(500, 300);
Scalar color = new Scalar(64, 64, 64);
int thickness = 10;
Imgproc.rectangle (src, point1, point2, color, thickness);
//Saving and displaying the image
Imgcodecs.imwrite("arrowed_line.jpg", src);
HighGui.imshow("Drawing a rectangle", src);
HighGui.waitKey();
}
}
On executing, the above program generates the following window − | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. To draw a rectangle you need to invoke the rectangle() method of this class. This method accepts the following parameters −"
},
{
"code": null,
"e": 1347,
"s": 1272,
"text": "A Mat object representing the image on which the rectangle is to be drawn."
},
{
"code": null,
"e": 1422,
"s": 1347,
"text": "A Mat object representing the image on which the rectangle is to be drawn."
},
{
"code": null,
"e": 1504,
"s": 1422,
"text": "Two Point objects representing the vertices of the rectangle that is to be\ndrawn."
},
{
"code": null,
"e": 1586,
"s": 1504,
"text": "Two Point objects representing the vertices of the rectangle that is to be\ndrawn."
},
{
"code": null,
"e": 1648,
"s": 1586,
"text": "A Scalar object representing the color of the rectangle(BGR)."
},
{
"code": null,
"e": 1710,
"s": 1648,
"text": "A Scalar object representing the color of the rectangle(BGR)."
},
{
"code": null,
"e": 1777,
"s": 1710,
"text": "An integer representing the thickness of the rectangle(default:1)."
},
{
"code": null,
"e": 1844,
"s": 1777,
"text": "An integer representing the thickness of the rectangle(default:1)."
},
{
"code": null,
"e": 2867,
"s": 1844,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class DrawingRectangle {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the source image in to a Mat object\n Mat src = Imgcodecs.imread(\"D:\\\\images\\\\blank.jpg\");\n //Drawing a Rectangle\n Point point1 = new Point(100, 100);\n Point point2 = new Point(500, 300);\n Scalar color = new Scalar(64, 64, 64);\n int thickness = 10;\n Imgproc.rectangle (src, point1, point2, color, thickness);\n //Saving and displaying the image\n Imgcodecs.imwrite(\"arrowed_line.jpg\", src);\n HighGui.imshow(\"Drawing a rectangle\", src);\n HighGui.waitKey();\n }\n}"
},
{
"code": null,
"e": 2932,
"s": 2867,
"text": "On executing, the above program generates the following window −"
}
] |
How to split a string in Java? | Java provides a split() methodology you'll be able to split the string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.
If the expression doesn't match any a part of the input then the ensuing array has the only 1part, specifically this string.
Live Demo
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "a d, m, i.n";
String delimiters = "\\s+|,\\s*|\\.\\s*";
String[] tokensVal = str.split(delimiters);
// prints the count of tokens
System.out.println("Count of tokens = " + tokensVal.length);
for(String token : tokensVal) {
System.out.print(token);
}
tokensVal = str.split(delimiters, 3);
System.out.println("\nCount of tokens = " + tokensVal.length);
for(String token : tokensVal) {
System.out.print(token);
}
}
}
Count of tokens = 5
admin
Count of tokens = 3
adm, i.n | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Java provides a split() methodology you'll be able to split the string around matches of the given regular expression."
},
{
"code": null,
"e": 1372,
"s": 1181,
"text": "The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. "
},
{
"code": null,
"e": 1497,
"s": 1372,
"text": "If the expression doesn't match any a part of the input then the ensuing array has the only 1part, specifically this string."
},
{
"code": null,
"e": 1507,
"s": 1497,
"text": "Live Demo"
},
{
"code": null,
"e": 2150,
"s": 1507,
"text": "import java.lang.*;\n\npublic class StringDemo {\n public static void main(String[] args) {\n\n String str = \"a d, m, i.n\";\n String delimiters = \"\\\\s+|,\\\\s*|\\\\.\\\\s*\";\n String[] tokensVal = str.split(delimiters);\n \n // prints the count of tokens\n System.out.println(\"Count of tokens = \" + tokensVal.length); \n \n for(String token : tokensVal) {\n System.out.print(token);\n } \n tokensVal = str.split(delimiters, 3);\n System.out.println(\"\\nCount of tokens = \" + tokensVal.length); \n \n for(String token : tokensVal) {\n System.out.print(token);\n } \n }\n}"
},
{
"code": null,
"e": 2205,
"s": 2150,
"text": "Count of tokens = 5\nadmin\nCount of tokens = 3\nadm, i.n"
}
] |
AngularJS | How to use ng-idle? - GeeksforGeeks | 03 Jul, 2019
The ng-idle is used to decrease the burden, bandwidth, and workload of an app, website, program, or software. With the help of ng-idle log out the session of inactive users so that our precious data & the workload is getting preserved or to even taunt them to participate in more actively.
The ng-idle is the module, which is required to respond to and handle the idle users in the module. The ng-idle directive displays a warning dialog by using the $uibModal from UI Bootstrap. It will do the countdown for the remaining time until the session gets timed-out. The application will be sending a request to the HTTP, which is going to be ending our or any user’s current session, send the error message and finally re-direct them to the initial login page/panel. So we have learned that the main objective of the ng-idle directive module is to detect those users, who are inactive, sluggish, or simply idle. But it has another job to do. It could also be implemented to notify, alert, and warn the users of an approaching time-out.
The core of this module is the service of Idle, which it excels at doing and is best at. This is totally based upon the user’s configuration and to be aware of the activeness of the user and to then detect whether the user is active or inactive, and then finally getting the information passed onto the main application so that it could make an appropriate response.
Note: AngularJS 1.2 or later is required. This is the only dependency required.
Syntax: This syntax will be included in the module as the dependency to complete the angular configuration.
var myApp = angular.module("myApp", ['ngIdle']);
Let’s see the usage of ng-idle with an example.Example:
<!DOCTYPE html><html> <head> <title> AngularJS ng-Idle </title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"> </script> <script type="text/javascript" src="https://rawgithub.com/hackedbychinese/ng-idle/master/angular-idle.js"> </script> <link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.1/ui-bootstrap-tpls.js"> </script> <script type="text/javascript"> var app = angular.module('myApp', ['ngIdle', 'ui.bootstrap']); app.controller( 'DemoCtrl', function($scope, Idle, Keepalive, $modal) { $scope.started = false; function closeModals() { if ($scope.warning) { $scope.warning.close(); $scope.warning = null; } if ($scope.timedout) { $scope.timedout.close(); $scope.timedout = null; } } $scope.$on('IdleStart', function() { closeModals(); $scope.warning = $modal.open({ templateUrl: 'warning-dialog.html', windowClass: 'modal-warning' }); }); $scope.$on('IdleEnd', function() { closeModals(); }); $scope.$on('IdleTimeout', function() { closeModals(); $scope.timedout = $modal.open({ templateUrl: 'timedout-dialog.html', windowClass: 'modal-danger' }); }); $scope.start = function() { console.log('start'); closeModals(); Idle.watch(); $scope.started = true; }; $scope.stop = function() { console.log('stop'); closeModals(); Idle.unwatch(); $scope.started = false; }; }); app.config(function(IdleProvider, KeepaliveProvider) { IdleProvider.idle(5); IdleProvider.timeout(5); KeepaliveProvider.interval(10); }); </script></head> <body> <body style="text-align:center"> <h2 style="color:green">GeeksForGeeks</h2> <h2 style="color:purple">AngularJS ng-idle</h2> <div ng-app="myApp" class="ng-scope"> <div ng-controller="DemoCtrl" class="ng-scope"> <p> <button type="button" class="btn btn-success" ng-hide="started" ng-click="start()"> Login </button> <button type="button" class="btn btn-danger ng-hide" data-ng-show="started" data-ng-click="stop()"> Reset </button> </p> </div> <script type="text/ng-template" id="warning-dialog.html"> <div class="modal-header"> <h3> The Idle mode is activated, because you are idle for far too long. As a result, you are going to be logout after in a few moments. </h3> </div> <div idle-countdown="countdown" ng-init="countdown=5" class="modal-body"> <progressbar max="5" value="5" animate="false" class="progress-striped active"> DO SOMETHING FAST! You are getting logged out in {{countdown}} second(s). </progressbar> </div> </script> <script type="text/ng-template" id="timedout-dialog.html"> <div class="modal-header"> <h3>Sorry, you have been Logged Out</h3> </div> <div class="modal-body"> <p> This program was idle for far too long. So we apologize for logging you out, but we had no option. </p> </div> </script> </div> </body> </html>
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25055,
"s": 25027,
"text": "\n03 Jul, 2019"
},
{
"code": null,
"e": 25345,
"s": 25055,
"text": "The ng-idle is used to decrease the burden, bandwidth, and workload of an app, website, program, or software. With the help of ng-idle log out the session of inactive users so that our precious data & the workload is getting preserved or to even taunt them to participate in more actively."
},
{
"code": null,
"e": 26087,
"s": 25345,
"text": "The ng-idle is the module, which is required to respond to and handle the idle users in the module. The ng-idle directive displays a warning dialog by using the $uibModal from UI Bootstrap. It will do the countdown for the remaining time until the session gets timed-out. The application will be sending a request to the HTTP, which is going to be ending our or any user’s current session, send the error message and finally re-direct them to the initial login page/panel. So we have learned that the main objective of the ng-idle directive module is to detect those users, who are inactive, sluggish, or simply idle. But it has another job to do. It could also be implemented to notify, alert, and warn the users of an approaching time-out."
},
{
"code": null,
"e": 26454,
"s": 26087,
"text": "The core of this module is the service of Idle, which it excels at doing and is best at. This is totally based upon the user’s configuration and to be aware of the activeness of the user and to then detect whether the user is active or inactive, and then finally getting the information passed onto the main application so that it could make an appropriate response."
},
{
"code": null,
"e": 26534,
"s": 26454,
"text": "Note: AngularJS 1.2 or later is required. This is the only dependency required."
},
{
"code": null,
"e": 26642,
"s": 26534,
"text": "Syntax: This syntax will be included in the module as the dependency to complete the angular configuration."
},
{
"code": null,
"e": 26691,
"s": 26642,
"text": "var myApp = angular.module(\"myApp\", ['ngIdle']);"
},
{
"code": null,
"e": 26747,
"s": 26691,
"text": "Let’s see the usage of ng-idle with an example.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> AngularJS ng-Idle </title> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js\"> </script> <script type=\"text/javascript\" src=\"https://rawgithub.com/hackedbychinese/ng-idle/master/angular-idle.js\"> </script> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css\"> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.1/ui-bootstrap-tpls.js\"> </script> <script type=\"text/javascript\"> var app = angular.module('myApp', ['ngIdle', 'ui.bootstrap']); app.controller( 'DemoCtrl', function($scope, Idle, Keepalive, $modal) { $scope.started = false; function closeModals() { if ($scope.warning) { $scope.warning.close(); $scope.warning = null; } if ($scope.timedout) { $scope.timedout.close(); $scope.timedout = null; } } $scope.$on('IdleStart', function() { closeModals(); $scope.warning = $modal.open({ templateUrl: 'warning-dialog.html', windowClass: 'modal-warning' }); }); $scope.$on('IdleEnd', function() { closeModals(); }); $scope.$on('IdleTimeout', function() { closeModals(); $scope.timedout = $modal.open({ templateUrl: 'timedout-dialog.html', windowClass: 'modal-danger' }); }); $scope.start = function() { console.log('start'); closeModals(); Idle.watch(); $scope.started = true; }; $scope.stop = function() { console.log('stop'); closeModals(); Idle.unwatch(); $scope.started = false; }; }); app.config(function(IdleProvider, KeepaliveProvider) { IdleProvider.idle(5); IdleProvider.timeout(5); KeepaliveProvider.interval(10); }); </script></head> <body> <body style=\"text-align:center\"> <h2 style=\"color:green\">GeeksForGeeks</h2> <h2 style=\"color:purple\">AngularJS ng-idle</h2> <div ng-app=\"myApp\" class=\"ng-scope\"> <div ng-controller=\"DemoCtrl\" class=\"ng-scope\"> <p> <button type=\"button\" class=\"btn btn-success\" ng-hide=\"started\" ng-click=\"start()\"> Login </button> <button type=\"button\" class=\"btn btn-danger ng-hide\" data-ng-show=\"started\" data-ng-click=\"stop()\"> Reset </button> </p> </div> <script type=\"text/ng-template\" id=\"warning-dialog.html\"> <div class=\"modal-header\"> <h3> The Idle mode is activated, because you are idle for far too long. As a result, you are going to be logout after in a few moments. </h3> </div> <div idle-countdown=\"countdown\" ng-init=\"countdown=5\" class=\"modal-body\"> <progressbar max=\"5\" value=\"5\" animate=\"false\" class=\"progress-striped active\"> DO SOMETHING FAST! You are getting logged out in {{countdown}} second(s). </progressbar> </div> </script> <script type=\"text/ng-template\" id=\"timedout-dialog.html\"> <div class=\"modal-header\"> <h3>Sorry, you have been Logged Out</h3> </div> <div class=\"modal-body\"> <p> This program was idle for far too long. So we apologize for logging you out, but we had no option. </p> </div> </script> </div> </body> </html>",
"e": 31643,
"s": 26747,
"text": null
},
{
"code": null,
"e": 31651,
"s": 31643,
"text": "Output:"
},
{
"code": null,
"e": 31666,
"s": 31651,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 31673,
"s": 31666,
"text": "Picked"
},
{
"code": null,
"e": 31683,
"s": 31673,
"text": "AngularJS"
},
{
"code": null,
"e": 31700,
"s": 31683,
"text": "Web Technologies"
},
{
"code": null,
"e": 31798,
"s": 31700,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31807,
"s": 31798,
"text": "Comments"
},
{
"code": null,
"e": 31820,
"s": 31807,
"text": "Old Comments"
},
{
"code": null,
"e": 31864,
"s": 31820,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 31928,
"s": 31864,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 31981,
"s": 31928,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 32016,
"s": 31981,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 32040,
"s": 32016,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 32082,
"s": 32040,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32115,
"s": 32082,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32177,
"s": 32115,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32220,
"s": 32177,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Use Images as Backgrounds in Tkinter? | If we will create an instance of Tkinter frame and display the window while keep running it, then it will show the default output canvas. However, we can add an image inside the Tkinter canvas as a background using PhotoImage methods and Canvas methods.
Since image support in Tkinter is limited to Gif, PNG and PPM, the PhotoImage(GIF,
PNG, PPM) function takes the location of the image file and displays the canvas with the
image as a background.
First, we will create a PhotoImage Object using the PhotoImage function.
from tkinter import *
from PIL import ImageTk
win = Tk()
win.geometry("700x300")
#Define the PhotoImage Constructor by passing the image file
img= PhotoImage(file='down.png', master= win)
img_label= Label(win,image=img)
#define the position of the image
img_label.place(x=0, y=0)
win.mainloop()
Running the above code snippet will display a window with a background image. | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": "If we will create an instance of Tkinter frame and display the window while keep running it, then it will show the default output canvas. However, we can add an image inside the Tkinter canvas as a background using PhotoImage methods and Canvas methods."
},
{
"code": null,
"e": 1511,
"s": 1316,
"text": "Since image support in Tkinter is limited to Gif, PNG and PPM, the PhotoImage(GIF,\nPNG, PPM) function takes the location of the image file and displays the canvas with the\nimage as a background."
},
{
"code": null,
"e": 1584,
"s": 1511,
"text": "First, we will create a PhotoImage Object using the PhotoImage function."
},
{
"code": null,
"e": 1883,
"s": 1584,
"text": "from tkinter import *\nfrom PIL import ImageTk\n\nwin = Tk()\nwin.geometry(\"700x300\")\n\n#Define the PhotoImage Constructor by passing the image file\nimg= PhotoImage(file='down.png', master= win)\nimg_label= Label(win,image=img)\n\n#define the position of the image\nimg_label.place(x=0, y=0)\n\nwin.mainloop()"
},
{
"code": null,
"e": 1961,
"s": 1883,
"text": "Running the above code snippet will display a window with a background image."
}
] |
How to create an ordered list in HTML? | To create ordered list in HTML, use the <ol> tag. Ordered list starts with the <ol> tag. The list item starts with the <li> tag and will be marked as numbers, letters and roman numbers. The default is numbers.
You can try to run the following code to use an ordered list in HTML −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Developed Countries</h1>
<p>The list of developed countries :</p>
<ol>
<li>US</li>
<li>Australia</li>
<li>New Zealand</li>
</ol>
</body>
</html> | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "To create ordered list in HTML, use the <ol> tag. Ordered list starts with the <ol> tag. The list item starts with the <li> tag and will be marked as numbers, letters and roman numbers. The default is numbers."
},
{
"code": null,
"e": 1343,
"s": 1272,
"text": "You can try to run the following code to use an ordered list in HTML −"
},
{
"code": null,
"e": 1353,
"s": 1343,
"text": "Live Demo"
},
{
"code": null,
"e": 1589,
"s": 1353,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <h1>Developed Countries</h1>\n <p>The list of developed countries :</p>\n <ol>\n <li>US</li>\n <li>Australia</li>\n <li>New Zealand</li>\n </ol>\n </body>\n</html>"
}
] |
Python | Pandas dataframe.notnull() | 25 Aug, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.notnull() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the same size as that of the object on which it is applied, indicating whether each individual value is a na value or not. All of the non-missing values gets mapped to true and missing values get mapped to false. Note : Characters such as empty strings ” or numpy.inf are not considered NA values. (unless you set pandas.options.mode.use_inf_as_na = True).
Syntax: DataFrame.notnull()Returns : Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value.
Example #1: Use notnull() function to find all the non-missing value in the dataframe.
Python3
# importing pandas as pdimport pandas as pd # Creating the first dataframedf = pd.DataFrame({"A":[14, 4, 5, 4, 1], "B":["Sam", "olivia", "terica", "megan", "amanda"], "C":[20 + 5j, 20 + 3j, 7, 3, 8], "D":[14, 3, 6, 2, 6]}) # Print the dataframedf
Let’s use the dataframe.notnull() function to find all the non-missing values in the dataframe.
Python3
# find non-na valuesdf.notnull()
Output :
As we can see in the output, all the non-missing values in the dataframe has been mapped to true. There is no false value as there is no missing value in the dataframe Example #2: Use notnull() function to find the non-missing values, when there are missing values in the dataframe.
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":["Sandy", "alex", "brook", "kelly", np.nan], "B":[np.nan, "olivia", "terica", "", "amanda"], "C":[20 + 5j, 20 + 3j, 7, None, 8], "D":[14.8, 3, None, 2.3, 6]}) # find non-missing valuesdf.notnull()
Output :
Notice, the empty string also got mapped to true indicating that it is not a NaN value.
Python | Pandas dataframe.notnull() | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersPython | Pandas dataframe.notnull() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=YpXUoVnG1is" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
sagartomar9927
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. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 735,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.notnull() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the same size as that of the object on which it is applied, indicating whether each individual value is a na value or not. All of the non-missing values gets mapped to true and missing values get mapped to false. Note : Characters such as empty strings ” or numpy.inf are not considered NA values. (unless you set pandas.options.mode.use_inf_as_na = True). "
},
{
"code": null,
"e": 877,
"s": 735,
"text": "Syntax: DataFrame.notnull()Returns : Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value. "
},
{
"code": null,
"e": 965,
"s": 877,
"text": "Example #1: Use notnull() function to find all the non-missing value in the dataframe. "
},
{
"code": null,
"e": 973,
"s": 965,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf = pd.DataFrame({\"A\":[14, 4, 5, 4, 1], \"B\":[\"Sam\", \"olivia\", \"terica\", \"megan\", \"amanda\"], \"C\":[20 + 5j, 20 + 3j, 7, 3, 8], \"D\":[14, 3, 6, 2, 6]}) # Print the dataframedf",
"e": 1274,
"s": 973,
"text": null
},
{
"code": null,
"e": 1372,
"s": 1274,
"text": "Let’s use the dataframe.notnull() function to find all the non-missing values in the dataframe. "
},
{
"code": null,
"e": 1380,
"s": 1372,
"text": "Python3"
},
{
"code": "# find non-na valuesdf.notnull()",
"e": 1413,
"s": 1380,
"text": null
},
{
"code": null,
"e": 1424,
"s": 1413,
"text": "Output : "
},
{
"code": null,
"e": 1709,
"s": 1424,
"text": "As we can see in the output, all the non-missing values in the dataframe has been mapped to true. There is no false value as there is no missing value in the dataframe Example #2: Use notnull() function to find the non-missing values, when there are missing values in the dataframe. "
},
{
"code": null,
"e": 1717,
"s": 1709,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[\"Sandy\", \"alex\", \"brook\", \"kelly\", np.nan], \"B\":[np.nan, \"olivia\", \"terica\", \"\", \"amanda\"], \"C\":[20 + 5j, 20 + 3j, 7, None, 8], \"D\":[14.8, 3, None, 2.3, 6]}) # find non-missing valuesdf.notnull()",
"e": 2060,
"s": 1717,
"text": null
},
{
"code": null,
"e": 2071,
"s": 2060,
"text": "Output : "
},
{
"code": null,
"e": 2161,
"s": 2071,
"text": "Notice, the empty string also got mapped to true indicating that it is not a NaN value. "
},
{
"code": null,
"e": 3049,
"s": 2161,
"text": "Python | Pandas dataframe.notnull() | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersPython | Pandas dataframe.notnull() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=YpXUoVnG1is\" 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": 3066,
"s": 3051,
"text": "sagartomar9927"
},
{
"code": null,
"e": 3090,
"s": 3066,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3122,
"s": 3090,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 3136,
"s": 3122,
"text": "Python-pandas"
},
{
"code": null,
"e": 3143,
"s": 3136,
"text": "Python"
}
] |
C/C++ Preprocessors | 22 Jun, 2022
As the name suggests, Preprocessors are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++. Let us have a look at these steps before we actually start learning about Preprocessors.
You can see the intermediate steps in the above diagram. The source code written by programmers is first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an expanded source code file is generated named “program.i”. This expanded file is compiled by the compiler and an object code file is generated named “program.obj”. Finally, the linker links this object code file to the object code of the library functions to generate the executable file “program.exe”.
Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get executed. Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include extra code in your program. We can place these preprocessor directives anywhere in our program.
There are 4 Main Types of Preprocessor Directives:
MacrosFile InclusionConditional CompilationOther directives
Macros
File Inclusion
Conditional Compilation
Other directives
Let us now learn about each of these directives in detail.
Macros are pieces of code in a program that is given some name. Whenever this name is encountered by the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro. Let us now understand the macro definition with the help of a program:
C++
C
#include <iostream> // macro definition#define LIMIT 5int main(){ for (int i = 0; i < LIMIT; i++) { std::cout << i << "\n"; } return 0;}
#include <stdio.h> // macro definition#define LIMIT 5int main(){ for (int i = 0; i < LIMIT; i++) { printf("%d \n",i); } return 0;}
Output:
0
1
2
3
4
In the above program, when the compiler executes the word LIMIT, it replaces it with 5. The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-colon to end.
Macros With Arguments: We can also pass arguments to macros. Macros defined with arguments work similarly to functions. Let us understand this with a program:
C++
C
#include <iostream> // macro with parameter#define AREA(l, b) (l * b)int main(){ int l1 = 10, l2 = 5, area; area = AREA(l1, l2); std::cout << "Area of rectangle is: " << area; return 0;}
#include <stdio.h> // macro with parameter#define AREA(l, b) (l * b)int main(){ int l1 = 10, l2 = 5, area; area = AREA(l1, l2); printf("Area of rectangle is: %d", area); return 0;}
Output:
Area of rectangle is: 50
We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it replaces it with the statement (l*b). Not only this, but the values passed to the macro template AREA(l, b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5.
This type of preprocessor directive tells the compiler to include a file in the source code program. There are two types of files that can be included by the user in the program: Header files or Standard files: These files contain definitions of pre-defined functions like printf(), scanf(), etc. These files must be included to work with these functions. Different functions are declared in different header files. For example, standard I/O functions are in the ‘iostream’ file whereas functions that perform string operations are in the ‘string’ file. Syntax:
#include< file_name >
where file_name is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to look for the file in the standard directory.
User-defined files: When a program becomes very large, it is a good practice to divide it into smaller files and include them whenever needed. These types of files are user-defined files. These files can be included as:
#include"filename"
Conditional Compilation directives are a type of directive that helps to compile a specific portion of the program or to skip the compilation of some specific part of the program based on some conditions. This can be done with the help of the two preprocessing commands ‘ifdef‘ and ‘endif‘. Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally, but if it is not defined, the compiler will simply skip this block of statements.
Apart from the above directives, there are two more directives that are not commonly used. These are: #undef Directive: The #undef directive is used to undefine an existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT” statement will evaluate as false.
#pragma Directive: This directive is a special purpose directive and is used to turn on or off some features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler. Some of the #pragma directives are discussed below:
#pragma startup and #pragma exit: These directives help us to specify the functions that are needed to run before program startup (before the control passes to main()) and just before program exit (just before the control returns from main()).
Note: Below program will not work with GCC compilers.
C++
C
#include <bits/stdc++.h>using namespace std; void func1();void func2(); #pragma startup func1#pragma exit func2 void func1(){ cout << "Inside func1()\n";} void func2(){ cout << "Inside func2()\n";} int main(){ void func1(); void func2(); cout << "Inside main()\n"; return 0;} // This code is contributed by shivanisinghss2110
#include <stdio.h> void func1();void func2(); #pragma startup func1#pragma exit func2 void func1(){ printf("Inside func1()\n");} void func2(){ printf("Inside func2()\n");} int main(){ void func1(); void func2(); printf("Inside main()\n"); return 0;}
Output:
Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:
Inside main()
This happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers.
C++
C
#include <iostream>using namespace std; void func1();void func2(); void __attribute__((constructor)) func1();void __attribute__((destructor)) func2(); void func1(){ printf("Inside func1()\n");} void func2(){ printf("Inside func2()\n");} // Driver codeint main(){ printf("Inside main()\n"); return 0;} // This code is contributed by Shivani
#include <stdio.h> void func1();void func2(); void __attribute__((constructor)) func1();void __attribute__((destructor)) func2(); void func1(){ printf("Inside func1()\n");} void func2(){ printf("Inside func2()\n");} int main(){ printf("Inside main()\n"); return 0;}
#pragma warn Directive: This directive is used to hide the warning message which is displayed during compilation. We can hide the warnings as shown below:
#pragma warn -rvl: This directive hides those warnings which are raised when a function that is supposed to return a value does not return a value.
#pragma warn -par: This directive hides those warnings which are raised when a function does not use the parameters passed to it.
#pragma warn -rch: This directive hides those warnings which are raised when a code is unreachable. For example, any code written after the return statement in a function is unreachable.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
RandomGuy7
Mohit Sehgal
abhishek_ranjan7
kumarvishal07442
shivanisinghss2110
harsh_shokeen
sriparnxnw7
C Basics
C-Macro & Preprocessor
CPP-Basics
cpp-macros
Macro & Preprocessor
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 340,
"s": 54,
"text": "As the name suggests, Preprocessors are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++. Let us have a look at these steps before we actually start learning about Preprocessors."
},
{
"code": null,
"e": 847,
"s": 340,
"text": "You can see the intermediate steps in the above diagram. The source code written by programmers is first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an expanded source code file is generated named “program.i”. This expanded file is compiled by the compiler and an object code file is generated named “program.obj”. Finally, the linker links this object code file to the object code of the library functions to generate the executable file “program.exe”. "
},
{
"code": null,
"e": 1512,
"s": 847,
"text": "Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get executed. Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include extra code in your program. We can place these preprocessor directives anywhere in our program. "
},
{
"code": null,
"e": 1565,
"s": 1512,
"text": "There are 4 Main Types of Preprocessor Directives: "
},
{
"code": null,
"e": 1625,
"s": 1565,
"text": "MacrosFile InclusionConditional CompilationOther directives"
},
{
"code": null,
"e": 1632,
"s": 1625,
"text": "Macros"
},
{
"code": null,
"e": 1647,
"s": 1632,
"text": "File Inclusion"
},
{
"code": null,
"e": 1671,
"s": 1647,
"text": "Conditional Compilation"
},
{
"code": null,
"e": 1688,
"s": 1671,
"text": "Other directives"
},
{
"code": null,
"e": 1748,
"s": 1688,
"text": "Let us now learn about each of these directives in detail. "
},
{
"code": null,
"e": 2047,
"s": 1748,
"text": "Macros are pieces of code in a program that is given some name. Whenever this name is encountered by the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro. Let us now understand the macro definition with the help of a program:"
},
{
"code": null,
"e": 2051,
"s": 2047,
"text": "C++"
},
{
"code": null,
"e": 2053,
"s": 2051,
"text": "C"
},
{
"code": "#include <iostream> // macro definition#define LIMIT 5int main(){ for (int i = 0; i < LIMIT; i++) { std::cout << i << \"\\n\"; } return 0;}",
"e": 2207,
"s": 2053,
"text": null
},
{
"code": "#include <stdio.h> // macro definition#define LIMIT 5int main(){ for (int i = 0; i < LIMIT; i++) { printf(\"%d \\n\",i); } return 0;}",
"e": 2355,
"s": 2207,
"text": null
},
{
"code": null,
"e": 2364,
"s": 2355,
"text": "Output: "
},
{
"code": null,
"e": 2374,
"s": 2364,
"text": "0\n1\n2\n3\n4"
},
{
"code": null,
"e": 2559,
"s": 2374,
"text": "In the above program, when the compiler executes the word LIMIT, it replaces it with 5. The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion. "
},
{
"code": null,
"e": 2679,
"s": 2559,
"text": "Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-colon to end."
},
{
"code": null,
"e": 2839,
"s": 2679,
"text": "Macros With Arguments: We can also pass arguments to macros. Macros defined with arguments work similarly to functions. Let us understand this with a program: "
},
{
"code": null,
"e": 2843,
"s": 2839,
"text": "C++"
},
{
"code": null,
"e": 2845,
"s": 2843,
"text": "C"
},
{
"code": "#include <iostream> // macro with parameter#define AREA(l, b) (l * b)int main(){ int l1 = 10, l2 = 5, area; area = AREA(l1, l2); std::cout << \"Area of rectangle is: \" << area; return 0;}",
"e": 3047,
"s": 2845,
"text": null
},
{
"code": "#include <stdio.h> // macro with parameter#define AREA(l, b) (l * b)int main(){ int l1 = 10, l2 = 5, area; area = AREA(l1, l2); printf(\"Area of rectangle is: %d\", area); return 0;}",
"e": 3243,
"s": 3047,
"text": null
},
{
"code": null,
"e": 3252,
"s": 3243,
"text": "Output: "
},
{
"code": null,
"e": 3277,
"s": 3252,
"text": "Area of rectangle is: 50"
},
{
"code": null,
"e": 3574,
"s": 3277,
"text": "We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it replaces it with the statement (l*b). Not only this, but the values passed to the macro template AREA(l, b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5. "
},
{
"code": null,
"e": 4136,
"s": 3574,
"text": "This type of preprocessor directive tells the compiler to include a file in the source code program. There are two types of files that can be included by the user in the program: Header files or Standard files: These files contain definitions of pre-defined functions like printf(), scanf(), etc. These files must be included to work with these functions. Different functions are declared in different header files. For example, standard I/O functions are in the ‘iostream’ file whereas functions that perform string operations are in the ‘string’ file. Syntax:"
},
{
"code": null,
"e": 4158,
"s": 4136,
"text": "#include< file_name >"
},
{
"code": null,
"e": 4306,
"s": 4158,
"text": "where file_name is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to look for the file in the standard directory. "
},
{
"code": null,
"e": 4526,
"s": 4306,
"text": "User-defined files: When a program becomes very large, it is a good practice to divide it into smaller files and include them whenever needed. These types of files are user-defined files. These files can be included as:"
},
{
"code": null,
"e": 4545,
"s": 4526,
"text": "#include\"filename\""
},
{
"code": null,
"e": 4844,
"s": 4545,
"text": "Conditional Compilation directives are a type of directive that helps to compile a specific portion of the program or to skip the compilation of some specific part of the program based on some conditions. This can be done with the help of the two preprocessing commands ‘ifdef‘ and ‘endif‘. Syntax:"
},
{
"code": null,
"e": 4951,
"s": 4844,
"text": "#ifdef macro_name\n statement1;\n statement2;\n statement3;\n .\n .\n .\n statementN;\n#endif"
},
{
"code": null,
"e": 5138,
"s": 4951,
"text": "If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally, but if it is not defined, the compiler will simply skip this block of statements. "
},
{
"code": null,
"e": 5343,
"s": 5138,
"text": "Apart from the above directives, there are two more directives that are not commonly used. These are: #undef Directive: The #undef directive is used to undefine an existing macro. This directive works as:"
},
{
"code": null,
"e": 5356,
"s": 5343,
"text": "#undef LIMIT"
},
{
"code": null,
"e": 5495,
"s": 5356,
"text": "Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT” statement will evaluate as false. "
},
{
"code": null,
"e": 5748,
"s": 5495,
"text": "#pragma Directive: This directive is a special purpose directive and is used to turn on or off some features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler. Some of the #pragma directives are discussed below: "
},
{
"code": null,
"e": 5993,
"s": 5748,
"text": "#pragma startup and #pragma exit: These directives help us to specify the functions that are needed to run before program startup (before the control passes to main()) and just before program exit (just before the control returns from main()). "
},
{
"code": null,
"e": 6048,
"s": 5993,
"text": "Note: Below program will not work with GCC compilers. "
},
{
"code": null,
"e": 6052,
"s": 6048,
"text": "C++"
},
{
"code": null,
"e": 6054,
"s": 6052,
"text": "C"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void func1();void func2(); #pragma startup func1#pragma exit func2 void func1(){ cout << \"Inside func1()\\n\";} void func2(){ cout << \"Inside func2()\\n\";} int main(){ void func1(); void func2(); cout << \"Inside main()\\n\"; return 0;} // This code is contributed by shivanisinghss2110",
"e": 6410,
"s": 6054,
"text": null
},
{
"code": "#include <stdio.h> void func1();void func2(); #pragma startup func1#pragma exit func2 void func1(){ printf(\"Inside func1()\\n\");} void func2(){ printf(\"Inside func2()\\n\");} int main(){ void func1(); void func2(); printf(\"Inside main()\\n\"); return 0;}",
"e": 6679,
"s": 6410,
"text": null
},
{
"code": null,
"e": 6688,
"s": 6679,
"text": "Output: "
},
{
"code": null,
"e": 6732,
"s": 6688,
"text": "Inside func1()\nInside main()\nInside func2()"
},
{
"code": null,
"e": 6814,
"s": 6732,
"text": "The above code will produce the output as given below when run on GCC compilers: "
},
{
"code": null,
"e": 6828,
"s": 6814,
"text": "Inside main()"
},
{
"code": null,
"e": 6971,
"s": 6828,
"text": "This happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers. "
},
{
"code": null,
"e": 6975,
"s": 6971,
"text": "C++"
},
{
"code": null,
"e": 6977,
"s": 6975,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; void func1();void func2(); void __attribute__((constructor)) func1();void __attribute__((destructor)) func2(); void func1(){ printf(\"Inside func1()\\n\");} void func2(){ printf(\"Inside func2()\\n\");} // Driver codeint main(){ printf(\"Inside main()\\n\"); return 0;} // This code is contributed by Shivani",
"e": 7330,
"s": 6977,
"text": null
},
{
"code": "#include <stdio.h> void func1();void func2(); void __attribute__((constructor)) func1();void __attribute__((destructor)) func2(); void func1(){ printf(\"Inside func1()\\n\");} void func2(){ printf(\"Inside func2()\\n\");} int main(){ printf(\"Inside main()\\n\"); return 0;}",
"e": 7609,
"s": 7330,
"text": null
},
{
"code": null,
"e": 7765,
"s": 7609,
"text": "#pragma warn Directive: This directive is used to hide the warning message which is displayed during compilation. We can hide the warnings as shown below: "
},
{
"code": null,
"e": 7913,
"s": 7765,
"text": "#pragma warn -rvl: This directive hides those warnings which are raised when a function that is supposed to return a value does not return a value."
},
{
"code": null,
"e": 8043,
"s": 7913,
"text": "#pragma warn -par: This directive hides those warnings which are raised when a function does not use the parameters passed to it."
},
{
"code": null,
"e": 8230,
"s": 8043,
"text": "#pragma warn -rch: This directive hides those warnings which are raised when a code is unreachable. For example, any code written after the return statement in a function is unreachable."
},
{
"code": null,
"e": 8654,
"s": 8230,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8665,
"s": 8654,
"text": "RandomGuy7"
},
{
"code": null,
"e": 8678,
"s": 8665,
"text": "Mohit Sehgal"
},
{
"code": null,
"e": 8695,
"s": 8678,
"text": "abhishek_ranjan7"
},
{
"code": null,
"e": 8712,
"s": 8695,
"text": "kumarvishal07442"
},
{
"code": null,
"e": 8731,
"s": 8712,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 8745,
"s": 8731,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 8757,
"s": 8745,
"text": "sriparnxnw7"
},
{
"code": null,
"e": 8766,
"s": 8757,
"text": "C Basics"
},
{
"code": null,
"e": 8789,
"s": 8766,
"text": "C-Macro & Preprocessor"
},
{
"code": null,
"e": 8800,
"s": 8789,
"text": "CPP-Basics"
},
{
"code": null,
"e": 8811,
"s": 8800,
"text": "cpp-macros"
},
{
"code": null,
"e": 8832,
"s": 8811,
"text": "Macro & Preprocessor"
},
{
"code": null,
"e": 8843,
"s": 8832,
"text": "C Language"
},
{
"code": null,
"e": 8847,
"s": 8843,
"text": "C++"
},
{
"code": null,
"e": 8851,
"s": 8847,
"text": "CPP"
}
] |
Output of C Programs | Set 3 | 03 Feb, 2021
Predict the output of the below program. Question 1
c
#include <stdio.h>int main(){ printf("%p", main); getchar(); return 0;}
Output: Address of function main. Explanation: Name of the function is actually a pointer variable to the function and prints the address of the function. Symbol table is implemented like this.
struct
{
char *name;
int (*funcptr)();
}
symtab[] = {
"func", func,
"anotherfunc", anotherfunc,
};
Question 2
c
#include <stdio.h>int main(){ printf("\new_c_question\by"); printf("\rgeeksforgeeks"); getchar(); return 0;}
Output: geeksforgeeks Explanation: First printf prints “ew_c_questioy”. Second printf has \r in it so it goes back to start of the line and starts printing characters.Now try to print following without using any of the escape characters.
new c questions by
geeksforgeeks
Question 3
c
# include<stdio.h># include<stdlib.h> void fun(int *a){ a = (int*)malloc(sizeof(int));} int main(){ int *p; fun(p); *p = 6; printf("%d\n",*p); getchar(); return(0);}
It does not work. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer.This is because fun() makes a copy of the pointer, so when malloc() is called, it is setting the copied pointer to the memory location, not p. p is pointing to random memory before and after the call to fun(), and when you dereference it, it will crash.If you want to add memory to a pointer from a function, you need to pass the address of the pointer (ie. double pointer).Thanks to John Doe for providing the correct solution. For better understanding please go through the following link: https://stackoverflow.com/questions/1398307/how-can-i-allocate-memory-and-return-it-via-a-pointer-parameter-to-the-callingQuestion 4
c
#include <stdio.h>int main(){ int i; i = 1, 2, 3; printf("i = %d\n", i); getchar(); return 0;}
Output: 1 The above program prints 1. Associativity of comma operator is from left to right, but = operator has higher precedence than comma operator. Therefore the statement i = 1, 2, 3 is treated as (i = 1), 2, 3 by the compiler.Now it should be easy to tell output of below program.
c
#include <stdio.h>int main(){ int i; i = (1, 2, 3); printf("i = %d\n", i); getchar(); return 0;}
Question 5
c
#include <stdio.h>int main(){ int first = 50, second = 60, third; third = first /* Will this comment work? */ + second; printf("%d /* And this? */ \n", third); getchar(); return 0;}
Output: 110 /* And this? */ Explanation: Compiler removes everything between “/*” and “*/” if they are not present inside double quotes (“”).
marant102
domkarchel38
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 105,
"s": 52,
"text": "Predict the output of the below program. Question 1 "
},
{
"code": null,
"e": 107,
"s": 105,
"text": "c"
},
{
"code": "#include <stdio.h>int main(){ printf(\"%p\", main); getchar(); return 0;}",
"e": 182,
"s": 107,
"text": null
},
{
"code": null,
"e": 377,
"s": 182,
"text": "Output: Address of function main. Explanation: Name of the function is actually a pointer variable to the function and prints the address of the function. Symbol table is implemented like this. "
},
{
"code": null,
"e": 490,
"s": 377,
"text": "struct \n{\n char *name;\n int (*funcptr)();\n}\nsymtab[] = {\n \"func\", func,\n \"anotherfunc\", anotherfunc,\n}; "
},
{
"code": null,
"e": 503,
"s": 490,
"text": "Question 2 "
},
{
"code": null,
"e": 505,
"s": 503,
"text": "c"
},
{
"code": "#include <stdio.h>int main(){ printf(\"\\new_c_question\\by\"); printf(\"\\rgeeksforgeeks\"); getchar(); return 0;}",
"e": 623,
"s": 505,
"text": null
},
{
"code": null,
"e": 862,
"s": 623,
"text": "Output: geeksforgeeks Explanation: First printf prints “ew_c_questioy”. Second printf has \\r in it so it goes back to start of the line and starts printing characters.Now try to print following without using any of the escape characters. "
},
{
"code": null,
"e": 895,
"s": 862,
"text": "new c questions by\ngeeksforgeeks"
},
{
"code": null,
"e": 908,
"s": 895,
"text": "Question 3 "
},
{
"code": null,
"e": 910,
"s": 908,
"text": "c"
},
{
"code": "# include<stdio.h># include<stdlib.h> void fun(int *a){ a = (int*)malloc(sizeof(int));} int main(){ int *p; fun(p); *p = 6; printf(\"%d\\n\",*p); getchar(); return(0);}",
"e": 1101,
"s": 910,
"text": null
},
{
"code": null,
"e": 1837,
"s": 1101,
"text": "It does not work. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer.This is because fun() makes a copy of the pointer, so when malloc() is called, it is setting the copied pointer to the memory location, not p. p is pointing to random memory before and after the call to fun(), and when you dereference it, it will crash.If you want to add memory to a pointer from a function, you need to pass the address of the pointer (ie. double pointer).Thanks to John Doe for providing the correct solution. For better understanding please go through the following link: https://stackoverflow.com/questions/1398307/how-can-i-allocate-memory-and-return-it-via-a-pointer-parameter-to-the-callingQuestion 4 "
},
{
"code": null,
"e": 1839,
"s": 1837,
"text": "c"
},
{
"code": "#include <stdio.h>int main(){ int i; i = 1, 2, 3; printf(\"i = %d\\n\", i); getchar(); return 0;}",
"e": 1958,
"s": 1839,
"text": null
},
{
"code": null,
"e": 2244,
"s": 1958,
"text": "Output: 1 The above program prints 1. Associativity of comma operator is from left to right, but = operator has higher precedence than comma operator. Therefore the statement i = 1, 2, 3 is treated as (i = 1), 2, 3 by the compiler.Now it should be easy to tell output of below program."
},
{
"code": null,
"e": 2246,
"s": 2244,
"text": "c"
},
{
"code": "#include <stdio.h>int main(){ int i; i = (1, 2, 3); printf(\"i = %d\\n\", i); getchar(); return 0;}",
"e": 2369,
"s": 2246,
"text": null
},
{
"code": null,
"e": 2381,
"s": 2369,
"text": "Question 5 "
},
{
"code": null,
"e": 2383,
"s": 2381,
"text": "c"
},
{
"code": "#include <stdio.h>int main(){ int first = 50, second = 60, third; third = first /* Will this comment work? */ + second; printf(\"%d /* And this? */ \\n\", third); getchar(); return 0;}",
"e": 2586,
"s": 2383,
"text": null
},
{
"code": null,
"e": 2728,
"s": 2586,
"text": "Output: 110 /* And this? */ Explanation: Compiler removes everything between “/*” and “*/” if they are not present inside double quotes (“”)."
},
{
"code": null,
"e": 2738,
"s": 2728,
"text": "marant102"
},
{
"code": null,
"e": 2751,
"s": 2738,
"text": "domkarchel38"
},
{
"code": null,
"e": 2760,
"s": 2751,
"text": "C-Output"
},
{
"code": null,
"e": 2775,
"s": 2760,
"text": "Program Output"
}
] |
Program to Count numbers on fingers | 15 Jun, 2021
Count the given numbers on your fingers and find the correct finger on which the number ends.
The first number starts from the thumb, second on the index finger, third on the middle finger, fourth on the ring finger, and fifth on the little finger.
Again six comes on the ring finger and so on.
Here we observer a pattern, 8(last number) and 2 ends up in 2nd position, 3rd or 7th on the middle finger, and so on.
The pattern keeps repeating after every 8 numbers1 to 89 to 1617 to 24, and so on
1 to 8
9 to 16
17 to 24, and so on
Examples:
Input : 17
Output :1
Input :27
Output :3
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to Count numbers on fingers#include <iostream>using namespace std; int count_num_finger(int n){ int r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r;} // Driver codeint main(){ int n; n = 30; cout << count_num_finger(n); return 0;}
// Java Program to Count numbers on fingersclass GFG{static int count_num_finger(int n){ int r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r;} // Driver Codepublic static void main(String[] args){ int n; n = 30; System.out.println(count_num_finger(n));}} // This code is contributed// by Mukul Singh
def count_num_finger( n ): r = n % 8 if r == 0: return 2 if r < 5: return r else: return 10 - r # Driver Coden = 30print(count_num_finger(n)) # This code is contributed by "Sharad_Bhardwaj".
// C# Program to Count numbers on fingersusing System; class GFG{ static int count_num_finger(int n){ int r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r;} // Driver Codepublic static void Main(String[] args){ int n; n = 30; Console.WriteLine(count_num_finger(n));}} // This code is contributed by Princi Singh
<?phpfunction count_num_finger( $n ){ $r = $n % 8; if ($r == 2) return 0; if ($r < 5) return $r; else return 10 - $r;} // Driver Code$n = 30;echo(count_num_finger($n)); // This code is contributed// by Aman Ojha?>
<script> // Javascript Program to Count numbers on fingers function count_num_finger(n) { let r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r; } let n; n = 30; document.write(count_num_finger(n)); // This code is contributed by mukesh07.</script>
Output:
4
Asked in Paytm Campus Placement August 2017 This article is contributed by Dinesh Malav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Aman ojha
Code_Mech
princi singh
AyushGupta31
mukesh07
logical-thinking
Paytm
School Programming
Paytm
logical-thinking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 148,
"s": 52,
"text": "Count the given numbers on your fingers and find the correct finger on which the number ends. "
},
{
"code": null,
"e": 303,
"s": 148,
"text": "The first number starts from the thumb, second on the index finger, third on the middle finger, fourth on the ring finger, and fifth on the little finger."
},
{
"code": null,
"e": 349,
"s": 303,
"text": "Again six comes on the ring finger and so on."
},
{
"code": null,
"e": 467,
"s": 349,
"text": "Here we observer a pattern, 8(last number) and 2 ends up in 2nd position, 3rd or 7th on the middle finger, and so on."
},
{
"code": null,
"e": 549,
"s": 467,
"text": "The pattern keeps repeating after every 8 numbers1 to 89 to 1617 to 24, and so on"
},
{
"code": null,
"e": 556,
"s": 549,
"text": "1 to 8"
},
{
"code": null,
"e": 564,
"s": 556,
"text": "9 to 16"
},
{
"code": null,
"e": 584,
"s": 564,
"text": "17 to 24, and so on"
},
{
"code": null,
"e": 598,
"s": 586,
"text": "Examples: "
},
{
"code": null,
"e": 640,
"s": 598,
"text": "Input : 17\nOutput :1\n\nInput :27\nOutput :3"
},
{
"code": null,
"e": 648,
"s": 644,
"text": "C++"
},
{
"code": null,
"e": 653,
"s": 648,
"text": "Java"
},
{
"code": null,
"e": 661,
"s": 653,
"text": "Python3"
},
{
"code": null,
"e": 664,
"s": 661,
"text": "C#"
},
{
"code": null,
"e": 668,
"s": 664,
"text": "PHP"
},
{
"code": null,
"e": 679,
"s": 668,
"text": "Javascript"
},
{
"code": "// CPP Program to Count numbers on fingers#include <iostream>using namespace std; int count_num_finger(int n){ int r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r;} // Driver codeint main(){ int n; n = 30; cout << count_num_finger(n); return 0;}",
"e": 996,
"s": 679,
"text": null
},
{
"code": "// Java Program to Count numbers on fingersclass GFG{static int count_num_finger(int n){ int r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r;} // Driver Codepublic static void main(String[] args){ int n; n = 30; System.out.println(count_num_finger(n));}} // This code is contributed// by Mukul Singh",
"e": 1363,
"s": 996,
"text": null
},
{
"code": "def count_num_finger( n ): r = n % 8 if r == 0: return 2 if r < 5: return r else: return 10 - r # Driver Coden = 30print(count_num_finger(n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 1587,
"s": 1363,
"text": null
},
{
"code": "// C# Program to Count numbers on fingersusing System; class GFG{ static int count_num_finger(int n){ int r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r;} // Driver Codepublic static void Main(String[] args){ int n; n = 30; Console.WriteLine(count_num_finger(n));}} // This code is contributed by Princi Singh",
"e": 1973,
"s": 1587,
"text": null
},
{
"code": "<?phpfunction count_num_finger( $n ){ $r = $n % 8; if ($r == 2) return 0; if ($r < 5) return $r; else return 10 - $r;} // Driver Code$n = 30;echo(count_num_finger($n)); // This code is contributed// by Aman Ojha?>",
"e": 2224,
"s": 1973,
"text": null
},
{
"code": "<script> // Javascript Program to Count numbers on fingers function count_num_finger(n) { let r = n % 8; if (r == 0) return 2; if (r < 5) return r; else return 10 - r; } let n; n = 30; document.write(count_num_finger(n)); // This code is contributed by mukesh07.</script>",
"e": 2589,
"s": 2224,
"text": null
},
{
"code": null,
"e": 2599,
"s": 2589,
"text": "Output: "
},
{
"code": null,
"e": 2601,
"s": 2599,
"text": "4"
},
{
"code": null,
"e": 3066,
"s": 2601,
"text": "Asked in Paytm Campus Placement August 2017 This article is contributed by Dinesh Malav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3076,
"s": 3066,
"text": "Aman ojha"
},
{
"code": null,
"e": 3086,
"s": 3076,
"text": "Code_Mech"
},
{
"code": null,
"e": 3099,
"s": 3086,
"text": "princi singh"
},
{
"code": null,
"e": 3112,
"s": 3099,
"text": "AyushGupta31"
},
{
"code": null,
"e": 3121,
"s": 3112,
"text": "mukesh07"
},
{
"code": null,
"e": 3138,
"s": 3121,
"text": "logical-thinking"
},
{
"code": null,
"e": 3144,
"s": 3138,
"text": "Paytm"
},
{
"code": null,
"e": 3163,
"s": 3144,
"text": "School Programming"
},
{
"code": null,
"e": 3169,
"s": 3163,
"text": "Paytm"
},
{
"code": null,
"e": 3186,
"s": 3169,
"text": "logical-thinking"
}
] |
Red-Black Tree | Set 1 (Introduction) | 07 Jun, 2022
A red-black tree is a kind of self-balancing binary search tree where each node has an extra bit, and that bit is often interpreted as the color (red or black). These colors are used to ensure that the tree remains balanced during insertions and deletions. Although the balance of the tree is not perfect, it is good enough to reduce the searching time and maintain it around O(log n) time, where n is the total number of elements in the tree. This tree was invented in 1972 by Rudolf Bayer.
It must be noted that as each node requires only 1 bit of space to store the color information, these types of trees show identical memory footprints to the classic (uncolored) binary search tree.
Every node has a color either red or black.The root of the tree is always black.There are no two adjacent red nodes (A red node cannot have a red parent or red child).Every path from a node (including root) to any of its descendants NULL nodes has the same number of black nodes.All leaf nodes are black nodes.
Every node has a color either red or black.
The root of the tree is always black.
There are no two adjacent red nodes (A red node cannot have a red parent or red child).
Every path from a node (including root) to any of its descendants NULL nodes has the same number of black nodes.
All leaf nodes are black nodes.
Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height of the BST. The cost of these operations may become O(n) for a skewed Binary tree. If we make sure that the height of the tree remains O(log n) after every insertion and deletion, then we can guarantee an upper bound of O(log n) for all these operations. The height of a Red-Black tree is always O(log n) where n is the number of nodes in the tree.
“n” is the total number of elements in the red-black tree.
Comparison with AVL Tree:The AVL trees are more balanced compared to Red-Black Trees, but they may cause more rotations during insertion and deletion. So if your application involves frequent insertions and deletions, then Red-Black trees should be preferred. And if the insertions and deletions are less frequent and search is a more frequent operation, then AVL tree should be preferred over the Red-Black Tree.
How does a Red-Black Tree ensure balance?A simple example to understand balancing is, that a chain of 3 nodes is not possible in the Red-Black tree. We can try any combination of colors and see if all of them violate the Red-Black tree property.
Proper structure of three noded Red-black tree
The black height of the red-black tree is the number of black nodes on a path from the root node to a leaf node. Leaf nodes are also counted as black nodes. So, a red-black tree of height h has black height >= h/2.Height of a red-black tree with n nodes is h<= 2 log2(n + 1).All leaves (NIL) are black.The black depth of a node is defined as the number of black nodes from the root to that node i.e the number of black ancestors.Every red-black tree is a special case of a binary tree.
The black height of the red-black tree is the number of black nodes on a path from the root node to a leaf node. Leaf nodes are also counted as black nodes. So, a red-black tree of height h has black height >= h/2.
Height of a red-black tree with n nodes is h<= 2 log2(n + 1).
All leaves (NIL) are black.
The black depth of a node is defined as the number of black nodes from the root to that node i.e the number of black ancestors.
Every red-black tree is a special case of a binary tree.
Black height is the number of black nodes on a path from the root to a leaf. Leaf nodes are also counted black nodes. From the above properties 3 and 4, we can derive, a Red-Black Tree of height h has black-height >= h/2.
Number of nodes from a node to its farthest descendant leaf is no more than twice as the number of nodes to the nearest descendant leaf.
Every Red Black Tree with n nodes has height <= 2Log2(n+1) This can be proved using the following facts:
For a general Binary Tree, let k be the minimum number of nodes on all root to NULL paths, then n >= 2k – 1 (Ex. If k is 3, then n is at least 7). This expression can also be written as k <= Log2(n+1).From property 4 of Red-Black trees and above claim, we can say in a Red-Black Tree with n nodes, there is a root to leaf path with at-most Log2(n+1) black nodes.From properties 3 and 5 of Red-Black trees, we can claim that the number of black nodes in a Red-Black tree is at least ⌊ n/2 ⌋ where n is the total number of nodes.
For a general Binary Tree, let k be the minimum number of nodes on all root to NULL paths, then n >= 2k – 1 (Ex. If k is 3, then n is at least 7). This expression can also be written as k <= Log2(n+1).
From property 4 of Red-Black trees and above claim, we can say in a Red-Black Tree with n nodes, there is a root to leaf path with at-most Log2(n+1) black nodes.
From properties 3 and 5 of Red-Black trees, we can claim that the number of black nodes in a Red-Black tree is at least ⌊ n/2 ⌋ where n is the total number of nodes.
From the above points, we can conclude the fact that Red Black Tree with n nodes has a height <= 2Log2(n+1)
As every red-black tree is a special case of a binary tree so the searching algorithm of a red-black tree is similar to that of a binary tree.
Algorithm:
searchElement (tree, val)
Step 1:
If tree -> data = val OR tree = NULL
Return tree
Else
If val < data
Return searchElement (tree -> left, val)
Else
Return searchElement (tree -> right, val)
[ End of if ]
[ End of if ]
Step 2: END
For the program, you can refer it for AVL tree.
Example: Searching 11 in the following red-black tree.
Solution:
Start from the root.Compare the inserting element with root, if less than root, then recurse for left, else recurse for right.If the element to search is found anywhere, return true, else return false.
Start from the root.
Compare the inserting element with root, if less than root, then recurse for left, else recurse for right.
If the element to search is found anywhere, return true, else return false.
Just follow the blue bubble.
In this post, we introduced Red-Black trees and discussed how balance is ensured. The hard part is to maintain balance when keys are added and removed. We have also seen how to search an element from the red-black tree. We will soon be discussing insertion and deletion operations in coming posts on the Red-Black tree.
1) Is it possible to have all black nodes in a Red-Black tree? 2) Draw a Red-Black Tree that is not an AVL tree structure-wise?
Red-Black Tree Insertion Red-Black Tree Deletion
Most of the self-balancing BST library functions like map, multiset, and multimap in C++ ( or java pacakages like java.util.TreeMap and java.util.TreeSet ) use Red-Black Trees.It is used to implement CPU Scheduling Linux. Completely Fair Scheduler uses it. It is also used in the K-mean clustering algorithm in machine learning for reducing time complexity. Moreover, MySQL also uses the Red-Black tree for indexes on tables in order to reduce the searching and insertion time.
Most of the self-balancing BST library functions like map, multiset, and multimap in C++ ( or java pacakages like java.util.TreeMap and java.util.TreeSet ) use Red-Black Trees.
It is used to implement CPU Scheduling Linux. Completely Fair Scheduler uses it.
It is also used in the K-mean clustering algorithm in machine learning for reducing time complexity.
Moreover, MySQL also uses the Red-Black tree for indexes on tables in order to reduce the searching and insertion time.
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest
http://en.wikipedia.org/wiki/Red%E2%80%93black_tree
Video Lecture on Red-Black Tree by Tim Roughgarden
MIT Video Lecture on Red-Black Tree
MIT Lecture Notes on Red-Black Tree
LinPs
krikti
gongyq10
aditya_taparia
jadd1988
201801215
aspshita
divyanshmishra101010
harendrakumar123
Red Black Tree
Self-Balancing-BST
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 547,
"s": 54,
"text": "A red-black tree is a kind of self-balancing binary search tree where each node has an extra bit, and that bit is often interpreted as the color (red or black). These colors are used to ensure that the tree remains balanced during insertions and deletions. Although the balance of the tree is not perfect, it is good enough to reduce the searching time and maintain it around O(log n) time, where n is the total number of elements in the tree. This tree was invented in 1972 by Rudolf Bayer. "
},
{
"code": null,
"e": 745,
"s": 547,
"text": "It must be noted that as each node requires only 1 bit of space to store the color information, these types of trees show identical memory footprints to the classic (uncolored) binary search tree. "
},
{
"code": null,
"e": 1056,
"s": 745,
"text": "Every node has a color either red or black.The root of the tree is always black.There are no two adjacent red nodes (A red node cannot have a red parent or red child).Every path from a node (including root) to any of its descendants NULL nodes has the same number of black nodes.All leaf nodes are black nodes."
},
{
"code": null,
"e": 1100,
"s": 1056,
"text": "Every node has a color either red or black."
},
{
"code": null,
"e": 1138,
"s": 1100,
"text": "The root of the tree is always black."
},
{
"code": null,
"e": 1226,
"s": 1138,
"text": "There are no two adjacent red nodes (A red node cannot have a red parent or red child)."
},
{
"code": null,
"e": 1339,
"s": 1226,
"text": "Every path from a node (including root) to any of its descendants NULL nodes has the same number of black nodes."
},
{
"code": null,
"e": 1371,
"s": 1339,
"text": "All leaf nodes are black nodes."
},
{
"code": null,
"e": 1832,
"s": 1371,
"text": "Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height of the BST. The cost of these operations may become O(n) for a skewed Binary tree. If we make sure that the height of the tree remains O(log n) after every insertion and deletion, then we can guarantee an upper bound of O(log n) for all these operations. The height of a Red-Black tree is always O(log n) where n is the number of nodes in the tree. "
},
{
"code": null,
"e": 1892,
"s": 1832,
"text": "“n” is the total number of elements in the red-black tree. "
},
{
"code": null,
"e": 2306,
"s": 1892,
"text": "Comparison with AVL Tree:The AVL trees are more balanced compared to Red-Black Trees, but they may cause more rotations during insertion and deletion. So if your application involves frequent insertions and deletions, then Red-Black trees should be preferred. And if the insertions and deletions are less frequent and search is a more frequent operation, then AVL tree should be preferred over the Red-Black Tree."
},
{
"code": null,
"e": 2553,
"s": 2306,
"text": "How does a Red-Black Tree ensure balance?A simple example to understand balancing is, that a chain of 3 nodes is not possible in the Red-Black tree. We can try any combination of colors and see if all of them violate the Red-Black tree property. "
},
{
"code": null,
"e": 2600,
"s": 2553,
"text": "Proper structure of three noded Red-black tree"
},
{
"code": null,
"e": 3086,
"s": 2600,
"text": "The black height of the red-black tree is the number of black nodes on a path from the root node to a leaf node. Leaf nodes are also counted as black nodes. So, a red-black tree of height h has black height >= h/2.Height of a red-black tree with n nodes is h<= 2 log2(n + 1).All leaves (NIL) are black.The black depth of a node is defined as the number of black nodes from the root to that node i.e the number of black ancestors.Every red-black tree is a special case of a binary tree."
},
{
"code": null,
"e": 3301,
"s": 3086,
"text": "The black height of the red-black tree is the number of black nodes on a path from the root node to a leaf node. Leaf nodes are also counted as black nodes. So, a red-black tree of height h has black height >= h/2."
},
{
"code": null,
"e": 3363,
"s": 3301,
"text": "Height of a red-black tree with n nodes is h<= 2 log2(n + 1)."
},
{
"code": null,
"e": 3391,
"s": 3363,
"text": "All leaves (NIL) are black."
},
{
"code": null,
"e": 3519,
"s": 3391,
"text": "The black depth of a node is defined as the number of black nodes from the root to that node i.e the number of black ancestors."
},
{
"code": null,
"e": 3576,
"s": 3519,
"text": "Every red-black tree is a special case of a binary tree."
},
{
"code": null,
"e": 3799,
"s": 3576,
"text": "Black height is the number of black nodes on a path from the root to a leaf. Leaf nodes are also counted black nodes. From the above properties 3 and 4, we can derive, a Red-Black Tree of height h has black-height >= h/2. "
},
{
"code": null,
"e": 3936,
"s": 3799,
"text": "Number of nodes from a node to its farthest descendant leaf is no more than twice as the number of nodes to the nearest descendant leaf."
},
{
"code": null,
"e": 4041,
"s": 3936,
"text": "Every Red Black Tree with n nodes has height <= 2Log2(n+1) This can be proved using the following facts:"
},
{
"code": null,
"e": 4569,
"s": 4041,
"text": "For a general Binary Tree, let k be the minimum number of nodes on all root to NULL paths, then n >= 2k – 1 (Ex. If k is 3, then n is at least 7). This expression can also be written as k <= Log2(n+1).From property 4 of Red-Black trees and above claim, we can say in a Red-Black Tree with n nodes, there is a root to leaf path with at-most Log2(n+1) black nodes.From properties 3 and 5 of Red-Black trees, we can claim that the number of black nodes in a Red-Black tree is at least ⌊ n/2 ⌋ where n is the total number of nodes."
},
{
"code": null,
"e": 4771,
"s": 4569,
"text": "For a general Binary Tree, let k be the minimum number of nodes on all root to NULL paths, then n >= 2k – 1 (Ex. If k is 3, then n is at least 7). This expression can also be written as k <= Log2(n+1)."
},
{
"code": null,
"e": 4933,
"s": 4771,
"text": "From property 4 of Red-Black trees and above claim, we can say in a Red-Black Tree with n nodes, there is a root to leaf path with at-most Log2(n+1) black nodes."
},
{
"code": null,
"e": 5099,
"s": 4933,
"text": "From properties 3 and 5 of Red-Black trees, we can claim that the number of black nodes in a Red-Black tree is at least ⌊ n/2 ⌋ where n is the total number of nodes."
},
{
"code": null,
"e": 5207,
"s": 5099,
"text": "From the above points, we can conclude the fact that Red Black Tree with n nodes has a height <= 2Log2(n+1)"
},
{
"code": null,
"e": 5350,
"s": 5207,
"text": "As every red-black tree is a special case of a binary tree so the searching algorithm of a red-black tree is similar to that of a binary tree."
},
{
"code": null,
"e": 5361,
"s": 5350,
"text": "Algorithm:"
},
{
"code": null,
"e": 5620,
"s": 5361,
"text": "searchElement (tree, val)\nStep 1:\nIf tree -> data = val OR tree = NULL\n Return tree\nElse\nIf val < data\n Return searchElement (tree -> left, val)\n Else\n Return searchElement (tree -> right, val)\n [ End of if ]\n[ End of if ]\n\nStep 2: END"
},
{
"code": null,
"e": 5669,
"s": 5620,
"text": "For the program, you can refer it for AVL tree. "
},
{
"code": null,
"e": 5726,
"s": 5669,
"text": "Example: Searching 11 in the following red-black tree. "
},
{
"code": null,
"e": 5737,
"s": 5726,
"text": "Solution: "
},
{
"code": null,
"e": 5939,
"s": 5737,
"text": "Start from the root.Compare the inserting element with root, if less than root, then recurse for left, else recurse for right.If the element to search is found anywhere, return true, else return false."
},
{
"code": null,
"e": 5960,
"s": 5939,
"text": "Start from the root."
},
{
"code": null,
"e": 6067,
"s": 5960,
"text": "Compare the inserting element with root, if less than root, then recurse for left, else recurse for right."
},
{
"code": null,
"e": 6143,
"s": 6067,
"text": "If the element to search is found anywhere, return true, else return false."
},
{
"code": null,
"e": 6172,
"s": 6143,
"text": "Just follow the blue bubble."
},
{
"code": null,
"e": 6492,
"s": 6172,
"text": "In this post, we introduced Red-Black trees and discussed how balance is ensured. The hard part is to maintain balance when keys are added and removed. We have also seen how to search an element from the red-black tree. We will soon be discussing insertion and deletion operations in coming posts on the Red-Black tree."
},
{
"code": null,
"e": 6620,
"s": 6492,
"text": "1) Is it possible to have all black nodes in a Red-Black tree? 2) Draw a Red-Black Tree that is not an AVL tree structure-wise?"
},
{
"code": null,
"e": 6670,
"s": 6620,
"text": "Red-Black Tree Insertion Red-Black Tree Deletion "
},
{
"code": null,
"e": 7149,
"s": 6670,
"text": "Most of the self-balancing BST library functions like map, multiset, and multimap in C++ ( or java pacakages like java.util.TreeMap and java.util.TreeSet ) use Red-Black Trees.It is used to implement CPU Scheduling Linux. Completely Fair Scheduler uses it. It is also used in the K-mean clustering algorithm in machine learning for reducing time complexity. Moreover, MySQL also uses the Red-Black tree for indexes on tables in order to reduce the searching and insertion time."
},
{
"code": null,
"e": 7327,
"s": 7149,
"text": "Most of the self-balancing BST library functions like map, multiset, and multimap in C++ ( or java pacakages like java.util.TreeMap and java.util.TreeSet ) use Red-Black Trees."
},
{
"code": null,
"e": 7408,
"s": 7327,
"text": "It is used to implement CPU Scheduling Linux. Completely Fair Scheduler uses it."
},
{
"code": null,
"e": 7510,
"s": 7408,
"text": " It is also used in the K-mean clustering algorithm in machine learning for reducing time complexity."
},
{
"code": null,
"e": 7631,
"s": 7510,
"text": " Moreover, MySQL also uses the Red-Black tree for indexes on tables in order to reduce the searching and insertion time."
},
{
"code": null,
"e": 7746,
"s": 7631,
"text": "Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest"
},
{
"code": null,
"e": 7798,
"s": 7746,
"text": "http://en.wikipedia.org/wiki/Red%E2%80%93black_tree"
},
{
"code": null,
"e": 7849,
"s": 7798,
"text": "Video Lecture on Red-Black Tree by Tim Roughgarden"
},
{
"code": null,
"e": 7885,
"s": 7849,
"text": "MIT Video Lecture on Red-Black Tree"
},
{
"code": null,
"e": 7921,
"s": 7885,
"text": "MIT Lecture Notes on Red-Black Tree"
},
{
"code": null,
"e": 7927,
"s": 7921,
"text": "LinPs"
},
{
"code": null,
"e": 7934,
"s": 7927,
"text": "krikti"
},
{
"code": null,
"e": 7943,
"s": 7934,
"text": "gongyq10"
},
{
"code": null,
"e": 7958,
"s": 7943,
"text": "aditya_taparia"
},
{
"code": null,
"e": 7967,
"s": 7958,
"text": "jadd1988"
},
{
"code": null,
"e": 7977,
"s": 7967,
"text": "201801215"
},
{
"code": null,
"e": 7986,
"s": 7977,
"text": "aspshita"
},
{
"code": null,
"e": 8007,
"s": 7986,
"text": "divyanshmishra101010"
},
{
"code": null,
"e": 8024,
"s": 8007,
"text": "harendrakumar123"
},
{
"code": null,
"e": 8039,
"s": 8024,
"text": "Red Black Tree"
},
{
"code": null,
"e": 8058,
"s": 8039,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 8082,
"s": 8058,
"text": "Advanced Data Structure"
}
] |
Interesting Commands on Mac Terminal | 25 Aug, 2020
Terminal is one of the most important tools in MacOS be it any field. To get good knowledge about the terminal is important. It teaches you many things in an innovative way which is liked by most of the developers. It’s a knowledge that only geeks and geniuses have. Here are some commands with the most impressive features.
The commands used below may or may not be installed in your system. To install them use the brew command as follows:
% brew install <command-name>
Make your Mac talk what you want using the say command:
% say Hello Geeks
Set up a login message to display for yourself on your Mac using the following command –
% sudo write /Library/Preferences/com.apple.loginwindow LoginwindowText "Login Message for Display"
% cowsay <message>
% emac
After the above command press “enter” then “escape” then “x”. Now you enter the following commands:
doctor
snake
solitaire
pong.
These are some command, there are many more. The doctor provides you a psychiatrist to talk and snakes, solitaire, etc are games.
This command displays random quotes
% fortune
You can see the complete Star Wars animation in your terminal using this command.
% nc towel.blinkenlights.nl 23
This command displays a neo style matrix on the terminal.
% cmatrix
This command reverses all the content of the file. It is used as follows.
Shell
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 379,
"s": 54,
"text": "Terminal is one of the most important tools in MacOS be it any field. To get good knowledge about the terminal is important. It teaches you many things in an innovative way which is liked by most of the developers. It’s a knowledge that only geeks and geniuses have. Here are some commands with the most impressive features."
},
{
"code": null,
"e": 496,
"s": 379,
"text": "The commands used below may or may not be installed in your system. To install them use the brew command as follows:"
},
{
"code": null,
"e": 528,
"s": 496,
"text": "% brew install <command-name>\n\n"
},
{
"code": null,
"e": 584,
"s": 528,
"text": "Make your Mac talk what you want using the say command:"
},
{
"code": null,
"e": 604,
"s": 584,
"text": "% say Hello Geeks\n\n"
},
{
"code": null,
"e": 693,
"s": 604,
"text": "Set up a login message to display for yourself on your Mac using the following command –"
},
{
"code": null,
"e": 795,
"s": 693,
"text": "% sudo write /Library/Preferences/com.apple.loginwindow LoginwindowText \"Login Message for Display\"\n\n"
},
{
"code": null,
"e": 816,
"s": 795,
"text": "% cowsay <message>\n\n"
},
{
"code": null,
"e": 825,
"s": 816,
"text": "% emac\n\n"
},
{
"code": null,
"e": 925,
"s": 825,
"text": "After the above command press “enter” then “escape” then “x”. Now you enter the following commands:"
},
{
"code": null,
"e": 932,
"s": 925,
"text": "doctor"
},
{
"code": null,
"e": 938,
"s": 932,
"text": "snake"
},
{
"code": null,
"e": 948,
"s": 938,
"text": "solitaire"
},
{
"code": null,
"e": 954,
"s": 948,
"text": "pong."
},
{
"code": null,
"e": 1084,
"s": 954,
"text": "These are some command, there are many more. The doctor provides you a psychiatrist to talk and snakes, solitaire, etc are games."
},
{
"code": null,
"e": 1120,
"s": 1084,
"text": "This command displays random quotes"
},
{
"code": null,
"e": 1132,
"s": 1120,
"text": "% fortune\n\n"
},
{
"code": null,
"e": 1214,
"s": 1132,
"text": "You can see the complete Star Wars animation in your terminal using this command."
},
{
"code": null,
"e": 1247,
"s": 1214,
"text": "% nc towel.blinkenlights.nl 23\n\n"
},
{
"code": null,
"e": 1305,
"s": 1247,
"text": "This command displays a neo style matrix on the terminal."
},
{
"code": null,
"e": 1317,
"s": 1305,
"text": "% cmatrix\n\n"
},
{
"code": null,
"e": 1391,
"s": 1317,
"text": "This command reverses all the content of the file. It is used as follows."
},
{
"code": null,
"e": 1397,
"s": 1391,
"text": "Shell"
},
{
"code": null,
"e": 1404,
"s": 1397,
"text": "How To"
},
{
"code": null,
"e": 1415,
"s": 1404,
"text": "Linux-Unix"
}
] |
HTML | <th> height Attribute | 26 Jun, 2019
The HTML <th> height Attribute is used to specify the height of the table header cell. If the <th> height attribute is not set then it takes default height according to content. It is not supported by HTML 5.
Syntax:
<th height="pixels | %">
Attribute Values:
pixels: It sets the height of table header cell in terms of pixels.
%: It sets the height of table header cell in terms of percentage (%).
Example:
<!DOCTYPE html><html> <head> <title> HTML th height Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th height Attribute</h2> <table border="1" width="500"> <tr> <th height="50">NAME</th> <th height="50">AGE</th> <th height="50">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>
Output:
Supported Browsers: The browser supported by HTML <th> height attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jun, 2019"
},
{
"code": null,
"e": 237,
"s": 28,
"text": "The HTML <th> height Attribute is used to specify the height of the table header cell. If the <th> height attribute is not set then it takes default height according to content. It is not supported by HTML 5."
},
{
"code": null,
"e": 245,
"s": 237,
"text": "Syntax:"
},
{
"code": null,
"e": 270,
"s": 245,
"text": "<th height=\"pixels | %\">"
},
{
"code": null,
"e": 288,
"s": 270,
"text": "Attribute Values:"
},
{
"code": null,
"e": 356,
"s": 288,
"text": "pixels: It sets the height of table header cell in terms of pixels."
},
{
"code": null,
"e": 427,
"s": 356,
"text": "%: It sets the height of table header cell in terms of percentage (%)."
},
{
"code": null,
"e": 436,
"s": 427,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML th height Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th height Attribute</h2> <table border=\"1\" width=\"500\"> <tr> <th height=\"50\">NAME</th> <th height=\"50\">AGE</th> <th height=\"50\">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>",
"e": 1002,
"s": 436,
"text": null
},
{
"code": null,
"e": 1010,
"s": 1002,
"text": "Output:"
},
{
"code": null,
"e": 1100,
"s": 1010,
"text": "Supported Browsers: The browser supported by HTML <th> height attribute are listed below:"
},
{
"code": null,
"e": 1114,
"s": 1100,
"text": "Google Chrome"
},
{
"code": null,
"e": 1132,
"s": 1114,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1140,
"s": 1132,
"text": "Firefox"
},
{
"code": null,
"e": 1147,
"s": 1140,
"text": "Safari"
},
{
"code": null,
"e": 1153,
"s": 1147,
"text": "Opera"
},
{
"code": null,
"e": 1169,
"s": 1153,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1174,
"s": 1169,
"text": "HTML"
},
{
"code": null,
"e": 1191,
"s": 1174,
"text": "Web Technologies"
},
{
"code": null,
"e": 1196,
"s": 1191,
"text": "HTML"
}
] |
Fast I/O for Competitive Programming in Python | 03 Nov, 2020
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line.
Normally, the input is taken from STDIN in the form of String using input(). And this STDIN is provided in the Judge’s file. So try reading the input directly from the Judge’s file using the Operating system(os) module, and input/output (io) module. This reading can be done in the form of bytes. By using this method, integer input works normally, but for string input, it will store the string as a byte like an object. For correcting this, the string can be decoded using the decode function.
Below is the implementation for Fast I/O in Python:
Python3
# Python program to illustrate the use# of fast Input / Outputimport io, os, time # Function to take normal inputdef normal_io(): # Stores the start time start = time.perf_counter() # Take Input s = input().strip(); # Stores the end time end = time.perf_counter() # Print the time taken print("\nTime taken in Normal I / O:", \ end - start) # Function for Fast Inputdef fast_io(): # Reinitialize the Input function # to take input from the Byte Like # objects input = io.BytesIO(os.read(0, \ os.fstat(0).st_size)).readline # Fast Input / Output start = time.perf_counter() # Taking input as string s = input().decode() # Stores the end time end = time.perf_counter() # Print the time taken print("\nTime taken in Fast I / O:", \ end - start) # Driver Codeif __name__ == "__main__": # Function Call normal_io() fast_io()
Output:
Instead of outputting to the STDOUT, we can try writing to the Judge’s system file. The code for that would be to use sys.stdout.write() instead of print() in Python. But remember we can only output strings using this, so convert the output to a string using str() or map().
Below is the implementation for the Fast Output:
Python3
# Python program to illustrate the use# of fast Input / Outputimport time, sys # Function to take normal inputdef normal_out(): # Stores the start time start = time.perf_counter() # Output Integer n = 5 print(n) # Output String s = "GeeksforGeeks" print(s) # Output List arr = [1, 2, 3, 4] print(*arr) # Stores the end time end = time.perf_counter() # Print the time taken print("\nTime taken in Normal Output:", \ end - start) # Function for Fast Outputdef fast_out(): start = time.perf_counter() # Output Integer n = 5 sys.stdout.write(str(n)+"\n") # Output String s = "GeeksforGeeks\n" sys.stdout.write(s) # Output Array arr = [1, 2, 3, 4] sys.stdout.write( " ".join(map(str, arr)) + "\n" ) # Stores the end time end = time.perf_counter() # Print the time taken print("\nTime taken in Fast Output:", \ end - start) # Driver Codeif __name__ == "__main__": # Function Call normal_out() fast_out()
Output:
python-input-output
Competitive Programming
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Nov, 2020"
},
{
"code": null,
"e": 322,
"s": 52,
"text": "In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line."
},
{
"code": null,
"e": 818,
"s": 322,
"text": "Normally, the input is taken from STDIN in the form of String using input(). And this STDIN is provided in the Judge’s file. So try reading the input directly from the Judge’s file using the Operating system(os) module, and input/output (io) module. This reading can be done in the form of bytes. By using this method, integer input works normally, but for string input, it will store the string as a byte like an object. For correcting this, the string can be decoded using the decode function."
},
{
"code": null,
"e": 870,
"s": 818,
"text": "Below is the implementation for Fast I/O in Python:"
},
{
"code": null,
"e": 878,
"s": 870,
"text": "Python3"
},
{
"code": "# Python program to illustrate the use# of fast Input / Outputimport io, os, time # Function to take normal inputdef normal_io(): # Stores the start time start = time.perf_counter() # Take Input s = input().strip(); # Stores the end time end = time.perf_counter() # Print the time taken print(\"\\nTime taken in Normal I / O:\", \\ end - start) # Function for Fast Inputdef fast_io(): # Reinitialize the Input function # to take input from the Byte Like # objects input = io.BytesIO(os.read(0, \\ os.fstat(0).st_size)).readline # Fast Input / Output start = time.perf_counter() # Taking input as string s = input().decode() # Stores the end time end = time.perf_counter() # Print the time taken print(\"\\nTime taken in Fast I / O:\", \\ end - start) # Driver Codeif __name__ == \"__main__\": # Function Call normal_io() fast_io()",
"e": 1874,
"s": 878,
"text": null
},
{
"code": null,
"e": 1882,
"s": 1874,
"text": "Output:"
},
{
"code": null,
"e": 2157,
"s": 1882,
"text": "Instead of outputting to the STDOUT, we can try writing to the Judge’s system file. The code for that would be to use sys.stdout.write() instead of print() in Python. But remember we can only output strings using this, so convert the output to a string using str() or map()."
},
{
"code": null,
"e": 2206,
"s": 2157,
"text": "Below is the implementation for the Fast Output:"
},
{
"code": null,
"e": 2214,
"s": 2206,
"text": "Python3"
},
{
"code": "# Python program to illustrate the use# of fast Input / Outputimport time, sys # Function to take normal inputdef normal_out(): # Stores the start time start = time.perf_counter() # Output Integer n = 5 print(n) # Output String s = \"GeeksforGeeks\" print(s) # Output List arr = [1, 2, 3, 4] print(*arr) # Stores the end time end = time.perf_counter() # Print the time taken print(\"\\nTime taken in Normal Output:\", \\ end - start) # Function for Fast Outputdef fast_out(): start = time.perf_counter() # Output Integer n = 5 sys.stdout.write(str(n)+\"\\n\") # Output String s = \"GeeksforGeeks\\n\" sys.stdout.write(s) # Output Array arr = [1, 2, 3, 4] sys.stdout.write( \" \".join(map(str, arr)) + \"\\n\" ) # Stores the end time end = time.perf_counter() # Print the time taken print(\"\\nTime taken in Fast Output:\", \\ end - start) # Driver Codeif __name__ == \"__main__\": # Function Call normal_out() fast_out()",
"e": 3315,
"s": 2214,
"text": null
},
{
"code": null,
"e": 3323,
"s": 3315,
"text": "Output:"
},
{
"code": null,
"e": 3343,
"s": 3323,
"text": "python-input-output"
},
{
"code": null,
"e": 3367,
"s": 3343,
"text": "Competitive Programming"
},
{
"code": null,
"e": 3374,
"s": 3367,
"text": "Python"
}
] |
numpy.fromstring() function – Python | 18 Aug, 2020
numpy.fromstring() function create a new one-dimensional array initialized from text data in a string.
Syntax : numpy.fromstring(string, dtype = float, count = -1, sep = ‘ ‘)
Parameters :
string : [str] A string that contained the data.
dtype : [data-type, optional] Data-type of the array. Default data type is float.
count : [int, optional] Number of items to read. If this is negative (the default), the count will be determined from the length of the data.
sep : [str, optional] The string separating numbers in the data.
Return : [ndarray] Return the constructed array.
Code #1 :
Python3
# Python program explaining# numpy.fromstring() function # importing numpy as geekimport numpy as geek gfg = geek.fromstring('1 2 3 4 5', dtype = float, sep = ' ') print(gfg)
Output :
[1. 2. 3. 4. 5.]
Code #2 :
Python3
# Python program explaining# numpy.fromstring() function # importing numpy as geekimport numpy as geek gfg = geek.fromstring('1 2 3 4 5 6', dtype = int, sep = ' ') print(gfg)
Output :
[1 2 3 4 5 6]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "numpy.fromstring() function create a new one-dimensional array initialized from text data in a string."
},
{
"code": null,
"e": 203,
"s": 131,
"text": "Syntax : numpy.fromstring(string, dtype = float, count = -1, sep = ‘ ‘)"
},
{
"code": null,
"e": 216,
"s": 203,
"text": "Parameters :"
},
{
"code": null,
"e": 265,
"s": 216,
"text": "string : [str] A string that contained the data."
},
{
"code": null,
"e": 347,
"s": 265,
"text": "dtype : [data-type, optional] Data-type of the array. Default data type is float."
},
{
"code": null,
"e": 489,
"s": 347,
"text": "count : [int, optional] Number of items to read. If this is negative (the default), the count will be determined from the length of the data."
},
{
"code": null,
"e": 554,
"s": 489,
"text": "sep : [str, optional] The string separating numbers in the data."
},
{
"code": null,
"e": 603,
"s": 554,
"text": "Return : [ndarray] Return the constructed array."
},
{
"code": null,
"e": 613,
"s": 603,
"text": "Code #1 :"
},
{
"code": null,
"e": 621,
"s": 613,
"text": "Python3"
},
{
"code": "# Python program explaining# numpy.fromstring() function # importing numpy as geekimport numpy as geek gfg = geek.fromstring('1 2 3 4 5', dtype = float, sep = ' ') print(gfg)",
"e": 802,
"s": 621,
"text": null
},
{
"code": null,
"e": 811,
"s": 802,
"text": "Output :"
},
{
"code": null,
"e": 828,
"s": 811,
"text": "[1. 2. 3. 4. 5.]"
},
{
"code": null,
"e": 838,
"s": 828,
"text": "Code #2 :"
},
{
"code": null,
"e": 846,
"s": 838,
"text": "Python3"
},
{
"code": "# Python program explaining# numpy.fromstring() function # importing numpy as geekimport numpy as geek gfg = geek.fromstring('1 2 3 4 5 6', dtype = int, sep = ' ') print(gfg)",
"e": 1027,
"s": 846,
"text": null
},
{
"code": null,
"e": 1036,
"s": 1027,
"text": "Output :"
},
{
"code": null,
"e": 1050,
"s": 1036,
"text": "[1 2 3 4 5 6]"
},
{
"code": null,
"e": 1063,
"s": 1050,
"text": "Python-numpy"
},
{
"code": null,
"e": 1070,
"s": 1063,
"text": "Python"
}
] |
Class Level Lock in Java | 17 Jan, 2022
Every class in Java has a unique lock which is nothing but class level lock. If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Class level lock prevents multiple threads to enter a synchronized block in any of all available instances of the class on runtime. This means if in runtime there are 10 instances of a class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.
If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Once a thread got the class level lock, then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock.
Methods: Thread can acquire the lock at a class level by two methods namely
Using the synchronized static method.Using synchronized block.
Using the synchronized static method.
Using synchronized block.
Method 1: Using the synchronized static method
Implementation: We have a Geek class. We want to use static synchronization method of this class, as soon as the thread entered the synchronized method, the thread acquires the lock at the class level, rest of the threads wait to get the class monitor lock. The thread will leave a lock when it exits from the synchronized method.
public static synchronized int incrementCount()
{
}
Example
Java
// Java program to illustrate class level lock // Main Class// Implememnting the Runnable interfaceclass Geek implements Runnable { // Method 1 // @Override public void run() { Lock(); } // Method 2 // Method is static public static synchronized void Lock() { // Gwetting the name of current thread by using // getName() method to get name of the thread and // currentThread() to get the current thread System.out.println( Thread.currentThread().getName()); // class level lock synchronized (Geek.class) { System.out.println( "in block " + Thread.currentThread().getName()); System.out.println( "in block " + Thread.currentThread().getName() + " end"); } } // Method 3 // Main driver method public static void main(String[] args) { // Creating an object of above class // in the main() method Geek g1 = new Geek(); // Sharing the same object across two Threads // Creating an object of thread class where // t1 takes g1 Thread t1 = new Thread(g1); // Creating an object of thread class where // t2 takes g1 Thread t2 = new Thread(g1); // Creating second object of above class // in the main() method Geek g2 = new Geek(); // Creating an object of thread class where // t3 takes g2 Thread t3 = new Thread(g2); // setName() method is used to set name to the // thread t1.setName("t1"); t2.setName("t2"); t3.setName("t3"); // start() method is used for initiating the current // thread t1.start(); t2.start(); t3.start(); }}
t1
in block t1
in block t1 end
t3
in block t3
in block t3 end
t2
in block t2
in block t2 end
Output explanation:
Thread t1 entered the static synchronized method and was holding a lock on Geek’s class. So, the rest of the threads waited for Thread t1 to release the lock on Geek’s class so that it could enter the static synchronized method.
Method 2: Using synchronized block method
Implementation: We have a “Geek” class. We want to create a synchronization block and pass class name. class as a parameter tells which class has to synchronized at the class level. As soon as the thread entered the synchronized block, the thread acquire the lock at class, rest of the threads wait to get the class monitor lock. The thread will leave lock when it exits from the synchronized block.
synchronized (Geek.class) {
//thread has acquired lock on Geek class
}
Example
Java
// Java program to illustrate class level lock // Main Class// It is implementing the Runnable interfaceclass Geek implements Runnable { // Method 1 // @Override public void run() { // Acquire lock on .class reference synchronized (Geek.class) // ClassName is name of the class containing method. { { System.out.println( Thread.currentThread().getName()); System.out.println( "in block " + Thread.currentThread().getName()); System.out.println( "in block " + Thread.currentThread().getName() + " end"); } } // Method 2 // Main driver method public static void main(String[] args) { // Creating an object of above class // in the main() method Geek g1 = new Geek(); // Creating an object of thread class i.e Thread // 1 where t1 takes g1 object Thread t1 = new Thread(g1); // Here, creating Thread 2 where t2 takes g1 // object Thread t2 = new Thread(g1); // Creating another object of above class // in the main() method Geek g2 = new Geek(); // Now Creating Thread 3 where t3 takes g2 object Thread t3 = new Thread(g2); // Ginving custom names to above 3 threads // using the setName() method t1.setName("t1"); t2.setName("t2"); t3.setName("t3"); // start() method is used to begin execution of // threads t1.start(); t2.start(); t3.start(); } }
Output:
t1
in block t1
in block t1 end
t3
in block t3
in block t3 end
t2
in block t2
in block t2 end
Output explanation:
Thread t1 entered synchronized block and was holding the lock on ‘Geek’ class. So, the rest of the threads waited for Thread t1 to release the lock on the ‘Geek’ class so that it could enter the synchronized block.
kk773572498
Java-Class and Object
Java-Multithreading
Picked
Java
Java-Class and Object
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 544,
"s": 28,
"text": "Every class in Java has a unique lock which is nothing but class level lock. If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Class level lock prevents multiple threads to enter a synchronized block in any of all available instances of the class on runtime. This means if in runtime there are 10 instances of a class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data."
},
{
"code": null,
"e": 836,
"s": 544,
"text": "If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Once a thread got the class level lock, then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock."
},
{
"code": null,
"e": 912,
"s": 836,
"text": "Methods: Thread can acquire the lock at a class level by two methods namely"
},
{
"code": null,
"e": 975,
"s": 912,
"text": "Using the synchronized static method.Using synchronized block."
},
{
"code": null,
"e": 1013,
"s": 975,
"text": "Using the synchronized static method."
},
{
"code": null,
"e": 1039,
"s": 1013,
"text": "Using synchronized block."
},
{
"code": null,
"e": 1086,
"s": 1039,
"text": "Method 1: Using the synchronized static method"
},
{
"code": null,
"e": 1417,
"s": 1086,
"text": "Implementation: We have a Geek class. We want to use static synchronization method of this class, as soon as the thread entered the synchronized method, the thread acquires the lock at the class level, rest of the threads wait to get the class monitor lock. The thread will leave a lock when it exits from the synchronized method."
},
{
"code": null,
"e": 1469,
"s": 1417,
"text": "public static synchronized int incrementCount()\n{\n}"
},
{
"code": null,
"e": 1477,
"s": 1469,
"text": "Example"
},
{
"code": null,
"e": 1482,
"s": 1477,
"text": "Java"
},
{
"code": "// Java program to illustrate class level lock // Main Class// Implememnting the Runnable interfaceclass Geek implements Runnable { // Method 1 // @Override public void run() { Lock(); } // Method 2 // Method is static public static synchronized void Lock() { // Gwetting the name of current thread by using // getName() method to get name of the thread and // currentThread() to get the current thread System.out.println( Thread.currentThread().getName()); // class level lock synchronized (Geek.class) { System.out.println( \"in block \" + Thread.currentThread().getName()); System.out.println( \"in block \" + Thread.currentThread().getName() + \" end\"); } } // Method 3 // Main driver method public static void main(String[] args) { // Creating an object of above class // in the main() method Geek g1 = new Geek(); // Sharing the same object across two Threads // Creating an object of thread class where // t1 takes g1 Thread t1 = new Thread(g1); // Creating an object of thread class where // t2 takes g1 Thread t2 = new Thread(g1); // Creating second object of above class // in the main() method Geek g2 = new Geek(); // Creating an object of thread class where // t3 takes g2 Thread t3 = new Thread(g2); // setName() method is used to set name to the // thread t1.setName(\"t1\"); t2.setName(\"t2\"); t3.setName(\"t3\"); // start() method is used for initiating the current // thread t1.start(); t2.start(); t3.start(); }}",
"e": 3300,
"s": 1482,
"text": null
},
{
"code": null,
"e": 3396,
"s": 3303,
"text": "t1\nin block t1\nin block t1 end\nt3\nin block t3\nin block t3 end\nt2\nin block t2\nin block t2 end"
},
{
"code": null,
"e": 3419,
"s": 3398,
"text": "Output explanation: "
},
{
"code": null,
"e": 3650,
"s": 3421,
"text": "Thread t1 entered the static synchronized method and was holding a lock on Geek’s class. So, the rest of the threads waited for Thread t1 to release the lock on Geek’s class so that it could enter the static synchronized method."
},
{
"code": null,
"e": 3695,
"s": 3652,
"text": "Method 2: Using synchronized block method "
},
{
"code": null,
"e": 4097,
"s": 3697,
"text": "Implementation: We have a “Geek” class. We want to create a synchronization block and pass class name. class as a parameter tells which class has to synchronized at the class level. As soon as the thread entered the synchronized block, the thread acquire the lock at class, rest of the threads wait to get the class monitor lock. The thread will leave lock when it exits from the synchronized block."
},
{
"code": null,
"e": 4175,
"s": 4099,
"text": "synchronized (Geek.class) {\n //thread has acquired lock on Geek class\n}"
},
{
"code": null,
"e": 4185,
"s": 4177,
"text": "Example"
},
{
"code": null,
"e": 4192,
"s": 4187,
"text": "Java"
},
{
"code": "// Java program to illustrate class level lock // Main Class// It is implementing the Runnable interfaceclass Geek implements Runnable { // Method 1 // @Override public void run() { // Acquire lock on .class reference synchronized (Geek.class) // ClassName is name of the class containing method. { { System.out.println( Thread.currentThread().getName()); System.out.println( \"in block \" + Thread.currentThread().getName()); System.out.println( \"in block \" + Thread.currentThread().getName() + \" end\"); } } // Method 2 // Main driver method public static void main(String[] args) { // Creating an object of above class // in the main() method Geek g1 = new Geek(); // Creating an object of thread class i.e Thread // 1 where t1 takes g1 object Thread t1 = new Thread(g1); // Here, creating Thread 2 where t2 takes g1 // object Thread t2 = new Thread(g1); // Creating another object of above class // in the main() method Geek g2 = new Geek(); // Now Creating Thread 3 where t3 takes g2 object Thread t3 = new Thread(g2); // Ginving custom names to above 3 threads // using the setName() method t1.setName(\"t1\"); t2.setName(\"t2\"); t3.setName(\"t3\"); // start() method is used to begin execution of // threads t1.start(); t2.start(); t3.start(); } }",
"e": 5988,
"s": 4192,
"text": null
},
{
"code": null,
"e": 6000,
"s": 5992,
"text": "Output:"
},
{
"code": null,
"e": 6095,
"s": 6002,
"text": "t1\nin block t1\nin block t1 end\nt3\nin block t3\nin block t3 end\nt2\nin block t2\nin block t2 end"
},
{
"code": null,
"e": 6118,
"s": 6097,
"text": "Output explanation: "
},
{
"code": null,
"e": 6335,
"s": 6120,
"text": "Thread t1 entered synchronized block and was holding the lock on ‘Geek’ class. So, the rest of the threads waited for Thread t1 to release the lock on the ‘Geek’ class so that it could enter the synchronized block."
},
{
"code": null,
"e": 6349,
"s": 6337,
"text": "kk773572498"
},
{
"code": null,
"e": 6371,
"s": 6349,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 6391,
"s": 6371,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 6398,
"s": 6391,
"text": "Picked"
},
{
"code": null,
"e": 6403,
"s": 6398,
"text": "Java"
},
{
"code": null,
"e": 6425,
"s": 6403,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 6430,
"s": 6425,
"text": "Java"
}
] |
Flutter – CheckboxListTile | 21 Feb, 2022
CheckboxListTile is a built-in widget in flutter. We can say it a combination of CheckBox with a ListTile. Its properties such as value, activeColor, and checkColor are similar to the CheckBox widget, and title, subtitle, contentPadding, etc are similar to the ListTile widget. We can tap anywhere on the CheckBoxListTile to Google the checkbox. Below we will see all the properties of this widget along with an example.
const CheckboxListTile(
{Key key,
@required bool value,
@required ValueChanged<bool> onChanged,
Color activeColor,
Color checkColor,
Widget title,
Widget subtitle,
bool isThreeLine: false,
bool dense,
Widget secondary,
bool selected: false,
ListTileControlAffinity controlAffinity: ListTileControlAffinity.platform,
bool autofocus: false,
EdgeInsetsGeometry contentPadding,
bool tristate: false}
)
Properties of CheckboxListTile Widget:
activeColor: This widget takes in the Color class as the object to assign the checkbox a color when it is checked.
autofocus: This property takes in a boolean as the value to divide whether the widget will be selected on the initial focus or not.
checkColor: This property assigns a color to the check icon by taking in the Color class as the object.
contentPadding: This property is responsible to assign empty space inside the widget by taking in EdgeIsetsGeometry class as the object.
controlAffinity: The controlAffinity property holds the ListTileControlAffinity class as the object to decide the location of action in respect to text inside the widget.
dense: The dense property takes in a boolean as the object whether is associated with the vertical dense list.
isThreeLine: This property also takes in a boolean as the object to decide whether the text in the widget will be printed till the third line.
onChanged: This property takes in Valuechanged<bool> as the object. This property is responsible for the change in the checkbox.
secondary: The secondary property holds a widget as the object to be displayed on the opposite side of the checkbox.
selected: This property takes in a boolean value as the object to decide whether the checkbox will be already selected or not.
subtitle: The subtitle property holds a widget as the object to be displayed below the title. Usually, this widget is Text.
title: This property also takes in a widget as the object to be displayed as the title of the CheckBoxListTle, usually, it is Text widget.
tristate: This property holds a boolean as the object. If it is set to true the values in the checkbox can either true, false, or null.
value: This property also takes in a boolean as the object to control whether the checkbox is selected or not.
Example 1:
Dart
import 'package:flutter/material.dart'; // importing material design libraryvoid main() { runApp(MaterialApp( // runApp method home: HomePage(), )); //MaterialApp} class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { // value set to false bool _value = false; // App widget tree @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton ), //AppBar body: SizedBox( width: 400, height: 400, child: Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.greenAccent), borderRadius: BorderRadius.circular(20), ), //BoxDecoration /** CheckboxListTile Widget **/ child: CheckboxListTile( title: const Text('GeeksforGeeks'), subtitle: const Text('A computer science portal for geeks.'), secondary: const Icon(Icons.code), autofocus: false, activeColor: Colors.green, checkColor: Colors.white, selected: _value, value: _value, onChanged: (bool value) { setState(() { _value = value; }); }, ), //CheckboxListTile ), //Container ), //Padding ), //Center ), //SizedBox ), //Scaffold ); //MaterialApp }}
Output:
Explanation: In the body of this flutter app the hierarchy till the CheckBoxListTile is SizedBox > Center > Padding > Container > CheckBoxListTile. All the widget above the CheckBoxListTile is mainly to put it in the center of the screen. In the CheckBoxListTile widget or title, the property is holding Text(‘GeeksforGeeks’), and the subtitle is also a Text widget. On the extreme left, we have the checkbox and on the extreme right, we have a material design code icon. The active color in the widget is green and the check icon color is white. The control of the state of this widget is taken by the value property. And the green-colored border is painted by the BoxDecoration widget with a 20 px curve on the edges. The combined result of all these is a nice looking checkbox tile, it can be used in many applications like to-do list or scheduler app.
Example 2:
Dart
import 'package:flutter/material.dart'; // importing material design libraryvoid main() { runApp(MaterialApp( // runApp method home: HomePage(), )); //MaterialApp} // Creating a stateful widget to manage// the state of the appclass HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { // value set to false bool _value = false; bool _valu = false; // App widget tree @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton ), //AppBar body: Center( child: SizedBox( width: 400, height: 400, child: Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ Container( decoration: BoxDecoration( border: Border.all(color: Colors.greenAccent), borderRadius: BorderRadius.circular(20), ), //BoxDecoration /** CheckboxListTile Widget **/ child: CheckboxListTile( title: const Text('GeeksforGeeks'), subtitle: const Text('A computer science portal for geeks. '), secondary: CircleAvatar( backgroundImage: NetworkImage( "https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"), //NetworkImage radius: 20, ), autofocus: false, activeColor: Colors.green, checkColor: Colors.white, selected: _value, dense: true, value: _value, onChanged: (bool value) { setState(() { _value = value; }); }, ), //CheckboxListTile ), SizedBox( height: 30, ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.black, offset: const Offset( 3.0, 3.0, ), //Offset blurRadius: 10.0, spreadRadius: 2.0, ), //BoxShadow BoxShadow( color: Colors.white, offset: const Offset(0.0, 0.0), blurRadius: 0.0, spreadRadius: 0.0, ), //BoxShadow ], ), //BoxDecoration /** CheckboxListTile Widget **/ child: CheckboxListTile( title: const Text('GeeksforGeeks'), subtitle: const Text( 'A computer science portal for geeks. Here you will find articles on all the technologies.'), secondary: CircleAvatar( backgroundImage: NetworkImage( "https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"), //NetworkImage radius: 20, ), autofocus: false, isThreeLine: true, activeColor: Colors.green, checkColor: Colors.white, selected: _valu, value: _valu, onChanged: (bool value) { setState(() { _valu = value; }); }, ), //CheckboxListTile ), ], ), //Container ), //Padding ), //Center ), ), //SizedBox ), debugShowCheckedModeBanner: false, //Scaffold ); //MaterialApp }}
Output:
Explanation: In this example displaying the use of CheckBoxTile widget we have modified the looks of the CheckBoxTile by employing its different parameters along with the BoxDecoration widget. By taking a look at the app we can notice an image has replaced that code icon. In both that CheckBoxTiles the secondary parameter is taking CircleAvatar widget as the object which is taking in NetworkImage. The size of the image is 20 px. In the first tile, the dense property is also set to true, which makes the tile bit small compared to the original size. Both tiles, separated by a SizedBox widget of height 30 px. In the second tile, the border parameter is removed from the BoxDecoration and the boxShadow has been added, which is giving a nice black shadow around the edges. In addition, the isThreeLine property is also set to true which some additional height to the tile, to accommodate more text in the subtitle parameter.
surinderdawra388
kashishsoda
simranarora5sos
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 449,
"s": 28,
"text": "CheckboxListTile is a built-in widget in flutter. We can say it a combination of CheckBox with a ListTile. Its properties such as value, activeColor, and checkColor are similar to the CheckBox widget, and title, subtitle, contentPadding, etc are similar to the ListTile widget. We can tap anywhere on the CheckBoxListTile to Google the checkbox. Below we will see all the properties of this widget along with an example."
},
{
"code": null,
"e": 847,
"s": 449,
"text": "const CheckboxListTile(\n{Key key,\n@required bool value,\n@required ValueChanged<bool> onChanged,\nColor activeColor,\nColor checkColor,\nWidget title,\nWidget subtitle,\nbool isThreeLine: false,\nbool dense,\nWidget secondary,\nbool selected: false,\nListTileControlAffinity controlAffinity: ListTileControlAffinity.platform,\nbool autofocus: false,\nEdgeInsetsGeometry contentPadding,\nbool tristate: false}\n)"
},
{
"code": null,
"e": 886,
"s": 847,
"text": "Properties of CheckboxListTile Widget:"
},
{
"code": null,
"e": 1001,
"s": 886,
"text": "activeColor: This widget takes in the Color class as the object to assign the checkbox a color when it is checked."
},
{
"code": null,
"e": 1133,
"s": 1001,
"text": "autofocus: This property takes in a boolean as the value to divide whether the widget will be selected on the initial focus or not."
},
{
"code": null,
"e": 1237,
"s": 1133,
"text": "checkColor: This property assigns a color to the check icon by taking in the Color class as the object."
},
{
"code": null,
"e": 1374,
"s": 1237,
"text": "contentPadding: This property is responsible to assign empty space inside the widget by taking in EdgeIsetsGeometry class as the object."
},
{
"code": null,
"e": 1545,
"s": 1374,
"text": "controlAffinity: The controlAffinity property holds the ListTileControlAffinity class as the object to decide the location of action in respect to text inside the widget."
},
{
"code": null,
"e": 1656,
"s": 1545,
"text": "dense: The dense property takes in a boolean as the object whether is associated with the vertical dense list."
},
{
"code": null,
"e": 1799,
"s": 1656,
"text": "isThreeLine: This property also takes in a boolean as the object to decide whether the text in the widget will be printed till the third line."
},
{
"code": null,
"e": 1928,
"s": 1799,
"text": "onChanged: This property takes in Valuechanged<bool> as the object. This property is responsible for the change in the checkbox."
},
{
"code": null,
"e": 2045,
"s": 1928,
"text": "secondary: The secondary property holds a widget as the object to be displayed on the opposite side of the checkbox."
},
{
"code": null,
"e": 2173,
"s": 2045,
"text": "selected: This property takes in a boolean value as the object to decide whether the checkbox will be already selected or not."
},
{
"code": null,
"e": 2297,
"s": 2173,
"text": "subtitle: The subtitle property holds a widget as the object to be displayed below the title. Usually, this widget is Text."
},
{
"code": null,
"e": 2436,
"s": 2297,
"text": "title: This property also takes in a widget as the object to be displayed as the title of the CheckBoxListTle, usually, it is Text widget."
},
{
"code": null,
"e": 2572,
"s": 2436,
"text": "tristate: This property holds a boolean as the object. If it is set to true the values in the checkbox can either true, false, or null."
},
{
"code": null,
"e": 2683,
"s": 2572,
"text": "value: This property also takes in a boolean as the object to control whether the checkbox is selected or not."
},
{
"code": null,
"e": 2694,
"s": 2683,
"text": "Example 1:"
},
{
"code": null,
"e": 2699,
"s": 2694,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; // importing material design libraryvoid main() { runApp(MaterialApp( // runApp method home: HomePage(), )); //MaterialApp} class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { // value set to false bool _value = false; // App widget tree @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton ), //AppBar body: SizedBox( width: 400, height: 400, child: Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.greenAccent), borderRadius: BorderRadius.circular(20), ), //BoxDecoration /** CheckboxListTile Widget **/ child: CheckboxListTile( title: const Text('GeeksforGeeks'), subtitle: const Text('A computer science portal for geeks.'), secondary: const Icon(Icons.code), autofocus: false, activeColor: Colors.green, checkColor: Colors.white, selected: _value, value: _value, onChanged: (bool value) { setState(() { _value = value; }); }, ), //CheckboxListTile ), //Container ), //Padding ), //Center ), //SizedBox ), //Scaffold ); //MaterialApp }}",
"e": 4667,
"s": 2699,
"text": null
},
{
"code": null,
"e": 4675,
"s": 4667,
"text": "Output:"
},
{
"code": null,
"e": 5531,
"s": 4675,
"text": "Explanation: In the body of this flutter app the hierarchy till the CheckBoxListTile is SizedBox > Center > Padding > Container > CheckBoxListTile. All the widget above the CheckBoxListTile is mainly to put it in the center of the screen. In the CheckBoxListTile widget or title, the property is holding Text(‘GeeksforGeeks’), and the subtitle is also a Text widget. On the extreme left, we have the checkbox and on the extreme right, we have a material design code icon. The active color in the widget is green and the check icon color is white. The control of the state of this widget is taken by the value property. And the green-colored border is painted by the BoxDecoration widget with a 20 px curve on the edges. The combined result of all these is a nice looking checkbox tile, it can be used in many applications like to-do list or scheduler app."
},
{
"code": null,
"e": 5542,
"s": 5531,
"text": "Example 2:"
},
{
"code": null,
"e": 5547,
"s": 5542,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; // importing material design libraryvoid main() { runApp(MaterialApp( // runApp method home: HomePage(), )); //MaterialApp} // Creating a stateful widget to manage// the state of the appclass HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { // value set to false bool _value = false; bool _valu = false; // App widget tree @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton ), //AppBar body: Center( child: SizedBox( width: 400, height: 400, child: Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ Container( decoration: BoxDecoration( border: Border.all(color: Colors.greenAccent), borderRadius: BorderRadius.circular(20), ), //BoxDecoration /** CheckboxListTile Widget **/ child: CheckboxListTile( title: const Text('GeeksforGeeks'), subtitle: const Text('A computer science portal for geeks. '), secondary: CircleAvatar( backgroundImage: NetworkImage( \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"), //NetworkImage radius: 20, ), autofocus: false, activeColor: Colors.green, checkColor: Colors.white, selected: _value, dense: true, value: _value, onChanged: (bool value) { setState(() { _value = value; }); }, ), //CheckboxListTile ), SizedBox( height: 30, ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.black, offset: const Offset( 3.0, 3.0, ), //Offset blurRadius: 10.0, spreadRadius: 2.0, ), //BoxShadow BoxShadow( color: Colors.white, offset: const Offset(0.0, 0.0), blurRadius: 0.0, spreadRadius: 0.0, ), //BoxShadow ], ), //BoxDecoration /** CheckboxListTile Widget **/ child: CheckboxListTile( title: const Text('GeeksforGeeks'), subtitle: const Text( 'A computer science portal for geeks. Here you will find articles on all the technologies.'), secondary: CircleAvatar( backgroundImage: NetworkImage( \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"), //NetworkImage radius: 20, ), autofocus: false, isThreeLine: true, activeColor: Colors.green, checkColor: Colors.white, selected: _valu, value: _valu, onChanged: (bool value) { setState(() { _valu = value; }); }, ), //CheckboxListTile ), ], ), //Container ), //Padding ), //Center ), ), //SizedBox ), debugShowCheckedModeBanner: false, //Scaffold ); //MaterialApp }}",
"e": 10341,
"s": 5547,
"text": null
},
{
"code": null,
"e": 10349,
"s": 10341,
"text": "Output:"
},
{
"code": null,
"e": 11278,
"s": 10349,
"text": "Explanation: In this example displaying the use of CheckBoxTile widget we have modified the looks of the CheckBoxTile by employing its different parameters along with the BoxDecoration widget. By taking a look at the app we can notice an image has replaced that code icon. In both that CheckBoxTiles the secondary parameter is taking CircleAvatar widget as the object which is taking in NetworkImage. The size of the image is 20 px. In the first tile, the dense property is also set to true, which makes the tile bit small compared to the original size. Both tiles, separated by a SizedBox widget of height 30 px. In the second tile, the border parameter is removed from the BoxDecoration and the boxShadow has been added, which is giving a nice black shadow around the edges. In addition, the isThreeLine property is also set to true which some additional height to the tile, to accommodate more text in the subtitle parameter."
},
{
"code": null,
"e": 11295,
"s": 11278,
"text": "surinderdawra388"
},
{
"code": null,
"e": 11307,
"s": 11295,
"text": "kashishsoda"
},
{
"code": null,
"e": 11323,
"s": 11307,
"text": "simranarora5sos"
},
{
"code": null,
"e": 11331,
"s": 11323,
"text": "Android"
},
{
"code": null,
"e": 11336,
"s": 11331,
"text": "Dart"
},
{
"code": null,
"e": 11344,
"s": 11336,
"text": "Flutter"
},
{
"code": null,
"e": 11352,
"s": 11344,
"text": "Android"
}
] |
Program to find equation of a plane passing through 3 points in C++ | In this tutorial, we will be discussing a program to find equation of a plane passing through 3 points.
For this we will be provided with 3 points. Our task is to find the equation of the plane consisting of or passing through those three given points.
Live Demo
#include <bits/stdc++.h>
#include<math.h>
#include <iostream>
#include <iomanip>
using namespace std;
//finding the equation of plane
void equation_plane(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3){
float a1 = x2 - x1;
float b1 = y2 - y1;
float c1 = z2 - z1;
float a2 = x3 - x1;
float b2 = y3 - y1;
float c2 = z3 - z1;
float a = b1 * c2 - b2 * c1;
float b = a2 * c1 - a1 * c2;
float c = a1 * b2 - b1 * a2;
float d = (- a * x1 - b * y1 - c * z1);
std::cout << std::fixed;
std::cout << std::setprecision(2);
cout << "Equation of plane is " << a << " x + " << b << " y + " << c << " z + " << d << " = 0";
}
int main(){
float x1 =-1;
float y1 = 2;
float z1 = 1;
float x2 = 0;
float y2 =-3;
float z2 = 2;
float x3 = 1;
float y3 = 1;
float z3 =-4;
equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3);
return 0;
}
Equation of plane is 26.00 x + 7.00 y + 9.00 z + 3.00 = 0 | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to find equation of a plane passing through 3 points."
},
{
"code": null,
"e": 1315,
"s": 1166,
"text": "For this we will be provided with 3 points. Our task is to find the equation of the plane consisting of or passing through those three given points."
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": " Live Demo"
},
{
"code": null,
"e": 2250,
"s": 1326,
"text": "#include <bits/stdc++.h>\n#include<math.h>\n#include <iostream>\n#include <iomanip>\nusing namespace std;\n//finding the equation of plane\nvoid equation_plane(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3){\n float a1 = x2 - x1;\n float b1 = y2 - y1;\n float c1 = z2 - z1;\n float a2 = x3 - x1;\n float b2 = y3 - y1;\n float c2 = z3 - z1;\n float a = b1 * c2 - b2 * c1;\n float b = a2 * c1 - a1 * c2;\n float c = a1 * b2 - b1 * a2;\n float d = (- a * x1 - b * y1 - c * z1);\n std::cout << std::fixed;\n std::cout << std::setprecision(2);\n cout << \"Equation of plane is \" << a << \" x + \" << b << \" y + \" << c << \" z + \" << d << \" = 0\";\n}\nint main(){\n float x1 =-1;\n float y1 = 2;\n float z1 = 1;\n float x2 = 0;\n float y2 =-3;\n float z2 = 2;\n float x3 = 1;\n float y3 = 1;\n float z3 =-4;\n equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3);\n return 0;\n}"
},
{
"code": null,
"e": 2308,
"s": 2250,
"text": "Equation of plane is 26.00 x + 7.00 y + 9.00 z + 3.00 = 0"
}
] |
Not class selector in jQuery - GeeksforGeeks | 31 May, 2019
Given a list of elements and the task is to not select a particular class using JQuery.
jQuery :not() Selector: This selector selects all elements except the specified element.Syntax:$(":not(selector)")Parameters: It contains single parameter selector which is required. It specifies the element which do not select. This parameter accepts all kind of selector.
Syntax:
$(":not(selector)")
Parameters: It contains single parameter selector which is required. It specifies the element which do not select. This parameter accepts all kind of selector.
jQuery not() Method: This method returns elements that do not match a defined condition. This method specifies a condition. Elements that do not match the condition are returned, and those that match will be removed. Mostly this method is used to remove one or more than one elements from a group of selected elements.Syntax:$(selector).not(condition, function(index))
Parameters:condition: This parameter is optional. It specifies a selector expression, a jQuery object or one or more than one elements to be removed from a group of selected elements.function(index): This parameter is optional. It specifies a function to run for every element in a group. If it returns true, the element is removed else, the element is kept.index: It specifies the index position of the element in the set
Syntax:
$(selector).not(condition, function(index))
Parameters:
condition: This parameter is optional. It specifies a selector expression, a jQuery object or one or more than one elements to be removed from a group of selected elements.
function(index): This parameter is optional. It specifies a function to run for every element in a group. If it returns true, the element is removed else, the element is kept.index: It specifies the index position of the element in the set
index: It specifies the index position of the element in the set
Example 1: In this example first all classes of starting GFG- are selected then class GFG-1 is removed from the selection using .not() method.
<!DOCTYPE HTML> <html> <head> <title> Not class selector in jQuery. </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 id = "h" style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG" style = "font-size: 15px; font-weight: bold;"> click on button to change the text content of all classes except GFG-1 </p> <p class = "GFG-1" style = "font-size: 15px; font-weight: bold;"> GFG-1 </p> <p class = "GFG-2" style = "font-size: 15px; font-weight: bold;"> GFG-2 </p> <p class = "GFG-3" style = "font-size: 15px; font-weight: bold;"> GFG-3 </p> <button id = "button"> Click here </button> <p class = "GFG" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $("button").on('click', function() { $('p[class^="GFG-"]').not('.GFG-1').text("new Content"); $(".GFG").text("Text content changed") }); </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: In this example, first all classes of starting GFG- are selected then class GFG-1 is removed from the selection using :not selector.
<!DOCTYPE HTML> <html> <head> <title> Not class selector in jQuery. </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 id = "h" style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG" style = "font-size: 15px; font-weight: bold;"> click on button to change the text content of all classes except GFG-1 </p> <p class = "GFG-1" style = "font-size: 15px; font-weight: bold;"> GFG-1 </p> <p class = "GFG-2" style = "font-size: 15px; font-weight: bold;"> GFG-2 </p> <p class = "GFG-3" style = "font-size: 15px; font-weight: bold;"> GFG-3 </p> <button id = "button"> Click here </button> <p class = "GFG" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $("button").on('click', function() { $('p[class^="GFG-"]:not(.GFG-1)').text("new Content"); $(".GFG").text("Text content changed") }); </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
jQuery-Selectors
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
jQuery | ajax() Method
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
How to check whether a checkbox is checked in jQuery?
Installation of Node.js on Linux
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24566,
"s": 24538,
"text": "\n31 May, 2019"
},
{
"code": null,
"e": 24654,
"s": 24566,
"text": "Given a list of elements and the task is to not select a particular class using JQuery."
},
{
"code": null,
"e": 24928,
"s": 24654,
"text": "jQuery :not() Selector: This selector selects all elements except the specified element.Syntax:$(\":not(selector)\")Parameters: It contains single parameter selector which is required. It specifies the element which do not select. This parameter accepts all kind of selector."
},
{
"code": null,
"e": 24936,
"s": 24928,
"text": "Syntax:"
},
{
"code": null,
"e": 24956,
"s": 24936,
"text": "$(\":not(selector)\")"
},
{
"code": null,
"e": 25116,
"s": 24956,
"text": "Parameters: It contains single parameter selector which is required. It specifies the element which do not select. This parameter accepts all kind of selector."
},
{
"code": null,
"e": 25908,
"s": 25116,
"text": "jQuery not() Method: This method returns elements that do not match a defined condition. This method specifies a condition. Elements that do not match the condition are returned, and those that match will be removed. Mostly this method is used to remove one or more than one elements from a group of selected elements.Syntax:$(selector).not(condition, function(index))\nParameters:condition: This parameter is optional. It specifies a selector expression, a jQuery object or one or more than one elements to be removed from a group of selected elements.function(index): This parameter is optional. It specifies a function to run for every element in a group. If it returns true, the element is removed else, the element is kept.index: It specifies the index position of the element in the set"
},
{
"code": null,
"e": 25916,
"s": 25908,
"text": "Syntax:"
},
{
"code": null,
"e": 25961,
"s": 25916,
"text": "$(selector).not(condition, function(index))\n"
},
{
"code": null,
"e": 25973,
"s": 25961,
"text": "Parameters:"
},
{
"code": null,
"e": 26146,
"s": 25973,
"text": "condition: This parameter is optional. It specifies a selector expression, a jQuery object or one or more than one elements to be removed from a group of selected elements."
},
{
"code": null,
"e": 26386,
"s": 26146,
"text": "function(index): This parameter is optional. It specifies a function to run for every element in a group. If it returns true, the element is removed else, the element is kept.index: It specifies the index position of the element in the set"
},
{
"code": null,
"e": 26451,
"s": 26386,
"text": "index: It specifies the index position of the element in the set"
},
{
"code": null,
"e": 26594,
"s": 26451,
"text": "Example 1: In this example first all classes of starting GFG- are selected then class GFG-1 is removed from the selection using .not() method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Not class selector in jQuery. </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 id = \"h\" style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG\" style = \"font-size: 15px; font-weight: bold;\"> click on button to change the text content of all classes except GFG-1 </p> <p class = \"GFG-1\" style = \"font-size: 15px; font-weight: bold;\"> GFG-1 </p> <p class = \"GFG-2\" style = \"font-size: 15px; font-weight: bold;\"> GFG-2 </p> <p class = \"GFG-3\" style = \"font-size: 15px; font-weight: bold;\"> GFG-3 </p> <button id = \"button\"> Click here </button> <p class = \"GFG\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $(\"button\").on('click', function() { $('p[class^=\"GFG-\"]').not('.GFG-1').text(\"new Content\"); $(\".GFG\").text(\"Text content changed\") }); </script> </body> </html> ",
"e": 27995,
"s": 26594,
"text": null
},
{
"code": null,
"e": 28003,
"s": 27995,
"text": "Output:"
},
{
"code": null,
"e": 28034,
"s": 28003,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28064,
"s": 28034,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28208,
"s": 28064,
"text": "Example 2: In this example, first all classes of starting GFG- are selected then class GFG-1 is removed from the selection using :not selector."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Not class selector in jQuery. </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 id = \"h\" style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG\" style = \"font-size: 15px; font-weight: bold;\"> click on button to change the text content of all classes except GFG-1 </p> <p class = \"GFG-1\" style = \"font-size: 15px; font-weight: bold;\"> GFG-1 </p> <p class = \"GFG-2\" style = \"font-size: 15px; font-weight: bold;\"> GFG-2 </p> <p class = \"GFG-3\" style = \"font-size: 15px; font-weight: bold;\"> GFG-3 </p> <button id = \"button\"> Click here </button> <p class = \"GFG\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $(\"button\").on('click', function() { $('p[class^=\"GFG-\"]:not(.GFG-1)').text(\"new Content\"); $(\".GFG\").text(\"Text content changed\") }); </script> </body> </html> ",
"e": 29622,
"s": 28208,
"text": null
},
{
"code": null,
"e": 29630,
"s": 29622,
"text": "Output:"
},
{
"code": null,
"e": 29661,
"s": 29630,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29691,
"s": 29661,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29708,
"s": 29691,
"text": "jQuery-Selectors"
},
{
"code": null,
"e": 29715,
"s": 29708,
"text": "JQuery"
},
{
"code": null,
"e": 29732,
"s": 29715,
"text": "Web Technologies"
},
{
"code": null,
"e": 29759,
"s": 29732,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29857,
"s": 29759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29866,
"s": 29857,
"text": "Comments"
},
{
"code": null,
"e": 29879,
"s": 29866,
"text": "Old Comments"
},
{
"code": null,
"e": 29902,
"s": 29879,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29956,
"s": 29902,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 30024,
"s": 29956,
"text": "How to get the ID of the clicked button using JavaScript / jQuery ?"
},
{
"code": null,
"e": 30058,
"s": 30024,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 30112,
"s": 30058,
"text": "How to check whether a checkbox is checked in jQuery?"
},
{
"code": null,
"e": 30145,
"s": 30112,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30182,
"s": 30145,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 30244,
"s": 30182,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30287,
"s": 30244,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to create Python dictionary from list of keys and values? | If L1 and L2 are list objects containing keys and respective values, following methods can be used to construct dictionary object.
Zip two lists and convert to dictionary using dict() function
>>> L1 = ['a','b','c','d']
>>> L2 = [1,2,3,4]
>>> d = dict(zip(L1,L2))
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using dictionary comprehension syntax
>>> L1 = ['a','b','c','d']
>>> L2 = [1,2,3,4]
>>> d = {k:v for k,v in zip(L1,L2)}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4} | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "If L1 and L2 are list objects containing keys and respective values, following methods can be used to construct dictionary object."
},
{
"code": null,
"e": 1255,
"s": 1193,
"text": "Zip two lists and convert to dictionary using dict() function"
},
{
"code": null,
"e": 1365,
"s": 1255,
"text": ">>> L1 = ['a','b','c','d']\n>>> L2 = [1,2,3,4]\n>>> d = dict(zip(L1,L2))\n>>> d\n{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
},
{
"code": null,
"e": 1403,
"s": 1365,
"text": "Using dictionary comprehension syntax"
},
{
"code": null,
"e": 1524,
"s": 1403,
"text": ">>> L1 = ['a','b','c','d']\n>>> L2 = [1,2,3,4]\n>>> d = {k:v for k,v in zip(L1,L2)}\n>>> d\n{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
}
] |
How to convert numbers to words using Python? | The constructor for the string class in python, ie, str can be used to convert a number to a string in python. For example,
i = 10050
str_i = str(i)
print(type(str_i))
This will give the output:
<class 'str'>
But if you want something that converts integers to words like 99 to ninety-nine, you have to use an external package or build one yourself. The pynum2word module is pretty good at this task. You can install it using
$ pip install pynum2word
Then use it in the following way
>>> import num2word
>>> num2word.to_card(16)
'sixteen'
>>> num2word.to_card(23)
'twenty-three'
>>> num2word.to_card(1223)
'one thousand, two hundred and twenty-three' | [
{
"code": null,
"e": 1186,
"s": 1062,
"text": "The constructor for the string class in python, ie, str can be used to convert a number to a string in python. For example,"
},
{
"code": null,
"e": 1230,
"s": 1186,
"text": "i = 10050\nstr_i = str(i)\nprint(type(str_i))"
},
{
"code": null,
"e": 1257,
"s": 1230,
"text": "This will give the output:"
},
{
"code": null,
"e": 1271,
"s": 1257,
"text": "<class 'str'>"
},
{
"code": null,
"e": 1488,
"s": 1271,
"text": "But if you want something that converts integers to words like 99 to ninety-nine, you have to use an external package or build one yourself. The pynum2word module is pretty good at this task. You can install it using"
},
{
"code": null,
"e": 1513,
"s": 1488,
"text": "$ pip install pynum2word"
},
{
"code": null,
"e": 1546,
"s": 1513,
"text": "Then use it in the following way"
},
{
"code": null,
"e": 1713,
"s": 1546,
"text": ">>> import num2word\n>>> num2word.to_card(16)\n'sixteen'\n>>> num2word.to_card(23)\n'twenty-three'\n>>> num2word.to_card(1223)\n'one thousand, two hundred and twenty-three'"
}
] |
gettext - Unix, Linux Command | Display native language translation of a textual message.
gettext is an internationalization and localization system commonly used for writing multilingual programs. For gettext to work, the message catalogue is required.
$ cat test.sh
gettext -s "This message to be translated"
$ xgettext -c /
msgid "This message to be translated"
msgstr ""
$ msginit --locale=es --input=name.pot
msgid "This message to be translated"
msgstr "This is a translated message"
$ msginit --locale=es --input=es.pot
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10637,
"s": 10577,
"text": "\nDisplay native language translation of a textual message.\n"
},
{
"code": null,
"e": 10801,
"s": 10637,
"text": "gettext is an internationalization and localization system commonly used for writing multilingual programs. For gettext to work, the message catalogue is required."
},
{
"code": null,
"e": 10859,
"s": 10801,
"text": "$ cat test.sh\ngettext -s \"This message to be translated\"\n"
},
{
"code": null,
"e": 10876,
"s": 10859,
"text": "$ xgettext -c /\n"
},
{
"code": null,
"e": 10925,
"s": 10876,
"text": "msgid \"This message to be translated\"\nmsgstr \"\"\n"
},
{
"code": null,
"e": 10965,
"s": 10925,
"text": "$ msginit --locale=es --input=name.pot\n"
},
{
"code": null,
"e": 11042,
"s": 10965,
"text": "msgid \"This message to be translated\"\nmsgstr \"This is a translated message\"\n"
},
{
"code": null,
"e": 11080,
"s": 11042,
"text": "$ msginit --locale=es --input=es.pot\n"
},
{
"code": null,
"e": 11115,
"s": 11080,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 11143,
"s": 11115,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11177,
"s": 11143,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11194,
"s": 11177,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11227,
"s": 11194,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11238,
"s": 11227,
"text": " Pradeep D"
},
{
"code": null,
"e": 11273,
"s": 11238,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11289,
"s": 11273,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 11322,
"s": 11289,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11334,
"s": 11322,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 11366,
"s": 11334,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11374,
"s": 11366,
"text": " Uplatz"
},
{
"code": null,
"e": 11381,
"s": 11374,
"text": " Print"
},
{
"code": null,
"e": 11392,
"s": 11381,
"text": " Add Notes"
}
] |
Add space between pagination links with CSS | You can try to run the following code to add space between pagination links with CSS:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
display: inline-block;
}
.demo a {
color: red;
padding: 5px 12px;
text-decoration: none;
transition: background-color 2s;
border: 1px solid orange;
}
.demo a.active {
background-color: orange;
color: white;
border-radius: 5px;
}
.demo a:hover:not(.active) {
background-color: yellow;
}
.demo a:first-child {
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
.demo a:last-child {
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
}
</style>
</head>
<body>
<h2>Our Quizzes</h2>
<div class = "demo">
<a href = "prev.html"><</a>
<a href = "quiz1.html">Quiz1</a>
<a href = "quiz2.html">Quiz2</a>
<a href = "quiz3.html" class = "active">Quiz3</a>
<a href = "quiz4.html">Quiz4</a>
<a href = "next.html">></a>
</div>
</body>
</html> | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "You can try to run the following code to add space between pagination links with CSS:"
},
{
"code": null,
"e": 1158,
"s": 1148,
"text": "Live Demo"
},
{
"code": null,
"e": 2330,
"s": 1158,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .demo {\n display: inline-block;\n }\n .demo a {\n color: red;\n padding: 5px 12px;\n text-decoration: none;\n transition: background-color 2s;\n border: 1px solid orange;\n }\n .demo a.active {\n background-color: orange;\n color: white;\n border-radius: 5px;\n }\n .demo a:hover:not(.active) {\n background-color: yellow;\n }\n .demo a:first-child {\n border-top-left-radius: 10px;\n border-bottom-left-radius: 10px;\n }\n .demo a:last-child {\n border-top-right-radius: 10px;\n border-bottom-right-radius: 10px;\n }\n </style>\n </head>\n <body>\n <h2>Our Quizzes</h2>\n <div class = \"demo\">\n <a href = \"prev.html\"><</a>\n <a href = \"quiz1.html\">Quiz1</a>\n <a href = \"quiz2.html\">Quiz2</a>\n <a href = \"quiz3.html\" class = \"active\">Quiz3</a>\n <a href = \"quiz4.html\">Quiz4</a>\n <a href = \"next.html\">></a>\n </div>\n </body>\n</html>"
}
] |
Model Management in productive ML software | by Maximilian Beckers | Towards Data Science | Developing a good Proof of Concept for a machine learning problem can be hard sometimes. You are working through tons and tons of data engineering layers and testing many different models until finally you have “cracked the code” and gotten a good score on your test set. Hurray! That is great news because now the fun really starts and your model can potentially help your company make or save money. If that ever is supposed to be the case you have to build productive software around your model. What does that mean? You need a solution architecture that allows for a live data flow, a compute component that can scale with that data flow, a real front end, and a good storage solution. And those are just your main components! You also need a monitoring solution in case any of your software pieces run an error and a DevOps tool that takes care of testing and releasing your newer code versions into the productive environment. Now that’s just your every-day data use case, if you are trying to build AI software you probably are dealing with massive amounts of data and a very intense data engineering layer to get your raw data into a form that can be used to train/infer machine learning models. Most likely you will need an ETL pipelining tool to orchestrate your data engineering during every day runs. But lastly one thing that might be the most important piece of the puzzle, you need to know what your ML model is doing over time!
How good is the model today vs how good was it yesterday?
Which features was it trained on?
What are the optimal hyperparameters? Do they change over time?
How do training and test data change over time?
Which model is in production/integration?
How do I bring a major model update into this set-up?
All these questions arise due to the complexity of the machine learning lifecycle. Because data changes over time, even in productive ML settings, we are pretty much constantly in a loop of collecting data, exploring models, refining models, and finally testing/evaluating, deploying, and in the end monitoring our models.
How can we keep control over this complex loop that is constantly evolving?
Actually there is a very simple solution — Write everything down! Or in computer terminology:
LOGGING OF ALL THE RELEVANT INFORMATION!
A fancy name for this is Machine Learning Model Management, a vital part of MLOps. The constant process of capturing relevant information while the software is executed and making automatic decisions based on it. Metrics during preparation, training, and evaluation as well as trained models, preprocessing pipelines, and hyperparameters. All saved away neatly in a model database, ready to be compared, analyzed and used to pick out one specific model that will serve as the prediction layer. Now in theory you could just use any normal database as backend and write your own API on how to measure and store away all this info. In practice, however, we can make use of some pretty cool pre-built frameworks designed to help with this task. Azure Machine Learning, Polyaxon, and mldb.ai are just a few examples. This article focuses on MLflow. MLflow was developed by the folks at Databricks and integrates seamlessly into their ecosystem. As I am already doing all my ETL as well as hyperparameter tuning on Databricks (using the hyperopt framework) it was an easy choice for model management framework.
MLflow is an “open source platform for the machine learning lifecycle”. The managed version on Databricks is especially easy to use and you can even create an empty MLflow experiment using the user interface by clicking on “New MLflow Experiment” below.
You don’t have to worry about setting up a backend database, everything is taken care of automatically. Once the experiment is available, the MLflow tracking API can be used in your code to log various information. For a quick walk-through, let’s have a look at an example:
I had a look at the open source wine dataset from sklearn. It contains data on the chemical analysis of three different wine types from different Italian wine cultivators. The goal is to create a classifier to predict the wine class, using the given features, such as alcohol, magnesium, color intensity, etc.
You can start by opening up a new Databricks notebook and load the following packages (make sure they are installed):
import warningsfrom sklearn import datasetsfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score, f1_scoreimport pandas as pdimport numpy as npimport mlflowimport mlflow.sklearnwarnings.filterwarnings(“ignore”)
Now you can load the data into a Pandas dataframe:
# Load wine datasetwine = datasets.load_wine()X = wine.datay = wine.target#create pandas df:Y = np.array([y]).transpose()d = np.concatenate((X, Y), axis=1)cols = ["Alcohol", "Malic acid", "Ash", "Alcalinity of ash", "Magnesium", "Total phenols", "Flavanoids", "Nonflavanoid phenols", "Proanthocyanins", "Color intensity", "Hue", "OD280/OD315 of diluted wines", "Proline", "class"]data = pd.DataFrame(d, columns=cols)
First we need to make up our mind on what all we would like to log during the training phase. In principle MLflow lets us log anything. Yes anything! In the most basic form we can write any information to a file and have MLflow log it as an artifact. Pre-built logging functionality includes:
run ID
date
parameters (e.g.: hyperparameters)
metrics
models (trained models)
artifacts (e.g.: trained encoders, preprocessing pipelines etc)
tags (e.g.: model version, model name, other meta information)
In this example we will stick to the basics and log 2 metrics, all the hyperparameters as well as the trained model and give it a model version tag. In order to simplify a little bit we build a little wrapper around scikit-learn’s .fit() method that takes care of the MLflow logging. Then we can call the wrapper, passing in different hyperparameters and see how performance varies and everything gets logged to our MLflow backend.
Let’s start with an evaluation function, including accuracy and the F1 score:
from sklearn.metrics import accuracy_score, f1_scoredef eval_metrics(actual, pred): acc = accuracy_score(actual, pred) f1 = f1_score(actual, pred, average = "weighted") return acc, f1
and then write our wrapper around scikit-learn’s RandomForestClassifier, giving it two hyperparameters to tweak, the number of trees in the forest, as well as the fraction of feature columns to use per decision split within a tree.
def train_winedata(data, in_n_estimators, in_max_features): warnings.filterwarnings("ignore") np.random.seed(40)# Split the data into training and test sets. (0.75, 0.25) split. train, test = train_test_split(data, stratify= data["class"])# The predicted column is "class" train_x = train.drop(["class"], axis=1) test_x = test.drop(["class"], axis=1) train_y = train[["class"]] test_y = test[["class"]] # start run with mlflow.start_run(): rf = RandomForestClassifier(n_estimators = in_n_estimators, max_features= in_max_features) rf.fit(train_x, train_y) acc, f1 = eval_metrics(test_y, rf.predict(test_x)) print(" Accuracy: %s" % acc) print(" F1 Score: %s" % f1) #log metrics mlflow.log_metric("F1", f1) mlflow.log_metric("Accuracy", acc) #log params mlflow.log_param("n_estimator", in_n_estimators) mlflow.log_param("max_features", in_max_features) # add tags mlflow.set_tag("model_name", "Wineforest") # save the trained model mlflow.sklearn.log_model(rf, "model")
Before running the training we need to tell our MLflow Client where to log all this info. We will have it point to the empty MLflow experiment we created earlier via the Databricks UI:
mlflow.set_experiment("/Users/<your user>/WineClassifier")
Now we can run our first set of hyperparameters:
train_winedata(data, in_n_estimators= 1, in_max_features= 0.1)Accuracy: 0.733 F1 Score: 0.731
We can see that a fairly decent Accuracy and F1 score was achieved by a single tree only using 10% of the features per split.
Rerunning the training now with 50% of max_features:
train_winedata(data, in_n_estimators= 1, in_max_features= 0.5)Accuracy: 0.933 F1 Score: 0.931
Already gives a really good score. However, including 100 trees in the random forest increases the performance even more:
train_winedata(data, in_n_estimators= 100, in_max_features= 0.5)Accuracy: 0.98 F1 Score: 0.98
Let’s have a quick look at the outcome in our MLflow experiment:
We can see a nice GUI that includes all our logged info. We can also deep-dive into a single run by clicking on the date. There we find the logged model as an artifact, ready to be loaded and used to make predictions. We can now set up our serving layer to fetch the best model (e.g. by F1 score) and automatically deploy to it our production environment. The effect of different hyperparameter logs can be explored to potentially adjust search spaces in the hyperparameter grid when doing extensive grid search.
When building productive software we always have to keep in mind that one single environment most likely won’t do the trick. If we have a productive setup running and we want to make changes to the code we need at least an integration environment where we can first test any changes.
As training data increases and changes over time, we also need to define cycles in which we retrain our model, redo hyperparameter tuning or even re-evaluate the type of machine learning model overall. This needs to happen in an automated fashion and the best model (tested on a fixed external dataset), that has been successfully tested in the integration environment, needs to be deployed in production at all times. If we decide to change the external test dataset or the code changes in a major way we might want to incorporate a newer model version and only compare models for deployment older than such version etc. A somewhat complicated process.
The model registry within MLflow provides a tool that can help with this process. Here we can register trained models from our MLflow backend with different names, versions, and stages. Stages ranging from “None”, over “Staging” to “Production”.
Logging our wine classifier from earlier, we only need to grab the model_uri from MLflow and run:
mlflow.register_model(model_uri=model_uri, name="winetest")
Let’s have a closer look at how we can manage two basic ML lifecycle scenarios with this setup: Retraining and retuning the already deployed PROD model periodically as well as deploying new or updated model code into the productive system. The main difference: the latter needs to go through a testing phase on INT since the code has changed while the former does not. The code remains the same, simply the performance of the model might have changed.
Think of the following scenario: A model named AImodel currently on version 1.0 is registered as “Production” and also deployed on PROD. We are retraining and retuning the model every x days. Once retraining and retuning occurs we can grab the model from the registry, run our training and tuning pipeline, logging the new model performance of AImodel version 1.0 into MLflow. Now we can kick off an automatic selection process by comparing the performance of the newly trained AImodel 1.0 with all existing performances of AImodel 1.0 on an external dataset and deploy the best model (due to some metric) by overwriting the current AImodel 1.0 sitting in the model Registry at “Production” stage with our selected model. Now we still have AImodel 1.0 in PROD, only with a (hopefully) better performance since trained on newer (more) data.
That is pretty straightforward and allows for constantly deploying the best AImodel 1.0 in production. What if we want to change something in the code of AImodel 1.0 or even introduce MLmodel 1.0 to compete with AImodel 1.0 for the production slot? We need to make use of our integration environment!
Deploying code into an environment is managed by a DevOps Pipeline, which gets triggered by a pull request on the int or master Git branch respectively. That get’s us the INT or PROD version of our code into the respective environment. So let’s imagine we included distributed training into the code of AImodel 1.0. We deploy whats on the INT Git branch through DevOps into our INT environment, and run the newly configured training, again logging into MLflow (giving the model an INT tag) and register the model as AImodel 2.0 as well as “Staging”. Now the key concept: Our two environments are automatically choosing the model to use as serving layer due to some criteria (as explained above using a performance metric). Since we only want AImodel 2.0 used (and therefore tested) on INT and not yet on PROD, we introduce model version allowances per environment. This means PROD is only allowed to select from models ≤ Version 1.0 whereas INT is allowed to select versions ≤ 2.0 (or if we specifically want to test version 2.0: =2.0). Upon completion of the test phase on INT, we can transition the model to “Production” in the registry and up the model version allowance in PROD to ≤ 2.0 (or =2.0 or 1.0≤PROD version≤2.0 etc). Now the new code (new model) is ready for the PROD environment. So basically in every new training loop on INT, we are comparing and potentially replacing the current model in “Staging” with a subset of models, according to version allowance on INT (and e.g. model tag model name, etc), from MLflow. The same thing happens on PROD according to version allowance on PROD using the model sitting in “Production”. In case we have major updates to the code (such as wanting to use a completely different model) we can always register the model under a new name and start with version 1.0 all over again.
This setup allows for automatically deploying the best performing model while still having the availability to introduce new code and models into the system smoothly. However, it is still a somewhat basic setup as in most cases tuning and training will be done asynchronously since the tuning job is very compute intensive and might therefore only occur for example every 10th training loop. Now we can think about using different MLflow backends, one for tuning and one for training to keep things clear and manageable.
Overall the tooling available in MLflow allows for a very flexible model management setup that can be tailored directly to the use case’s needs and fulfills production-grade requirements. We can also imagine building a dashboard on top of our MLflow backend, allowing power users to track the performance, version status as well as parameter and feature selections without having to open Databricks.
Try it out and take your machine learning application to the next level :)
MLflow
mlflow.org
MLflow Model Registry | [
{
"code": null,
"e": 1616,
"s": 172,
"text": "Developing a good Proof of Concept for a machine learning problem can be hard sometimes. You are working through tons and tons of data engineering layers and testing many different models until finally you have “cracked the code” and gotten a good score on your test set. Hurray! That is great news because now the fun really starts and your model can potentially help your company make or save money. If that ever is supposed to be the case you have to build productive software around your model. What does that mean? You need a solution architecture that allows for a live data flow, a compute component that can scale with that data flow, a real front end, and a good storage solution. And those are just your main components! You also need a monitoring solution in case any of your software pieces run an error and a DevOps tool that takes care of testing and releasing your newer code versions into the productive environment. Now that’s just your every-day data use case, if you are trying to build AI software you probably are dealing with massive amounts of data and a very intense data engineering layer to get your raw data into a form that can be used to train/infer machine learning models. Most likely you will need an ETL pipelining tool to orchestrate your data engineering during every day runs. But lastly one thing that might be the most important piece of the puzzle, you need to know what your ML model is doing over time!"
},
{
"code": null,
"e": 1674,
"s": 1616,
"text": "How good is the model today vs how good was it yesterday?"
},
{
"code": null,
"e": 1708,
"s": 1674,
"text": "Which features was it trained on?"
},
{
"code": null,
"e": 1772,
"s": 1708,
"text": "What are the optimal hyperparameters? Do they change over time?"
},
{
"code": null,
"e": 1820,
"s": 1772,
"text": "How do training and test data change over time?"
},
{
"code": null,
"e": 1862,
"s": 1820,
"text": "Which model is in production/integration?"
},
{
"code": null,
"e": 1916,
"s": 1862,
"text": "How do I bring a major model update into this set-up?"
},
{
"code": null,
"e": 2239,
"s": 1916,
"text": "All these questions arise due to the complexity of the machine learning lifecycle. Because data changes over time, even in productive ML settings, we are pretty much constantly in a loop of collecting data, exploring models, refining models, and finally testing/evaluating, deploying, and in the end monitoring our models."
},
{
"code": null,
"e": 2315,
"s": 2239,
"text": "How can we keep control over this complex loop that is constantly evolving?"
},
{
"code": null,
"e": 2409,
"s": 2315,
"text": "Actually there is a very simple solution — Write everything down! Or in computer terminology:"
},
{
"code": null,
"e": 2450,
"s": 2409,
"text": "LOGGING OF ALL THE RELEVANT INFORMATION!"
},
{
"code": null,
"e": 3555,
"s": 2450,
"text": "A fancy name for this is Machine Learning Model Management, a vital part of MLOps. The constant process of capturing relevant information while the software is executed and making automatic decisions based on it. Metrics during preparation, training, and evaluation as well as trained models, preprocessing pipelines, and hyperparameters. All saved away neatly in a model database, ready to be compared, analyzed and used to pick out one specific model that will serve as the prediction layer. Now in theory you could just use any normal database as backend and write your own API on how to measure and store away all this info. In practice, however, we can make use of some pretty cool pre-built frameworks designed to help with this task. Azure Machine Learning, Polyaxon, and mldb.ai are just a few examples. This article focuses on MLflow. MLflow was developed by the folks at Databricks and integrates seamlessly into their ecosystem. As I am already doing all my ETL as well as hyperparameter tuning on Databricks (using the hyperopt framework) it was an easy choice for model management framework."
},
{
"code": null,
"e": 3809,
"s": 3555,
"text": "MLflow is an “open source platform for the machine learning lifecycle”. The managed version on Databricks is especially easy to use and you can even create an empty MLflow experiment using the user interface by clicking on “New MLflow Experiment” below."
},
{
"code": null,
"e": 4083,
"s": 3809,
"text": "You don’t have to worry about setting up a backend database, everything is taken care of automatically. Once the experiment is available, the MLflow tracking API can be used in your code to log various information. For a quick walk-through, let’s have a look at an example:"
},
{
"code": null,
"e": 4393,
"s": 4083,
"text": "I had a look at the open source wine dataset from sklearn. It contains data on the chemical analysis of three different wine types from different Italian wine cultivators. The goal is to create a classifier to predict the wine class, using the given features, such as alcohol, magnesium, color intensity, etc."
},
{
"code": null,
"e": 4511,
"s": 4393,
"text": "You can start by opening up a new Databricks notebook and load the following packages (make sure they are installed):"
},
{
"code": null,
"e": 4814,
"s": 4511,
"text": "import warningsfrom sklearn import datasetsfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score, f1_scoreimport pandas as pdimport numpy as npimport mlflowimport mlflow.sklearnwarnings.filterwarnings(“ignore”)"
},
{
"code": null,
"e": 4865,
"s": 4814,
"text": "Now you can load the data into a Pandas dataframe:"
},
{
"code": null,
"e": 5282,
"s": 4865,
"text": "# Load wine datasetwine = datasets.load_wine()X = wine.datay = wine.target#create pandas df:Y = np.array([y]).transpose()d = np.concatenate((X, Y), axis=1)cols = [\"Alcohol\", \"Malic acid\", \"Ash\", \"Alcalinity of ash\", \"Magnesium\", \"Total phenols\", \"Flavanoids\", \"Nonflavanoid phenols\", \"Proanthocyanins\", \"Color intensity\", \"Hue\", \"OD280/OD315 of diluted wines\", \"Proline\", \"class\"]data = pd.DataFrame(d, columns=cols)"
},
{
"code": null,
"e": 5575,
"s": 5282,
"text": "First we need to make up our mind on what all we would like to log during the training phase. In principle MLflow lets us log anything. Yes anything! In the most basic form we can write any information to a file and have MLflow log it as an artifact. Pre-built logging functionality includes:"
},
{
"code": null,
"e": 5582,
"s": 5575,
"text": "run ID"
},
{
"code": null,
"e": 5587,
"s": 5582,
"text": "date"
},
{
"code": null,
"e": 5622,
"s": 5587,
"text": "parameters (e.g.: hyperparameters)"
},
{
"code": null,
"e": 5630,
"s": 5622,
"text": "metrics"
},
{
"code": null,
"e": 5654,
"s": 5630,
"text": "models (trained models)"
},
{
"code": null,
"e": 5718,
"s": 5654,
"text": "artifacts (e.g.: trained encoders, preprocessing pipelines etc)"
},
{
"code": null,
"e": 5781,
"s": 5718,
"text": "tags (e.g.: model version, model name, other meta information)"
},
{
"code": null,
"e": 6213,
"s": 5781,
"text": "In this example we will stick to the basics and log 2 metrics, all the hyperparameters as well as the trained model and give it a model version tag. In order to simplify a little bit we build a little wrapper around scikit-learn’s .fit() method that takes care of the MLflow logging. Then we can call the wrapper, passing in different hyperparameters and see how performance varies and everything gets logged to our MLflow backend."
},
{
"code": null,
"e": 6291,
"s": 6213,
"text": "Let’s start with an evaluation function, including accuracy and the F1 score:"
},
{
"code": null,
"e": 6484,
"s": 6291,
"text": "from sklearn.metrics import accuracy_score, f1_scoredef eval_metrics(actual, pred): acc = accuracy_score(actual, pred) f1 = f1_score(actual, pred, average = \"weighted\") return acc, f1"
},
{
"code": null,
"e": 6716,
"s": 6484,
"text": "and then write our wrapper around scikit-learn’s RandomForestClassifier, giving it two hyperparameters to tweak, the number of trees in the forest, as well as the fraction of feature columns to use per decision split within a tree."
},
{
"code": null,
"e": 7790,
"s": 6716,
"text": "def train_winedata(data, in_n_estimators, in_max_features): warnings.filterwarnings(\"ignore\") np.random.seed(40)# Split the data into training and test sets. (0.75, 0.25) split. train, test = train_test_split(data, stratify= data[\"class\"])# The predicted column is \"class\" train_x = train.drop([\"class\"], axis=1) test_x = test.drop([\"class\"], axis=1) train_y = train[[\"class\"]] test_y = test[[\"class\"]] # start run with mlflow.start_run(): rf = RandomForestClassifier(n_estimators = in_n_estimators, max_features= in_max_features) rf.fit(train_x, train_y) acc, f1 = eval_metrics(test_y, rf.predict(test_x)) print(\" Accuracy: %s\" % acc) print(\" F1 Score: %s\" % f1) #log metrics mlflow.log_metric(\"F1\", f1) mlflow.log_metric(\"Accuracy\", acc) #log params mlflow.log_param(\"n_estimator\", in_n_estimators) mlflow.log_param(\"max_features\", in_max_features) # add tags mlflow.set_tag(\"model_name\", \"Wineforest\") # save the trained model mlflow.sklearn.log_model(rf, \"model\")"
},
{
"code": null,
"e": 7975,
"s": 7790,
"text": "Before running the training we need to tell our MLflow Client where to log all this info. We will have it point to the empty MLflow experiment we created earlier via the Databricks UI:"
},
{
"code": null,
"e": 8034,
"s": 7975,
"text": "mlflow.set_experiment(\"/Users/<your user>/WineClassifier\")"
},
{
"code": null,
"e": 8083,
"s": 8034,
"text": "Now we can run our first set of hyperparameters:"
},
{
"code": null,
"e": 8179,
"s": 8083,
"text": "train_winedata(data, in_n_estimators= 1, in_max_features= 0.1)Accuracy: 0.733 F1 Score: 0.731"
},
{
"code": null,
"e": 8305,
"s": 8179,
"text": "We can see that a fairly decent Accuracy and F1 score was achieved by a single tree only using 10% of the features per split."
},
{
"code": null,
"e": 8358,
"s": 8305,
"text": "Rerunning the training now with 50% of max_features:"
},
{
"code": null,
"e": 8454,
"s": 8358,
"text": "train_winedata(data, in_n_estimators= 1, in_max_features= 0.5)Accuracy: 0.933 F1 Score: 0.931"
},
{
"code": null,
"e": 8576,
"s": 8454,
"text": "Already gives a really good score. However, including 100 trees in the random forest increases the performance even more:"
},
{
"code": null,
"e": 8673,
"s": 8576,
"text": "train_winedata(data, in_n_estimators= 100, in_max_features= 0.5)Accuracy: 0.98 F1 Score: 0.98"
},
{
"code": null,
"e": 8738,
"s": 8673,
"text": "Let’s have a quick look at the outcome in our MLflow experiment:"
},
{
"code": null,
"e": 9251,
"s": 8738,
"text": "We can see a nice GUI that includes all our logged info. We can also deep-dive into a single run by clicking on the date. There we find the logged model as an artifact, ready to be loaded and used to make predictions. We can now set up our serving layer to fetch the best model (e.g. by F1 score) and automatically deploy to it our production environment. The effect of different hyperparameter logs can be explored to potentially adjust search spaces in the hyperparameter grid when doing extensive grid search."
},
{
"code": null,
"e": 9535,
"s": 9251,
"text": "When building productive software we always have to keep in mind that one single environment most likely won’t do the trick. If we have a productive setup running and we want to make changes to the code we need at least an integration environment where we can first test any changes."
},
{
"code": null,
"e": 10189,
"s": 9535,
"text": "As training data increases and changes over time, we also need to define cycles in which we retrain our model, redo hyperparameter tuning or even re-evaluate the type of machine learning model overall. This needs to happen in an automated fashion and the best model (tested on a fixed external dataset), that has been successfully tested in the integration environment, needs to be deployed in production at all times. If we decide to change the external test dataset or the code changes in a major way we might want to incorporate a newer model version and only compare models for deployment older than such version etc. A somewhat complicated process."
},
{
"code": null,
"e": 10435,
"s": 10189,
"text": "The model registry within MLflow provides a tool that can help with this process. Here we can register trained models from our MLflow backend with different names, versions, and stages. Stages ranging from “None”, over “Staging” to “Production”."
},
{
"code": null,
"e": 10533,
"s": 10435,
"text": "Logging our wine classifier from earlier, we only need to grab the model_uri from MLflow and run:"
},
{
"code": null,
"e": 10593,
"s": 10533,
"text": "mlflow.register_model(model_uri=model_uri, name=\"winetest\")"
},
{
"code": null,
"e": 11045,
"s": 10593,
"text": "Let’s have a closer look at how we can manage two basic ML lifecycle scenarios with this setup: Retraining and retuning the already deployed PROD model periodically as well as deploying new or updated model code into the productive system. The main difference: the latter needs to go through a testing phase on INT since the code has changed while the former does not. The code remains the same, simply the performance of the model might have changed."
},
{
"code": null,
"e": 11885,
"s": 11045,
"text": "Think of the following scenario: A model named AImodel currently on version 1.0 is registered as “Production” and also deployed on PROD. We are retraining and retuning the model every x days. Once retraining and retuning occurs we can grab the model from the registry, run our training and tuning pipeline, logging the new model performance of AImodel version 1.0 into MLflow. Now we can kick off an automatic selection process by comparing the performance of the newly trained AImodel 1.0 with all existing performances of AImodel 1.0 on an external dataset and deploy the best model (due to some metric) by overwriting the current AImodel 1.0 sitting in the model Registry at “Production” stage with our selected model. Now we still have AImodel 1.0 in PROD, only with a (hopefully) better performance since trained on newer (more) data."
},
{
"code": null,
"e": 12186,
"s": 11885,
"text": "That is pretty straightforward and allows for constantly deploying the best AImodel 1.0 in production. What if we want to change something in the code of AImodel 1.0 or even introduce MLmodel 1.0 to compete with AImodel 1.0 for the production slot? We need to make use of our integration environment!"
},
{
"code": null,
"e": 14016,
"s": 12186,
"text": "Deploying code into an environment is managed by a DevOps Pipeline, which gets triggered by a pull request on the int or master Git branch respectively. That get’s us the INT or PROD version of our code into the respective environment. So let’s imagine we included distributed training into the code of AImodel 1.0. We deploy whats on the INT Git branch through DevOps into our INT environment, and run the newly configured training, again logging into MLflow (giving the model an INT tag) and register the model as AImodel 2.0 as well as “Staging”. Now the key concept: Our two environments are automatically choosing the model to use as serving layer due to some criteria (as explained above using a performance metric). Since we only want AImodel 2.0 used (and therefore tested) on INT and not yet on PROD, we introduce model version allowances per environment. This means PROD is only allowed to select from models ≤ Version 1.0 whereas INT is allowed to select versions ≤ 2.0 (or if we specifically want to test version 2.0: =2.0). Upon completion of the test phase on INT, we can transition the model to “Production” in the registry and up the model version allowance in PROD to ≤ 2.0 (or =2.0 or 1.0≤PROD version≤2.0 etc). Now the new code (new model) is ready for the PROD environment. So basically in every new training loop on INT, we are comparing and potentially replacing the current model in “Staging” with a subset of models, according to version allowance on INT (and e.g. model tag model name, etc), from MLflow. The same thing happens on PROD according to version allowance on PROD using the model sitting in “Production”. In case we have major updates to the code (such as wanting to use a completely different model) we can always register the model under a new name and start with version 1.0 all over again."
},
{
"code": null,
"e": 14537,
"s": 14016,
"text": "This setup allows for automatically deploying the best performing model while still having the availability to introduce new code and models into the system smoothly. However, it is still a somewhat basic setup as in most cases tuning and training will be done asynchronously since the tuning job is very compute intensive and might therefore only occur for example every 10th training loop. Now we can think about using different MLflow backends, one for tuning and one for training to keep things clear and manageable."
},
{
"code": null,
"e": 14937,
"s": 14537,
"text": "Overall the tooling available in MLflow allows for a very flexible model management setup that can be tailored directly to the use case’s needs and fulfills production-grade requirements. We can also imagine building a dashboard on top of our MLflow backend, allowing power users to track the performance, version status as well as parameter and feature selections without having to open Databricks."
},
{
"code": null,
"e": 15012,
"s": 14937,
"text": "Try it out and take your machine learning application to the next level :)"
},
{
"code": null,
"e": 15019,
"s": 15012,
"text": "MLflow"
},
{
"code": null,
"e": 15030,
"s": 15019,
"text": "mlflow.org"
}
] |
Python | Creating a Simple Drawing App in kivy - GeeksforGeeks | 02 Feb, 2021
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.
Kivy Tutorial – Learn Kivy with Examples.
In this we are going to create a simple drawing App with the help of kivy initially we are just making a canvas and a paintbrush so that by moving the cursor you can just feel like a drawing Application.In this, the widgets are added dynamically. If widgets are to be added dynamically, at run-time, depending on user interaction, they can only be added in the Python file.We are using widgets, layout, random to make it good.
Now Basic Approach of the App:
1) import kivy
2) import kivy App
3) import Relativelayout
4) import widget
5) set minimum version(optional)
6) Create widget class as needed
7) Create Layout class
8) create the App class
9) create .kv file
10) return the widget/layout etc class
11) Run an instance of the class
# .py file:
Python3
# Program to explain how to create drawing App in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Widgets are elements of a# graphical user interface that# form part of the User Experience.from kivy.uix.widget import Widget # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # Create the Widget classclass Paint_brush(Widget): pass # Create the layout class# where you are defining the working of# Paint_brush() classclass Drawing(RelativeLayout): # On mouse press how Paint_brush behave def on_touch_down(self, touch): pb = Paint_brush() pb.center = touch.pos self.add_widget(pb) # On mouse movement how Paint_brush behave def on_touch_move(self, touch): pb = Paint_brush() pb.center = touch.pos self.add_widget(pb) # Create the App class class DrawingApp(App): def build(self): return Drawing() DrawingApp().run()
# .ky file:
Python3
# Drawing.kv implementation # for assigning random color to the brush#:import rnd random # Paint brush coding<Paint_brush>: size_hint: None, None size: 25, 50 canvas: Color: rgb: rnd.random(), rnd.random(), rnd.random() Triangle: points: (self.x, self.y, self.x + self.width / 4, self.y, self.x + self.width / 4, self.y + self.height / 4) # Drawing pad creation <Drawing>: canvas: Color: rgb: .2, .5, .5 Rectangle: size: root.size pos: root.pos
Output:
abhigoya
Python-gui
Python-kivy
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 24164,
"s": 23927,
"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": 24206,
"s": 24164,
"text": "Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 24637,
"s": 24208,
"text": "In this we are going to create a simple drawing App with the help of kivy initially we are just making a canvas and a paintbrush so that by moving the cursor you can just feel like a drawing Application.In this, the widgets are added dynamically. If widgets are to be added dynamically, at run-time, depending on user interaction, they can only be added in the Python file.We are using widgets, layout, random to make it good. "
},
{
"code": null,
"e": 24949,
"s": 24637,
"text": "Now Basic Approach of the App:\n\n1) import kivy\n2) import kivy App\n3) import Relativelayout\n4) import widget\n5) set minimum version(optional)\n6) Create widget class as needed\n7) Create Layout class\n8) create the App class\n9) create .kv file\n10) return the widget/layout etc class\n11) Run an instance of the class"
},
{
"code": null,
"e": 24963,
"s": 24949,
"text": "# .py file: "
},
{
"code": null,
"e": 24971,
"s": 24963,
"text": "Python3"
},
{
"code": "# Program to explain how to create drawing App in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Widgets are elements of a# graphical user interface that# form part of the User Experience.from kivy.uix.widget import Widget # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # Create the Widget classclass Paint_brush(Widget): pass # Create the layout class# where you are defining the working of# Paint_brush() classclass Drawing(RelativeLayout): # On mouse press how Paint_brush behave def on_touch_down(self, touch): pb = Paint_brush() pb.center = touch.pos self.add_widget(pb) # On mouse movement how Paint_brush behave def on_touch_move(self, touch): pb = Paint_brush() pb.center = touch.pos self.add_widget(pb) # Create the App class class DrawingApp(App): def build(self): return Drawing() DrawingApp().run()",
"e": 26215,
"s": 24971,
"text": null
},
{
"code": null,
"e": 26228,
"s": 26215,
"text": "# .ky file: "
},
{
"code": null,
"e": 26236,
"s": 26228,
"text": "Python3"
},
{
"code": "# Drawing.kv implementation # for assigning random color to the brush#:import rnd random # Paint brush coding<Paint_brush>: size_hint: None, None size: 25, 50 canvas: Color: rgb: rnd.random(), rnd.random(), rnd.random() Triangle: points: (self.x, self.y, self.x + self.width / 4, self.y, self.x + self.width / 4, self.y + self.height / 4) # Drawing pad creation <Drawing>: canvas: Color: rgb: .2, .5, .5 Rectangle: size: root.size pos: root.pos",
"e": 26816,
"s": 26236,
"text": null
},
{
"code": null,
"e": 26826,
"s": 26816,
"text": "Output: "
},
{
"code": null,
"e": 26839,
"s": 26830,
"text": "abhigoya"
},
{
"code": null,
"e": 26850,
"s": 26839,
"text": "Python-gui"
},
{
"code": null,
"e": 26862,
"s": 26850,
"text": "Python-kivy"
},
{
"code": null,
"e": 26869,
"s": 26862,
"text": "Python"
},
{
"code": null,
"e": 26967,
"s": 26869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26976,
"s": 26967,
"text": "Comments"
},
{
"code": null,
"e": 26989,
"s": 26976,
"text": "Old Comments"
},
{
"code": null,
"e": 27007,
"s": 26989,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27029,
"s": 27007,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27061,
"s": 27029,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27103,
"s": 27061,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27129,
"s": 27103,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27166,
"s": 27129,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27191,
"s": 27166,
"text": "sum() function in Python"
},
{
"code": null,
"e": 27247,
"s": 27191,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27276,
"s": 27247,
"text": "*args and **kwargs in Python"
}
] |
Spring - Bean Definition | The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container. For example, in the form of XML <bean/> definitions which you have already seen in the previous chapters.
Bean definition contains the information called configuration metadata, which is needed for the container to know the following −
How to create a bean
Bean's lifecycle details
Bean's dependencies
All the above configuration metadata translates into a set of the following properties that make up each bean definition.
class
This attribute is mandatory and specifies the bean class to be used to create the bean.
name
This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata, you use the id and/or name attributes to specify the bean identifier(s).
scope
This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter.
constructor-arg
This is used to inject the dependencies and will be discussed in subsequent chapters.
properties
This is used to inject the dependencies and will be discussed in subsequent chapters.
autowiring mode
This is used to inject the dependencies and will be discussed in subsequent chapters.
lazy-initialization mode
A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at the startup.
initialization method
A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter.
destruction method
A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter.
Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. Following are the three important methods to provide configuration metadata to the Spring Container −
XML based configuration file.
Annotation-based configuration
Java-based configuration
You already have seen how XML-based configuration metadata is provided to the container, but let us see another sample of XML-based configuration file with different bean definitions including lazy initialization, initialization method, and destruction method −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- A simple bean definition -->
<bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with lazy init set on -->
<bean id = "..." class = "..." lazy-init = "true">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with initialization method -->
<bean id = "..." class = "..." init-method = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with destruction method -->
<bean id = "..." class = "..." destroy-method = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
You can check Spring Hello World Example to understand how to define, configure and create Spring Beans.
We will discuss about Annotation Based Configuration in a separate chapter. It is intentionally discussed in a separate chapter as we want you to grasp a few other important Spring concepts, before you start programming with Spring Dependency Injection with Annotations. | [
{
"code": null,
"e": 2846,
"s": 2426,
"text": "The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container. For example, in the form of XML <bean/> definitions which you have already seen in the previous chapters."
},
{
"code": null,
"e": 2976,
"s": 2846,
"text": "Bean definition contains the information called configuration metadata, which is needed for the container to know the following −"
},
{
"code": null,
"e": 2997,
"s": 2976,
"text": "How to create a bean"
},
{
"code": null,
"e": 3022,
"s": 2997,
"text": "Bean's lifecycle details"
},
{
"code": null,
"e": 3042,
"s": 3022,
"text": "Bean's dependencies"
},
{
"code": null,
"e": 3164,
"s": 3042,
"text": "All the above configuration metadata translates into a set of the following properties that make up each bean definition."
},
{
"code": null,
"e": 3170,
"s": 3164,
"text": "class"
},
{
"code": null,
"e": 3258,
"s": 3170,
"text": "This attribute is mandatory and specifies the bean class to be used to create the bean."
},
{
"code": null,
"e": 3263,
"s": 3258,
"text": "name"
},
{
"code": null,
"e": 3427,
"s": 3263,
"text": "This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata, you use the id and/or name attributes to specify the bean identifier(s)."
},
{
"code": null,
"e": 3433,
"s": 3427,
"text": "scope"
},
{
"code": null,
"e": 3574,
"s": 3433,
"text": "This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter."
},
{
"code": null,
"e": 3590,
"s": 3574,
"text": "constructor-arg"
},
{
"code": null,
"e": 3676,
"s": 3590,
"text": "This is used to inject the dependencies and will be discussed in subsequent chapters."
},
{
"code": null,
"e": 3687,
"s": 3676,
"text": "properties"
},
{
"code": null,
"e": 3773,
"s": 3687,
"text": "This is used to inject the dependencies and will be discussed in subsequent chapters."
},
{
"code": null,
"e": 3789,
"s": 3773,
"text": "autowiring mode"
},
{
"code": null,
"e": 3875,
"s": 3789,
"text": "This is used to inject the dependencies and will be discussed in subsequent chapters."
},
{
"code": null,
"e": 3900,
"s": 3875,
"text": "lazy-initialization mode"
},
{
"code": null,
"e": 4030,
"s": 3900,
"text": "A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at the startup."
},
{
"code": null,
"e": 4052,
"s": 4030,
"text": "initialization method"
},
{
"code": null,
"e": 4205,
"s": 4052,
"text": "A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter."
},
{
"code": null,
"e": 4224,
"s": 4205,
"text": "destruction method"
},
{
"code": null,
"e": 4348,
"s": 4224,
"text": "A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter."
},
{
"code": null,
"e": 4566,
"s": 4348,
"text": "Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. Following are the three important methods to provide configuration metadata to the Spring Container −"
},
{
"code": null,
"e": 4596,
"s": 4566,
"text": "XML based configuration file."
},
{
"code": null,
"e": 4627,
"s": 4596,
"text": "Annotation-based configuration"
},
{
"code": null,
"e": 4652,
"s": 4627,
"text": "Java-based configuration"
},
{
"code": null,
"e": 4914,
"s": 4652,
"text": "You already have seen how XML-based configuration metadata is provided to the container, but let us see another sample of XML-based configuration file with different bean definitions including lazy initialization, initialization method, and destruction method −"
},
{
"code": null,
"e": 5999,
"s": 4914,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- A simple bean definition -->\n <bean id = \"...\" class = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- A bean definition with lazy init set on -->\n <bean id = \"...\" class = \"...\" lazy-init = \"true\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- A bean definition with initialization method -->\n <bean id = \"...\" class = \"...\" init-method = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- A bean definition with destruction method -->\n <bean id = \"...\" class = \"...\" destroy-method = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n\n <!-- more bean definitions go here -->\n \n</beans>"
},
{
"code": null,
"e": 6104,
"s": 5999,
"text": "You can check Spring Hello World Example to understand how to define, configure and create Spring Beans."
}
] |
Python | Program that matches a word containing ‘g’ followed by one or more e’s using regex | 29 Dec, 2020
Prerequisites : Regular Expressions | Set 1, Set 2
Given a string, the task is to check if that string contains any g followed by one or more e’s in it, otherwise, print No match.
Examples :
Input : geeks for geeks
Output : geeks
geeks
Input : graphic era
Output : No match
Approach : Firstly, make a regular expression (regex) object that matches a word which contains ‘g’ followed by one or more e’s, then pass a string in the findall method. This method returns the list of the matched strings. Loop through the list and print each matched word.
\w – represent Any letter, numeric digit, or the underscore character.* means zero or more occurrence of the character.+ means one or more occurrence of the character.
Below is the implementation :
# Python program that matches a word# containing ‘g’ followed by one or# more e’s using regex # import re packagesimport re # Function check if the any word of# the string containing 'g' followed# by one or more e'sdef check(string) : # Regex \w * ge+\w * will match # text that contains 'g', followed # by one or more 'e' regex = re.compile("ge+\w*") # The findall() method returns all # matching strings of the regex pattern match_object = regex.findall(string) # If length of match_object is not # equal to zero then it contains # matched string if len(match_object) != 0 : # looping through the list for word in match_object : print(word) else : print("No match") # Driver Code if __name__ == '__main__' : # Enter the string string = "Welcome to geeks for geeks" # Calling check function check(string)
Output :
geeks
geeks
ManasChhabra2
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 104,
"s": 53,
"text": "Prerequisites : Regular Expressions | Set 1, Set 2"
},
{
"code": null,
"e": 233,
"s": 104,
"text": "Given a string, the task is to check if that string contains any g followed by one or more e’s in it, otherwise, print No match."
},
{
"code": null,
"e": 244,
"s": 233,
"text": "Examples :"
},
{
"code": null,
"e": 340,
"s": 244,
"text": "Input : geeks for geeks\nOutput : geeks \n geeks\n\nInput : graphic era\nOutput : No match \n"
},
{
"code": null,
"e": 615,
"s": 340,
"text": "Approach : Firstly, make a regular expression (regex) object that matches a word which contains ‘g’ followed by one or more e’s, then pass a string in the findall method. This method returns the list of the matched strings. Loop through the list and print each matched word."
},
{
"code": null,
"e": 783,
"s": 615,
"text": "\\w – represent Any letter, numeric digit, or the underscore character.* means zero or more occurrence of the character.+ means one or more occurrence of the character."
},
{
"code": null,
"e": 813,
"s": 783,
"text": "Below is the implementation :"
},
{
"code": "# Python program that matches a word# containing ‘g’ followed by one or# more e’s using regex # import re packagesimport re # Function check if the any word of# the string containing 'g' followed# by one or more e'sdef check(string) : # Regex \\w * ge+\\w * will match # text that contains 'g', followed # by one or more 'e' regex = re.compile(\"ge+\\w*\") # The findall() method returns all # matching strings of the regex pattern match_object = regex.findall(string) # If length of match_object is not # equal to zero then it contains # matched string if len(match_object) != 0 : # looping through the list for word in match_object : print(word) else : print(\"No match\") # Driver Code if __name__ == '__main__' : # Enter the string string = \"Welcome to geeks for geeks\" # Calling check function check(string)",
"e": 1743,
"s": 813,
"text": null
},
{
"code": null,
"e": 1752,
"s": 1743,
"text": "Output :"
},
{
"code": null,
"e": 1764,
"s": 1752,
"text": "geeks\ngeeks"
},
{
"code": null,
"e": 1778,
"s": 1764,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 1800,
"s": 1778,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 1813,
"s": 1800,
"text": "python-regex"
},
{
"code": null,
"e": 1820,
"s": 1813,
"text": "Python"
},
{
"code": null,
"e": 1836,
"s": 1820,
"text": "Python Programs"
}
] |
Python – Replace delimiter | 10 Jul, 2020
Given List of Strings and replacing delimiter, replace current delimiter in each string.
Input : test_list = [“a, t”, “g, f, g”, “w, e”, “d, o”], repl_delim = ‘ ‘Output : [“a t”, “g f g”, “w e”, “d o”]Explanation : comma is replaced by empty spaces at each string.
Input : test_list = [“g#f#g”], repl_delim = ‘, ‘Output : [“g, f, g”]Explanation : hash is replaced by comma at each string.
Method #1 : Using replace() + loopThe combination of above functions provide a brute force method to solve this problem. In this, a loop is used to iterate through each string and perform replacement using replace().
# Python3 code to demonstrate working of # Replace delimiter# Using loop + replace() # initializing listtest_list = ["a, t", "g, f, g", "w, e", "d, o"] # printing original listprint("The original list is : " + str(test_list)) # initializing replace delimiterrepl_delim = '#' # Replace delimiterres = []for ele in test_list: # adding each string after replacement using replace() res.append(ele.replace(", ", repl_delim)) # printing result print("Replaced List : " + str(res))
The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']
Method #2 : Using list comprehension + replace()The combination of above functions can provide one liner to this problem. This is similar to above method, just encapsulated in list comprehension.
# Python3 code to demonstrate working of # Replace delimiter# Using list comprehension + replace() # initializing listtest_list = ["a, t", "g, f, g", "w, e", "d, o"] # printing original listprint("The original list is : " + str(test_list)) # initializing replace delimiterrepl_delim = '#' # Replace delimiter# iterating inside comprehension, performing replace using replace()res = [sub.replace(', ', repl_delim) for sub in test_list] # printing result print("Replaced List : " + str(res))
The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 117,
"s": 28,
"text": "Given List of Strings and replacing delimiter, replace current delimiter in each string."
},
{
"code": null,
"e": 293,
"s": 117,
"text": "Input : test_list = [“a, t”, “g, f, g”, “w, e”, “d, o”], repl_delim = ‘ ‘Output : [“a t”, “g f g”, “w e”, “d o”]Explanation : comma is replaced by empty spaces at each string."
},
{
"code": null,
"e": 417,
"s": 293,
"text": "Input : test_list = [“g#f#g”], repl_delim = ‘, ‘Output : [“g, f, g”]Explanation : hash is replaced by comma at each string."
},
{
"code": null,
"e": 634,
"s": 417,
"text": "Method #1 : Using replace() + loopThe combination of above functions provide a brute force method to solve this problem. In this, a loop is used to iterate through each string and perform replacement using replace()."
},
{
"code": "# Python3 code to demonstrate working of # Replace delimiter# Using loop + replace() # initializing listtest_list = [\"a, t\", \"g, f, g\", \"w, e\", \"d, o\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing replace delimiterrepl_delim = '#' # Replace delimiterres = []for ele in test_list: # adding each string after replacement using replace() res.append(ele.replace(\", \", repl_delim)) # printing result print(\"Replaced List : \" + str(res))",
"e": 1129,
"s": 634,
"text": null
},
{
"code": null,
"e": 1236,
"s": 1129,
"text": "The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']\nReplaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']\n"
},
{
"code": null,
"e": 1434,
"s": 1238,
"text": "Method #2 : Using list comprehension + replace()The combination of above functions can provide one liner to this problem. This is similar to above method, just encapsulated in list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Replace delimiter# Using list comprehension + replace() # initializing listtest_list = [\"a, t\", \"g, f, g\", \"w, e\", \"d, o\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing replace delimiterrepl_delim = '#' # Replace delimiter# iterating inside comprehension, performing replace using replace()res = [sub.replace(', ', repl_delim) for sub in test_list] # printing result print(\"Replaced List : \" + str(res))",
"e": 1930,
"s": 1434,
"text": null
},
{
"code": null,
"e": 2037,
"s": 1930,
"text": "The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']\nReplaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']\n"
},
{
"code": null,
"e": 2058,
"s": 2037,
"text": "Python list-programs"
},
{
"code": null,
"e": 2065,
"s": 2058,
"text": "Python"
},
{
"code": null,
"e": 2081,
"s": 2065,
"text": "Python Programs"
},
{
"code": null,
"e": 2179,
"s": 2081,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2221,
"s": 2179,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2243,
"s": 2221,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2269,
"s": 2243,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2301,
"s": 2269,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2330,
"s": 2301,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2352,
"s": 2330,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2391,
"s": 2352,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2429,
"s": 2391,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2478,
"s": 2429,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Evaluate the Mathematical Expressions using Tkinter in Python | 17 Feb, 2022
This article focuses on the evaluation of mathematical expression using the Tkinter and math packages in Python.
Tkinter: Python Tkinter is a GUI programming package or built-in package. Tkinter provides the Tk GUI toolkit with a potent object-oriented interface. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
Math module: In python, a variety of mathematical operations can be carried out with ease by importing a python module called “math” that specifies various functions, making our tasks simpler.
Importing the tkinter & math packages.
Create the main window.
Add number of widgets to the main window : Entry , Label.
Evaluating the expression.
Displaying message.
Apply the event trigger on the widgets.
PYTHON
# Importing tkinter module as tkimport tkinter as tk # Importing all functions/methods# from math modulefrom math import * # Import messagebox class from tkinterfrom tkinter import messagebox # function for evaluating the expressiondef eval_expression(event): result.configure(text = " Result: " + str(eval(entry.get()))) messagebox.showinfo("Evaluate Expression", "Successfully evaluated" ) # creating Tk windowroot = tk.Tk() # set geometry of root windowroot.geometry('300x150+600+200') # set the title of root windowroot.title('Evaluate Expression') # label and entry fieldinput_label = tk.Label(root, text = " Enter Your Expression:",).grid(row = 1)entry = tk.Entry(root) # bind 'enter' event to the# eval_expression() through# entry widgetentry.bind("
OUTPUT :
Evaluate expression GUI
Evaluate expression working
varshagumber28
punamsingh628700
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "This article focuses on the evaluation of mathematical expression using the Tkinter and math packages in Python. "
},
{
"code": null,
"e": 419,
"s": 142,
"text": "Tkinter: Python Tkinter is a GUI programming package or built-in package. Tkinter provides the Tk GUI toolkit with a potent object-oriented interface. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. "
},
{
"code": null,
"e": 613,
"s": 419,
"text": "Math module: In python, a variety of mathematical operations can be carried out with ease by importing a python module called “math” that specifies various functions, making our tasks simpler. "
},
{
"code": null,
"e": 653,
"s": 613,
"text": "Importing the tkinter & math packages."
},
{
"code": null,
"e": 677,
"s": 653,
"text": "Create the main window."
},
{
"code": null,
"e": 735,
"s": 677,
"text": "Add number of widgets to the main window : Entry , Label."
},
{
"code": null,
"e": 762,
"s": 735,
"text": "Evaluating the expression."
},
{
"code": null,
"e": 782,
"s": 762,
"text": "Displaying message."
},
{
"code": null,
"e": 822,
"s": 782,
"text": "Apply the event trigger on the widgets."
},
{
"code": null,
"e": 829,
"s": 822,
"text": "PYTHON"
},
{
"code": "# Importing tkinter module as tkimport tkinter as tk # Importing all functions/methods# from math modulefrom math import * # Import messagebox class from tkinterfrom tkinter import messagebox # function for evaluating the expressiondef eval_expression(event): result.configure(text = \" Result: \" + str(eval(entry.get()))) messagebox.showinfo(\"Evaluate Expression\", \"Successfully evaluated\" ) # creating Tk windowroot = tk.Tk() # set geometry of root windowroot.geometry('300x150+600+200') # set the title of root windowroot.title('Evaluate Expression') # label and entry fieldinput_label = tk.Label(root, text = \" Enter Your Expression:\",).grid(row = 1)entry = tk.Entry(root) # bind 'enter' event to the# eval_expression() through# entry widgetentry.bind(\"",
"e": 1662,
"s": 829,
"text": null
},
{
"code": null,
"e": 1671,
"s": 1662,
"text": "OUTPUT :"
},
{
"code": null,
"e": 1695,
"s": 1671,
"text": "Evaluate expression GUI"
},
{
"code": null,
"e": 1723,
"s": 1695,
"text": "Evaluate expression working"
},
{
"code": null,
"e": 1740,
"s": 1725,
"text": "varshagumber28"
},
{
"code": null,
"e": 1757,
"s": 1740,
"text": "punamsingh628700"
},
{
"code": null,
"e": 1782,
"s": 1757,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 1797,
"s": 1782,
"text": "Python-tkinter"
},
{
"code": null,
"e": 1804,
"s": 1797,
"text": "Python"
}
] |
set::emplace() in C++ STL | 23 Jan, 2018
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
This function is used to insert a new element into the set container, only if the element to be inserted is unique and does not already exists in the set.
Syntax :
setname.emplace(value)
Parameters :
The element to be inserted into the set
is passed as the parameter.
Result :
The parameter is added to the set if
the set does not contain that element already.
Examples:
Input : myset{1, 2, 3, 4, 5};
myset.emplace(6);
Output : myset = 1, 2, 3, 4, 5, 6
Input : myset{1, 2, 3, 4, 5};
myset.emplace(4);
Output : myset = 1, 2, 3, 4, 5
Errors and Exceptions1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown2. Parameter should be of the same type as that of the container otherwise, an error is thrown
// INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <set>using namespace std; int main(){ set<int> myset{}; myset.emplace(2); myset.emplace(6); myset.emplace(8); myset.emplace(9); myset.emplace(0); // set becomes 0, 2, 6, 8, 9 // adding unique element myset.emplace(5); // set becomes 0, 2, 5, 6, 8, 9 // adding element which already // exists there will be no // change in the set myset.emplace(2); // set remains 0, 2, 5, 6, 8, 9 // printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}
Output:
0 2 5 6 8 9
// STRING SET EXAMPLE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <set>#include <string>using namespace std; int main(){ set<string> myset{}; myset.emplace("This"); myset.emplace("is"); myset.emplace("a"); myset.emplace("computer science"); myset.emplace("portal"); // set becomes This, a, computer // science, is, portal // adding unique element myset.emplace("GeeksForGeeks"); // set becomes GeeksForGeeks, This, is, // a, computer science, portal // adding element which already exists // there will be no change in the set myset.emplace("is"); // set remains GeeksForGeeks, This, is, // a, computer science, portal // printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}
Output:
GeeksForGeeks This a computer science is portal
Time Complexity : O(logn)
ApplicationInput an empty multi set with the following numbers and order using emplace() function and find sum of elements.
Input : 7, 9, 4, 6, 2, 5, 3
Output : 36
// CPP program to illustrate// Application of emplace() function#include <iostream>#include <set>using namespace std; int main(){ // sum variable declaration int sum = 0; // set declaration set<int> myset{}; myset.emplace(7); myset.emplace(9); myset.emplace(4); myset.emplace(6); myset.emplace(2); myset.emplace(5); myset.emplace(3); // iterator declaration set<int>::iterator it; // finding sum of elements while (!myset.empty()) { it = myset.begin(); sum = sum + *it; myset.erase(it); } // printing the sum cout << sum; return 0;}
Output :
36
emplace() vs insertWhen we use insert, we create an object and then insert it into the multiset. With emplace(), the object is constructed in-place.
// C++ code to demonstrate difference between// emplace and insert#include<bits/stdc++.h>using namespace std; int main(){ // declaring set set<pair<char, int>> ms; // using emplace() to insert pair in-place ms.emplace('a', 24); // Below line would not compile // ms.insert('b', 25); // using emplace() to insert pair in-place ms.insert(make_pair('b', 25)); // printing the set for (auto it = ms.begin(); it != ms.end(); ++it) cout << " " << (*it).first << " " << (*it).second << endl; return 0;}
Output :
a 24
b 25
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jan, 2018"
},
{
"code": null,
"e": 332,
"s": 53,
"text": "Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element."
},
{
"code": null,
"e": 487,
"s": 332,
"text": "This function is used to insert a new element into the set container, only if the element to be inserted is unique and does not already exists in the set."
},
{
"code": null,
"e": 496,
"s": 487,
"text": "Syntax :"
},
{
"code": null,
"e": 695,
"s": 496,
"text": "setname.emplace(value)\nParameters :\nThe element to be inserted into the set\nis passed as the parameter.\nResult :\nThe parameter is added to the set if \nthe set does not contain that element already.\n"
},
{
"code": null,
"e": 705,
"s": 695,
"text": "Examples:"
},
{
"code": null,
"e": 888,
"s": 705,
"text": "Input : myset{1, 2, 3, 4, 5};\n myset.emplace(6);\nOutput : myset = 1, 2, 3, 4, 5, 6\n\nInput : myset{1, 2, 3, 4, 5};\n myset.emplace(4);\nOutput : myset = 1, 2, 3, 4, 5\n"
},
{
"code": null,
"e": 1100,
"s": 888,
"text": "Errors and Exceptions1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown2. Parameter should be of the same type as that of the container otherwise, an error is thrown"
},
{
"code": "// INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <set>using namespace std; int main(){ set<int> myset{}; myset.emplace(2); myset.emplace(6); myset.emplace(8); myset.emplace(9); myset.emplace(0); // set becomes 0, 2, 6, 8, 9 // adding unique element myset.emplace(5); // set becomes 0, 2, 5, 6, 8, 9 // adding element which already // exists there will be no // change in the set myset.emplace(2); // set remains 0, 2, 5, 6, 8, 9 // printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}",
"e": 1783,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1791,
"s": 1783,
"text": "Output:"
},
{
"code": null,
"e": 1804,
"s": 1791,
"text": "0 2 5 6 8 9\n"
},
{
"code": "// STRING SET EXAMPLE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <set>#include <string>using namespace std; int main(){ set<string> myset{}; myset.emplace(\"This\"); myset.emplace(\"is\"); myset.emplace(\"a\"); myset.emplace(\"computer science\"); myset.emplace(\"portal\"); // set becomes This, a, computer // science, is, portal // adding unique element myset.emplace(\"GeeksForGeeks\"); // set becomes GeeksForGeeks, This, is, // a, computer science, portal // adding element which already exists // there will be no change in the set myset.emplace(\"is\"); // set remains GeeksForGeeks, This, is, // a, computer science, portal // printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}",
"e": 2663,
"s": 1804,
"text": null
},
{
"code": null,
"e": 2671,
"s": 2663,
"text": "Output:"
},
{
"code": null,
"e": 2720,
"s": 2671,
"text": "GeeksForGeeks This a computer science is portal\n"
},
{
"code": null,
"e": 2746,
"s": 2720,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 2870,
"s": 2746,
"text": "ApplicationInput an empty multi set with the following numbers and order using emplace() function and find sum of elements."
},
{
"code": null,
"e": 2911,
"s": 2870,
"text": "Input : 7, 9, 4, 6, 2, 5, 3\nOutput : 36"
},
{
"code": "// CPP program to illustrate// Application of emplace() function#include <iostream>#include <set>using namespace std; int main(){ // sum variable declaration int sum = 0; // set declaration set<int> myset{}; myset.emplace(7); myset.emplace(9); myset.emplace(4); myset.emplace(6); myset.emplace(2); myset.emplace(5); myset.emplace(3); // iterator declaration set<int>::iterator it; // finding sum of elements while (!myset.empty()) { it = myset.begin(); sum = sum + *it; myset.erase(it); } // printing the sum cout << sum; return 0;}",
"e": 3531,
"s": 2911,
"text": null
},
{
"code": null,
"e": 3540,
"s": 3531,
"text": "Output :"
},
{
"code": null,
"e": 3544,
"s": 3540,
"text": "36\n"
},
{
"code": null,
"e": 3693,
"s": 3544,
"text": "emplace() vs insertWhen we use insert, we create an object and then insert it into the multiset. With emplace(), the object is constructed in-place."
},
{
"code": "// C++ code to demonstrate difference between// emplace and insert#include<bits/stdc++.h>using namespace std; int main(){ // declaring set set<pair<char, int>> ms; // using emplace() to insert pair in-place ms.emplace('a', 24); // Below line would not compile // ms.insert('b', 25); // using emplace() to insert pair in-place ms.insert(make_pair('b', 25)); // printing the set for (auto it = ms.begin(); it != ms.end(); ++it) cout << \" \" << (*it).first << \" \" << (*it).second << endl; return 0;}",
"e": 4277,
"s": 3693,
"text": null
},
{
"code": null,
"e": 4286,
"s": 4277,
"text": "Output :"
},
{
"code": null,
"e": 4299,
"s": 4286,
"text": " a 24\n b 25\n"
},
{
"code": null,
"e": 4307,
"s": 4299,
"text": "cpp-set"
},
{
"code": null,
"e": 4311,
"s": 4307,
"text": "STL"
},
{
"code": null,
"e": 4315,
"s": 4311,
"text": "C++"
},
{
"code": null,
"e": 4319,
"s": 4315,
"text": "STL"
},
{
"code": null,
"e": 4323,
"s": 4319,
"text": "CPP"
}
] |
How to Change the Tkinter Label Font Size? | 23 Dec, 2020
Tkinter Label is used to display one or more lines, it can also be used to display bitmap or images. In this article, we are going to change the font-size of the Label Widget. To create Label use following:
Syntax: label = Label(parent, option, ...)
Parameters:parent: Object of the widget that will display this label, generally a root objecttext: To display one or more lines of text.image: To display a static imagecompound: To display both Text and Image. It accepts TOP, BOTTOM, LEFT, RIGHT, CENTER. For example, if you write compound=TOPimage will displayed to the top of Text.
We can do this using different methods:
Method 1: By using Label’s font property.
Python3
# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.ttk import Label # Creating App class which will contain# Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text="I have default font-size").pack(pady=20) # Creating second label # This label has a font-family of Arial # and font-size of 25 Label(self.master, text="I have a font-size of 25", # Changing font-size here font=("Arial", 25) ).pack() if __name__ == "__main__": # Instantiating top level root = Tk() # Setting the title of the window root.title("Change font-size of Label") # Setting the geometry i.e Dimensions root.geometry("400x250") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()
Output:
Method 2: By using Style class. In this method, we will use our custom style otherwise all the Label widgets will get the same style.
Python3
# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.ttk import Label, Style # Creating App class which will contain# Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text="I have default font-size").pack(pady=20) # Instantiating Style class self.style = Style(self.master) # Configuring Custom Style # Name of the Style is "My.TLabel" self.style.configure("My.TLabel", font=('Arial', 25)) # Creating second label # This label has a font-family of Arial # and font-size of 25 Label( self.master, text="I have a font-size of 25", # Changing font-size using custom style style="My.TLabel").pack() if __name__ == "__main__": # Instantiating top level root = Tk() # Setting the title of the window root.title("Change font-size of Label") # Setting the geometry i.e Dimensions root.geometry("400x250") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()
Output:
Note: In the above method, TLabel is the name of the default style. So if you want to create your own style name then always use below syntax
my_style_name.default_style_name
Example:New.TButton # To override Button Widget’s stylesMy.TLabel # To override Label Widget’s StylesAbc.TEntry # To override Entry Widget’s Styles
If you use only the default style name then it will apply to all the corresponding widgets i.e if I use TLabel instead of My.TLabel then both the label will have font-size of 25. And importantly, if you use the default style name then you don’t need to provide style property.
Extra: Changing font size using the Default Style Name.
Python3
# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.ttk import Label, Style # Creating App class which will contain# Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text="I have default font-size").pack(pady=20) # Instantiating Style class self.style = Style(self.master) # Changing font-size of all the Label Widget self.style.configure("TLabel", font=('Arial', 25)) # Creating second label # This label has a font-family of Arial # and font-size of 25 Label(self.master, text="I have a font-size of 25").pack() if __name__ == "__main__": # Instantiating top level root = Tk() # Setting the title of the window root.title("Change font-size of Label") # Setting the geometry i.e Dimensions root.geometry("400x250") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()
Notice in the above program that we have not provided style or font property to any of the Label still both of them got the same font-size and same font-family.
Output:
Method 3: By using the Font class. In this method, we will create a Font object and then use this to change Font style of any widget. Benefit of this
Font class consist of following property:root: Object of toplevel widget.family: The font family name as a string.size: The font height as an integer in points.weight: ‘bold’/BOLD for boldface, ‘normal’/NORMAL for regular weight.slant: ‘italic’/ITALIC for italic, ‘roman’/ROMAN for unslanted.underline: 1/True/TRUE for underlined text, 0/False/FALSE for normal.overstrike: 1/True/TRUE for overstruck text, 0/False/FALSE for normal.
Python3
# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.font import BOLD, Fontfrom tkinter.ttk import Label # Creating App class which will contain Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text="I have default font-size").pack(pady=20) # Creating Font, with a "size of 25" and weight of BOLD self.bold25 = Font(self.master, size=25, weight=BOLD) # Creating second label # This label has a default font-family # and font-size of 25 Label(self.master, text="I have a font-size of 25", font=self.bold25).pack() if __name__ == "__main__": # Instantiating top level root = Tk() # Setting the title of the window root.title("Change font-size of Label") # Setting the geometry i.e Dimensions root.geometry("400x250") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()
Output:
Picked
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
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": "\n23 Dec, 2020"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "Tkinter Label is used to display one or more lines, it can also be used to display bitmap or images. In this article, we are going to change the font-size of the Label Widget. To create Label use following:"
},
{
"code": null,
"e": 278,
"s": 235,
"text": "Syntax: label = Label(parent, option, ...)"
},
{
"code": null,
"e": 612,
"s": 278,
"text": "Parameters:parent: Object of the widget that will display this label, generally a root objecttext: To display one or more lines of text.image: To display a static imagecompound: To display both Text and Image. It accepts TOP, BOTTOM, LEFT, RIGHT, CENTER. For example, if you write compound=TOPimage will displayed to the top of Text."
},
{
"code": null,
"e": 652,
"s": 612,
"text": "We can do this using different methods:"
},
{
"code": null,
"e": 694,
"s": 652,
"text": "Method 1: By using Label’s font property."
},
{
"code": null,
"e": 702,
"s": 694,
"text": "Python3"
},
{
"code": "# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.ttk import Label # Creating App class which will contain# Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text=\"I have default font-size\").pack(pady=20) # Creating second label # This label has a font-family of Arial # and font-size of 25 Label(self.master, text=\"I have a font-size of 25\", # Changing font-size here font=(\"Arial\", 25) ).pack() if __name__ == \"__main__\": # Instantiating top level root = Tk() # Setting the title of the window root.title(\"Change font-size of Label\") # Setting the geometry i.e Dimensions root.geometry(\"400x250\") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()",
"e": 1747,
"s": 702,
"text": null
},
{
"code": null,
"e": 1756,
"s": 1747,
"text": "Output: "
},
{
"code": null,
"e": 1890,
"s": 1756,
"text": "Method 2: By using Style class. In this method, we will use our custom style otherwise all the Label widgets will get the same style."
},
{
"code": null,
"e": 1898,
"s": 1890,
"text": "Python3"
},
{
"code": "# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.ttk import Label, Style # Creating App class which will contain# Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text=\"I have default font-size\").pack(pady=20) # Instantiating Style class self.style = Style(self.master) # Configuring Custom Style # Name of the Style is \"My.TLabel\" self.style.configure(\"My.TLabel\", font=('Arial', 25)) # Creating second label # This label has a font-family of Arial # and font-size of 25 Label( self.master, text=\"I have a font-size of 25\", # Changing font-size using custom style style=\"My.TLabel\").pack() if __name__ == \"__main__\": # Instantiating top level root = Tk() # Setting the title of the window root.title(\"Change font-size of Label\") # Setting the geometry i.e Dimensions root.geometry(\"400x250\") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()",
"e": 3170,
"s": 1898,
"text": null
},
{
"code": null,
"e": 3178,
"s": 3170,
"text": "Output:"
},
{
"code": null,
"e": 3320,
"s": 3178,
"text": "Note: In the above method, TLabel is the name of the default style. So if you want to create your own style name then always use below syntax"
},
{
"code": null,
"e": 3353,
"s": 3320,
"text": "my_style_name.default_style_name"
},
{
"code": null,
"e": 3507,
"s": 3353,
"text": "Example:New.TButton # To override Button Widget’s stylesMy.TLabel # To override Label Widget’s StylesAbc.TEntry # To override Entry Widget’s Styles"
},
{
"code": null,
"e": 3784,
"s": 3507,
"text": "If you use only the default style name then it will apply to all the corresponding widgets i.e if I use TLabel instead of My.TLabel then both the label will have font-size of 25. And importantly, if you use the default style name then you don’t need to provide style property."
},
{
"code": null,
"e": 3840,
"s": 3784,
"text": "Extra: Changing font size using the Default Style Name."
},
{
"code": null,
"e": 3848,
"s": 3840,
"text": "Python3"
},
{
"code": "# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.ttk import Label, Style # Creating App class which will contain# Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text=\"I have default font-size\").pack(pady=20) # Instantiating Style class self.style = Style(self.master) # Changing font-size of all the Label Widget self.style.configure(\"TLabel\", font=('Arial', 25)) # Creating second label # This label has a font-family of Arial # and font-size of 25 Label(self.master, text=\"I have a font-size of 25\").pack() if __name__ == \"__main__\": # Instantiating top level root = Tk() # Setting the title of the window root.title(\"Change font-size of Label\") # Setting the geometry i.e Dimensions root.geometry(\"400x250\") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()",
"e": 4987,
"s": 3848,
"text": null
},
{
"code": null,
"e": 5148,
"s": 4987,
"text": "Notice in the above program that we have not provided style or font property to any of the Label still both of them got the same font-size and same font-family."
},
{
"code": null,
"e": 5156,
"s": 5148,
"text": "Output:"
},
{
"code": null,
"e": 5306,
"s": 5156,
"text": "Method 3: By using the Font class. In this method, we will create a Font object and then use this to change Font style of any widget. Benefit of this"
},
{
"code": null,
"e": 5738,
"s": 5306,
"text": "Font class consist of following property:root: Object of toplevel widget.family: The font family name as a string.size: The font height as an integer in points.weight: ‘bold’/BOLD for boldface, ‘normal’/NORMAL for regular weight.slant: ‘italic’/ITALIC for italic, ‘roman’/ROMAN for unslanted.underline: 1/True/TRUE for underlined text, 0/False/FALSE for normal.overstrike: 1/True/TRUE for overstruck text, 0/False/FALSE for normal."
},
{
"code": null,
"e": 5746,
"s": 5738,
"text": "Python3"
},
{
"code": "# importing tkinter module and Widgetsfrom tkinter import Tkfrom tkinter.font import BOLD, Fontfrom tkinter.ttk import Label # Creating App class which will contain Label Widgetsclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating first Label i.e with default font-size Label(self.master, text=\"I have default font-size\").pack(pady=20) # Creating Font, with a \"size of 25\" and weight of BOLD self.bold25 = Font(self.master, size=25, weight=BOLD) # Creating second label # This label has a default font-family # and font-size of 25 Label(self.master, text=\"I have a font-size of 25\", font=self.bold25).pack() if __name__ == \"__main__\": # Instantiating top level root = Tk() # Setting the title of the window root.title(\"Change font-size of Label\") # Setting the geometry i.e Dimensions root.geometry(\"400x250\") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()",
"e": 6880,
"s": 5746,
"text": null
},
{
"code": null,
"e": 6888,
"s": 6880,
"text": "Output:"
},
{
"code": null,
"e": 6895,
"s": 6888,
"text": "Picked"
},
{
"code": null,
"e": 6910,
"s": 6895,
"text": "Python-tkinter"
},
{
"code": null,
"e": 6934,
"s": 6910,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6941,
"s": 6934,
"text": "Python"
},
{
"code": null,
"e": 6960,
"s": 6941,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7058,
"s": 6960,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7076,
"s": 7058,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7118,
"s": 7076,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7140,
"s": 7118,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7175,
"s": 7140,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7201,
"s": 7175,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7233,
"s": 7201,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7262,
"s": 7233,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 7289,
"s": 7262,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7319,
"s": 7289,
"text": "Iterate over a list in Python"
}
] |
Performing DataBase Operations in XAMPP | 26 Nov, 2020
XAMPP is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is open-source. It has an Apache HTTP Server, MariaDB, and interpreter for 11 different programming languages like Perl and PHP. XAMPP Stands for cross-platform, Apache, MySQL, PHP, and Perl.
It allows you to build a website on a local web server on your computer.
Stores data locally
In this article, we are going to perform Database operations like Create, Insert, Update, Delete data from the database created in XAMPP localhost server. We are also going to create a table and then start performing database operations. Following are the list of database operations with their respective syntax:
It is used to display all the details from the table.
Syntax: SELECT * FROM 'table_name'
It is used to insert data into the table.
Syntax: INSERT INTO `table_name`(`col`, `col2`, `col3`,.. `coln`) VALUES ([value-1],[value-2],
[value-3],....,[value-n)
It is used to change/update any data in the table.
Syntax: UPDATE `table_name` SET `col1`=[value-1],
`col2`=[value-2],
`col3`=[value-3],
`coln`=[value-n] WHERE 1
It is used to delete data from a table.
Syntax: DELETE FROM table_name where col="value"
Follow the below steps to perform database operations on XAMPP:
Start XAMPP Server
Create Database and Create Table
Perform Database Operations
Verify Resultant Table
1. Start XAMPP server
2. Go to Browser and type “http://localhost/phpmyadmin” and Create a database with the name “Vignan” by selecting new
3. After that, Create table Name “ITDept” and give the number of columns (I created 4 columns) and click on Go
Give column names as “Rollno”(Varchar), “Name”(Varchar), “Gender” (Char), “Address”(Varchar), and Save.
Note: Clicking the “Save” option is important, if not the table is not created.
Then we get the output as:
INSERT Operation:
Click on SQL
Click on INSERT Option
By default, code is available like this:
INSERT INTO `itdept`(`Rollno`, `Name`, `Gender`, `Address`)
VALUES ([value-1],[value-2],[value-3],[value-4])
We want to modify the values as follows and click on “GO”
INSERT INTO `itdept`(`Rollno`, `Name`, `Gender`, `Address`)
VALUES ("171FA07058","Sravan Kumar Gottumukkala", "m", "HYD" )
Output:
Now insert 5 records. Data in the database is as follows:
UPDATE Operation:
Default code in the update is:
UPDATE `itdept` SET `Rollno`=[value-1],
`Name`=[value-2],
`Gender`=[value-3],
`Address`=[value-4] WHERE 1
Now change the name to Sujatha where rollno is 171FA07078 as follows:
UPDATE `itdept` SET NAME="Sujitha" WHERE `Rollno`="171FA07078"
Output:
SELECT Operation:
The Select statement is used to display or query for data from the database. Follow the below steps to do so:
Click on the Select* option
This will result in the following code generation:
SELECT * FROM `itdept`
Output:
For Selecting particular data follow the below sample query:
Select Rollno, Name from itept
DELETE Operation:
Click on the Delete button to delete the data as shown below:
The generated code would look like below:
DELETE FROM itdept where Rollno="171FA07058"
Confirm the deletion by clicking YES
Output:
Our Final data in Table is:
DBMS-SQL
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
Difference between OLAP and OLTP in DBMS
Difference between Where and Having Clause in SQL
SQL | DDL, DML, TCL and DCL
Introduction of Relational Algebra in DBMS
Relational Model in DBMS
KDD Process in Data Mining
Difference between Star Schema and Snowflake Schema | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 360,
"s": 28,
"text": "XAMPP is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is open-source. It has an Apache HTTP Server, MariaDB, and interpreter for 11 different programming languages like Perl and PHP. XAMPP Stands for cross-platform, Apache, MySQL, PHP, and Perl."
},
{
"code": null,
"e": 433,
"s": 360,
"text": "It allows you to build a website on a local web server on your computer."
},
{
"code": null,
"e": 453,
"s": 433,
"text": "Stores data locally"
},
{
"code": null,
"e": 767,
"s": 453,
"text": "In this article, we are going to perform Database operations like Create, Insert, Update, Delete data from the database created in XAMPP localhost server. We are also going to create a table and then start performing database operations. Following are the list of database operations with their respective syntax:"
},
{
"code": null,
"e": 821,
"s": 767,
"text": "It is used to display all the details from the table."
},
{
"code": null,
"e": 856,
"s": 821,
"text": "Syntax: SELECT * FROM 'table_name'"
},
{
"code": null,
"e": 898,
"s": 856,
"text": "It is used to insert data into the table."
},
{
"code": null,
"e": 1022,
"s": 898,
"text": "Syntax: INSERT INTO `table_name`(`col`, `col2`, `col3`,.. `coln`) VALUES ([value-1],[value-2],\n [value-3],....,[value-n)"
},
{
"code": null,
"e": 1073,
"s": 1022,
"text": "It is used to change/update any data in the table."
},
{
"code": null,
"e": 1187,
"s": 1073,
"text": "Syntax: UPDATE `table_name` SET `col1`=[value-1],\n `col2`=[value-2],\n `col3`=[value-3],\n `coln`=[value-n] WHERE 1"
},
{
"code": null,
"e": 1227,
"s": 1187,
"text": "It is used to delete data from a table."
},
{
"code": null,
"e": 1276,
"s": 1227,
"text": "Syntax: DELETE FROM table_name where col=\"value\""
},
{
"code": null,
"e": 1340,
"s": 1276,
"text": "Follow the below steps to perform database operations on XAMPP:"
},
{
"code": null,
"e": 1359,
"s": 1340,
"text": "Start XAMPP Server"
},
{
"code": null,
"e": 1392,
"s": 1359,
"text": "Create Database and Create Table"
},
{
"code": null,
"e": 1420,
"s": 1392,
"text": "Perform Database Operations"
},
{
"code": null,
"e": 1443,
"s": 1420,
"text": "Verify Resultant Table"
},
{
"code": null,
"e": 1465,
"s": 1443,
"text": "1. Start XAMPP server"
},
{
"code": null,
"e": 1583,
"s": 1465,
"text": "2. Go to Browser and type “http://localhost/phpmyadmin” and Create a database with the name “Vignan” by selecting new"
},
{
"code": null,
"e": 1695,
"s": 1583,
"text": "3. After that, Create table Name “ITDept” and give the number of columns (I created 4 columns) and click on Go"
},
{
"code": null,
"e": 1799,
"s": 1695,
"text": "Give column names as “Rollno”(Varchar), “Name”(Varchar), “Gender” (Char), “Address”(Varchar), and Save."
},
{
"code": null,
"e": 1879,
"s": 1799,
"text": "Note: Clicking the “Save” option is important, if not the table is not created."
},
{
"code": null,
"e": 1906,
"s": 1879,
"text": "Then we get the output as:"
},
{
"code": null,
"e": 1924,
"s": 1906,
"text": "INSERT Operation:"
},
{
"code": null,
"e": 1937,
"s": 1924,
"text": "Click on SQL"
},
{
"code": null,
"e": 1960,
"s": 1937,
"text": "Click on INSERT Option"
},
{
"code": null,
"e": 2001,
"s": 1960,
"text": "By default, code is available like this:"
},
{
"code": null,
"e": 2110,
"s": 2001,
"text": "INSERT INTO `itdept`(`Rollno`, `Name`, `Gender`, `Address`)\nVALUES ([value-1],[value-2],[value-3],[value-4])"
},
{
"code": null,
"e": 2169,
"s": 2110,
"text": "We want to modify the values as follows and click on “GO”"
},
{
"code": null,
"e": 2293,
"s": 2169,
"text": "INSERT INTO `itdept`(`Rollno`, `Name`, `Gender`, `Address`)\n VALUES (\"171FA07058\",\"Sravan Kumar Gottumukkala\", \"m\", \"HYD\" )"
},
{
"code": null,
"e": 2301,
"s": 2293,
"text": "Output:"
},
{
"code": null,
"e": 2359,
"s": 2301,
"text": "Now insert 5 records. Data in the database is as follows:"
},
{
"code": null,
"e": 2377,
"s": 2359,
"text": "UPDATE Operation:"
},
{
"code": null,
"e": 2408,
"s": 2377,
"text": "Default code in the update is:"
},
{
"code": null,
"e": 2514,
"s": 2408,
"text": "UPDATE `itdept` SET `Rollno`=[value-1],\n`Name`=[value-2],\n`Gender`=[value-3],\n`Address`=[value-4] WHERE 1"
},
{
"code": null,
"e": 2584,
"s": 2514,
"text": "Now change the name to Sujatha where rollno is 171FA07078 as follows:"
},
{
"code": null,
"e": 2647,
"s": 2584,
"text": "UPDATE `itdept` SET NAME=\"Sujitha\" WHERE `Rollno`=\"171FA07078\""
},
{
"code": null,
"e": 2655,
"s": 2647,
"text": "Output:"
},
{
"code": null,
"e": 2673,
"s": 2655,
"text": "SELECT Operation:"
},
{
"code": null,
"e": 2783,
"s": 2673,
"text": "The Select statement is used to display or query for data from the database. Follow the below steps to do so:"
},
{
"code": null,
"e": 2811,
"s": 2783,
"text": "Click on the Select* option"
},
{
"code": null,
"e": 2862,
"s": 2811,
"text": "This will result in the following code generation:"
},
{
"code": null,
"e": 2886,
"s": 2862,
"text": "SELECT * FROM `itdept` "
},
{
"code": null,
"e": 2894,
"s": 2886,
"text": "Output:"
},
{
"code": null,
"e": 2955,
"s": 2894,
"text": "For Selecting particular data follow the below sample query:"
},
{
"code": null,
"e": 2986,
"s": 2955,
"text": "Select Rollno, Name from itept"
},
{
"code": null,
"e": 3004,
"s": 2986,
"text": "DELETE Operation:"
},
{
"code": null,
"e": 3067,
"s": 3004,
"text": "Click on the Delete button to delete the data as shown below:"
},
{
"code": null,
"e": 3109,
"s": 3067,
"text": "The generated code would look like below:"
},
{
"code": null,
"e": 3154,
"s": 3109,
"text": "DELETE FROM itdept where Rollno=\"171FA07058\""
},
{
"code": null,
"e": 3191,
"s": 3154,
"text": "Confirm the deletion by clicking YES"
},
{
"code": null,
"e": 3199,
"s": 3191,
"text": "Output:"
},
{
"code": null,
"e": 3227,
"s": 3199,
"text": "Our Final data in Table is:"
},
{
"code": null,
"e": 3236,
"s": 3227,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 3241,
"s": 3236,
"text": "DBMS"
},
{
"code": null,
"e": 3246,
"s": 3241,
"text": "DBMS"
},
{
"code": null,
"e": 3344,
"s": 3246,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3385,
"s": 3344,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 3422,
"s": 3385,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 3454,
"s": 3422,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 3495,
"s": 3454,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 3545,
"s": 3495,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 3573,
"s": 3545,
"text": "SQL | DDL, DML, TCL and DCL"
},
{
"code": null,
"e": 3616,
"s": 3573,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 3641,
"s": 3616,
"text": "Relational Model in DBMS"
},
{
"code": null,
"e": 3668,
"s": 3641,
"text": "KDD Process in Data Mining"
}
] |
Program for Sum of the digits of a given number | 10 Jun, 2022
Given a number, find sum of its digits.
Examples :
Input : n = 687
Output : 21
Input : n = 12
Output : 3
General Algorithm for sum of digits in a given number:
Get the numberDeclare a variable to store the sum and set it to 0Repeat the next two steps till the number is not 0Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.Print or return the sum
Get the number
Declare a variable to store the sum and set it to 0
Repeat the next two steps till the number is not 0
Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.
Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
Print or return the sum
Below are the solutions to get sum of the digits. 1. Iterative:
C++
C
Java
Python3
C#
PHP
Javascript
// C program to compute sum of digits in// number.#include <iostream>using namespace std; /* Function to get sum of digits */class gfg {public: int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; }}; // Driver codeint main(){ gfg g; int n = 687; cout << g.getSum(n); return 0;}// This code is contributed by Soumik
// C program to compute sum of digits in// number.#include <stdio.h> /* Function to get sum of digits */int getSum(int n){ int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum;} // Driver codeint main(){ int n = 687; printf(" %d ", getSum(n)); return 0;}
// Java program to compute// sum of digits in number.import java.io.*; class GFG { /* Function to get sum of digits */ static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } // Driver code public static void main(String[] args) { int n = 687; System.out.println(getSum(n)); }} // This code is contributed by Gitanjali
# Python 3 program to# compute sum of digits in# number. # Function to get sum of digits def getSum(n): sum = 0 while (n != 0): sum = sum + int(n % 10) n = int(n/10) return sum # Driver coden = 687print(getSum(n))
// C# program to compute// sum of digits in number.using System; class GFG { /* Function to get sum of digits */ static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } // Driver code public static void Main() { int n = 687; Console.Write(getSum(n)); }} // This code is contributed by Sam007
<?php// PHP Code to compute sum// of digits in number. // Function to get// $sum of digitsfunction getsum($n){ $sum = 0; while ($n != 0) { $sum = $sum + $n % 10; $n = $n/10; } return $sum;} // Driver Code$n = 687;$res = getsum($n);echo("$res"); // This code is contributed by// Smitha Dinesh Semwal.?>
<script> // Javascript program to compute sum of digits in// number. /* Function to get sum of digits */function getSum(n){ var sum = 0; while (n != 0) { sum = sum + n % 10; n = parseInt(n / 10); } return sum;} // Driver codevar n = 687;document.write(getSum(n)); </script>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
21
Time Complexity : O(logn)
Auxiliary Space: O(1)
How to compute in a single line? The below function has three lines instead of one line, but it calculates the sum in line. It can be made one-line function if we pass the pointer to sum.
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; /* Function to get sum of digits */class gfg {public: int getSum(int n) { int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; }}; // Driver codeint main(){ gfg g; int n = 687; cout << g.getSum(n); return 0;}// This code is contributed by Soumik
#include <stdio.h> /* Function to get sum of digits */int getSum(int n){ int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum;} // Driver codeint main(){ int n = 687; printf(" %d ", getSum(n)); return 0;}
// Java program to compute// sum of digits in number.import java.io.*; class GFG { /* Function to get sum of digits */ static int getSum(int n) { int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } // Driver code public static void main(String[] args) { int n = 687; System.out.println(getSum(n)); }} // This code is contributed by Gitanjali
# Function to get sum of digits def getSum(n): sum = 0 # Single line that calculates sum while(n > 0): sum += int(n % 10) n = int(n/10) return sum # Driver coden = 687print(getSum(n)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to compute// sum of digits in number.using System; class GFG { static int getSum(int n) { int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } // Driver code public static void Main() { int n = 687; Console.Write(getSum(n)); }} // This code is contributed by Sam007
<?php// PHP Code for Sum the// digits of a given number // Function to get sum of digitsfunction getsum($n){ // Single line that calculates $sum for ($sum = 0; $n > 0; $sum += $n % 10, $n /= 10); return $sum;} // Driver Code$n = 687;echo(getsum($n)); // This code is contributed by// Smitha Dinesh Semwal.?>
<script> // Javascript program to compute// sum of digits in number. // Function to get sum of digitsfunction getSum(n){ let sum; // Single line that calculates sum for(sum = 0; n > 0; sum += n % 10, n = parseInt(n / 10)) ; return sum;} // Driver codelet n = 687; document.write(getSum(n)); // This code is contributed by subhammahato348 </script>
21
Time Complexity : O(logn)
Auxiliary Space: O(1)
2. Recursive Thanks to Ayesha for providing the below recursive solution.
Algorithm :
1) Get the number
2) Get the remainder and pass the next remaining digits
3) Get the rightmost digit of the number with help of the remainder '%' operator by dividing it by 10 and add it to sum.
Divide the number by 10 with help of '/' operator to remove the rightmost digit.
4) Check the base case with n = 0
5) Print or return the sum
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to compute// sum of digits in number.#include <iostream>using namespace std;class gfg {public: int sumDigits(int no) { if(no == 0){ return 0 ; } return (no % 10) + sumDigits(no / 10) ; }}; // Driver codeint main(void){ gfg g; cout << g.sumDigits(687); return 0;}
// C program to compute// sum of digits in number.#include <stdio.h> int sumDigits(int no){ if(no == 0){ return 0 ; } return (no % 10) + sumDigits(no / 10) ;} int main(){ printf("%d", sumDigits(687)); return 0;}
// Java program to compute// sum of digits in number.import java.io.*; class GFG { /* Function to get sum of digits */ static int sumDigits(int no) { if(no == 0){ return 0 ; } return (no % 10) + sumDigits(no / 10) ; } // Driver code public static void main(String[] args) { System.out.println(sumDigits(687)); }} // This code is contributed by Gitanjali
# Python program to compute# sum of digits in number. def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no/10)) # Driver codeprint(sumDigits(687)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to compute// sum of digits in number.using System; class GFG { /* Function to get sum of digits */ static int sumDigits(int no) { return no == 0 ? 0 : no % 10 + sumDigits(no / 10); } // Driver code public static void Main() { Console.Write(sumDigits(687)); }} // This code is contributed by Sam007
<?php// PHP program to compute// sum of digits in number.function sumDigits($no){return $no == 0 ? 0 : $no % 10 + sumDigits($no / 10) ;} // Driver Codeecho sumDigits(687); // This code is contributed by aj_36?>
<script>// Program to compute// sum of digits in number // Function to get sum of digits function sumDigits(no) { if(no == 0){ return 0 ; } return (no % 10) + sumDigits(parseInt(no/10)) ; } // Driver code document.write(sumDigits(687)); // This is code is contributed by simranarora5sos</script>
21
Time Complexity : O(logn)
Auxiliary Space: O(logn)
3.Taking input as String
When the number of digits of that number exceeds 1019 , we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric)
Below is the implementation of the above approach
C++14
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <iostream>using namespace std;int getSum(string str){ int sum = 0; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + str[i] - 48; } return sum;} // Driver Codeint main(){ string st = "123456789123456789123422"; cout << getSum(st); return 0;}
// Java implementation of the above approachimport java.io.*;class GFG { static int getSum(String str) { int sum = 0; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + str.charAt(i) - 48; } return sum; } // Driver Code public static void main(String[] args) { String st = "123456789123456789123422"; System.out.print(getSum(st)); }} // This code is contributed by Dharanendra L V.
# Python implementation of the above approachdef getSum(n): # Initializing sum to 0 sum = 0 # Traversing through string for i in n: # Converting char to int sum = sum + int(i) return sum n = "123456789123456789123422"print(getSum(n))
// C# implementation of the above approachusing System;public class GFG { static int getSum(String str) { int sum = 0; // Traversing through the string for (int i = 0; i < str.Length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + str[i] - 48; } return sum; } // Driver Code static public void Main() { String st = "123456789123456789123422"; Console.Write(getSum(st)); }} // This code is contributed by Dharanendra L V.
<script>// Javascript implementation of the above approach function getSum(str){ let sum = 0; // Traversing through the string for (let i = 0; i < str.length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + parseInt(str[i]); } return sum;} // Driver Codelet st = "123456789123456789123422";document.write(getSum(st)); // This code is contributed by subhammahato348.</script>
104
Time Complexity : O(logn)
Auxiliary Space: O(1)
4. Using Tail Recursion
This problem can also be solved using Tail Recursion. Here is an approach to solving it.
1. Add another variable “Val” to the function and initialize it to ( val = 0 )
2. On every call to the function add the mod value (n%10) to the variable as “(n%10)+val” which is the last digit in n. Along with pass the variable n as n/10.
3. So on the First call it will have the last digit. As we are passing n/10 as n, It follows until n is reduced to a single digit.
4. n<10 is the base case so When n < 10, then add the n to the variable as it is the last digit and return the val which will have the sum of digits
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to check sum// of digit using tail recursionint sum_of_digit(int n, int val){ if (n < 10) { val = val + n; return val; } return sum_of_digit(n / 10, (n % 10) + val);} // Driver codeint main(){ int num = 12345; int result = sum_of_digit(num, 0); cout << "Sum of digits is " << result; return 0;} // This code is contributed by subhammahato348
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class sum_of_digits { // Function to check sum // of digit using tail recursion static int sum_of_digit(int n, int val) { if (n < 10) { val = val + n; return val; } return sum_of_digit(n / 10, (n % 10) + val); } // Driven Program to check above public static void main(String args[]) { int num = 12345; int result = sum_of_digit(num, 0); System.out.println("Sum of digits is " + result); }}
# Python3 program for the above approach # Function to check sum# of digit using tail recursiondef sum_of_digit(n, val): if (n < 10): val = val + n return val return sum_of_digit(n // 10, (n % 10) + val) # Driver codenum = 12345result = sum_of_digit(num, 0) print("Sum of digits is", result) # This code is contributed by subhammahato348
// C# program for the above approachusing System; class GFG{ // Function to check sum// of digit using tail recursionstatic int sum_of_digit(int n, int val){ if (n < 10) { val = val + n; return val; } return sum_of_digit(n / 10, (n % 10) + val);} // Driver codepublic static void Main(){ int num = 12345; int result = sum_of_digit(num, 0); Console.Write("Sum of digits is " + result);}} // This code is contributed by subhammahato348
<script> // Javascript program for the above approach // Function to check sum// of digit using tail recursionfunction sum_of_digit(n, val){ if (n < 10) { val = val + n; return val; } return sum_of_digit(parseInt(n / 10), (n % 10) + val);} // Driver code let num = 12345; let result = sum_of_digit(num, 0); document.write("Sum of digits is " + result); // This code is contributed by subhammahato348 </script>
Sum of digits is 15
Time Complexity : O(logn)
Auxiliary Space: O(logn)
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
jit_t
SoumikMondal
RishabhPrabhu
vikkycirus
dharanendralv23
SatheeshKumarMR
gauravl3hardwaj
rutvik_56
subhammahato348
simranarora5sos
ruhelaa48
prasanna1995
susobhanakhuli
helderdacosta
cpp-puzzle
number-digits
C Language
C++
Recursion
Recursion
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
std::sort() in C++ STL
Bitwise Operators in C/C++
Arrays in C/C++
Substring in C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 92,
"s": 52,
"text": "Given a number, find sum of its digits."
},
{
"code": null,
"e": 104,
"s": 92,
"text": "Examples : "
},
{
"code": null,
"e": 159,
"s": 104,
"text": "Input : n = 687\nOutput : 21\n\nInput : n = 12\nOutput : 3"
},
{
"code": null,
"e": 215,
"s": 159,
"text": "General Algorithm for sum of digits in a given number: "
},
{
"code": null,
"e": 551,
"s": 215,
"text": "Get the numberDeclare a variable to store the sum and set it to 0Repeat the next two steps till the number is not 0Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.Print or return the sum"
},
{
"code": null,
"e": 566,
"s": 551,
"text": "Get the number"
},
{
"code": null,
"e": 618,
"s": 566,
"text": "Declare a variable to store the sum and set it to 0"
},
{
"code": null,
"e": 669,
"s": 618,
"text": "Repeat the next two steps till the number is not 0"
},
{
"code": null,
"e": 787,
"s": 669,
"text": "Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum."
},
{
"code": null,
"e": 868,
"s": 787,
"text": "Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit."
},
{
"code": null,
"e": 892,
"s": 868,
"text": "Print or return the sum"
},
{
"code": null,
"e": 956,
"s": 892,
"text": "Below are the solutions to get sum of the digits. 1. Iterative:"
},
{
"code": null,
"e": 960,
"s": 956,
"text": "C++"
},
{
"code": null,
"e": 962,
"s": 960,
"text": "C"
},
{
"code": null,
"e": 967,
"s": 962,
"text": "Java"
},
{
"code": null,
"e": 975,
"s": 967,
"text": "Python3"
},
{
"code": null,
"e": 978,
"s": 975,
"text": "C#"
},
{
"code": null,
"e": 982,
"s": 978,
"text": "PHP"
},
{
"code": null,
"e": 993,
"s": 982,
"text": "Javascript"
},
{
"code": "// C program to compute sum of digits in// number.#include <iostream>using namespace std; /* Function to get sum of digits */class gfg {public: int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; }}; // Driver codeint main(){ gfg g; int n = 687; cout << g.getSum(n); return 0;}// This code is contributed by Soumik",
"e": 1423,
"s": 993,
"text": null
},
{
"code": "// C program to compute sum of digits in// number.#include <stdio.h> /* Function to get sum of digits */int getSum(int n){ int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum;} // Driver codeint main(){ int n = 687; printf(\" %d \", getSum(n)); return 0;}",
"e": 1735,
"s": 1423,
"text": null
},
{
"code": "// Java program to compute// sum of digits in number.import java.io.*; class GFG { /* Function to get sum of digits */ static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } // Driver code public static void main(String[] args) { int n = 687; System.out.println(getSum(n)); }} // This code is contributed by Gitanjali",
"e": 2196,
"s": 1735,
"text": null
},
{
"code": "# Python 3 program to# compute sum of digits in# number. # Function to get sum of digits def getSum(n): sum = 0 while (n != 0): sum = sum + int(n % 10) n = int(n/10) return sum # Driver coden = 687print(getSum(n))",
"e": 2438,
"s": 2196,
"text": null
},
{
"code": "// C# program to compute// sum of digits in number.using System; class GFG { /* Function to get sum of digits */ static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } // Driver code public static void Main() { int n = 687; Console.Write(getSum(n)); }} // This code is contributed by Sam007",
"e": 2870,
"s": 2438,
"text": null
},
{
"code": "<?php// PHP Code to compute sum// of digits in number. // Function to get// $sum of digitsfunction getsum($n){ $sum = 0; while ($n != 0) { $sum = $sum + $n % 10; $n = $n/10; } return $sum;} // Driver Code$n = 687;$res = getsum($n);echo(\"$res\"); // This code is contributed by// Smitha Dinesh Semwal.?>",
"e": 3201,
"s": 2870,
"text": null
},
{
"code": "<script> // Javascript program to compute sum of digits in// number. /* Function to get sum of digits */function getSum(n){ var sum = 0; while (n != 0) { sum = sum + n % 10; n = parseInt(n / 10); } return sum;} // Driver codevar n = 687;document.write(getSum(n)); </script>",
"e": 3501,
"s": 3201,
"text": null
},
{
"code": null,
"e": 3510,
"s": 3501,
"text": "Chapters"
},
{
"code": null,
"e": 3537,
"s": 3510,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 3587,
"s": 3537,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 3610,
"s": 3587,
"text": "captions off, selected"
},
{
"code": null,
"e": 3618,
"s": 3610,
"text": "English"
},
{
"code": null,
"e": 3642,
"s": 3618,
"text": "This is a modal window."
},
{
"code": null,
"e": 3711,
"s": 3642,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 3733,
"s": 3711,
"text": "End of dialog window."
},
{
"code": null,
"e": 3736,
"s": 3733,
"text": "21"
},
{
"code": null,
"e": 3762,
"s": 3736,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 3784,
"s": 3762,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3973,
"s": 3784,
"text": "How to compute in a single line? The below function has three lines instead of one line, but it calculates the sum in line. It can be made one-line function if we pass the pointer to sum. "
},
{
"code": null,
"e": 3977,
"s": 3973,
"text": "C++"
},
{
"code": null,
"e": 3979,
"s": 3977,
"text": "C"
},
{
"code": null,
"e": 3984,
"s": 3979,
"text": "Java"
},
{
"code": null,
"e": 3992,
"s": 3984,
"text": "Python3"
},
{
"code": null,
"e": 3995,
"s": 3992,
"text": "C#"
},
{
"code": null,
"e": 3999,
"s": 3995,
"text": "PHP"
},
{
"code": null,
"e": 4010,
"s": 3999,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; /* Function to get sum of digits */class gfg {public: int getSum(int n) { int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; }}; // Driver codeint main(){ gfg g; int n = 687; cout << g.getSum(n); return 0;}// This code is contributed by Soumik",
"e": 4411,
"s": 4010,
"text": null
},
{
"code": "#include <stdio.h> /* Function to get sum of digits */int getSum(int n){ int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum;} // Driver codeint main(){ int n = 687; printf(\" %d \", getSum(n)); return 0;}",
"e": 4698,
"s": 4411,
"text": null
},
{
"code": "// Java program to compute// sum of digits in number.import java.io.*; class GFG { /* Function to get sum of digits */ static int getSum(int n) { int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } // Driver code public static void main(String[] args) { int n = 687; System.out.println(getSum(n)); }} // This code is contributed by Gitanjali",
"e": 5178,
"s": 4698,
"text": null
},
{
"code": "# Function to get sum of digits def getSum(n): sum = 0 # Single line that calculates sum while(n > 0): sum += int(n % 10) n = int(n/10) return sum # Driver coden = 687print(getSum(n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 5445,
"s": 5178,
"text": null
},
{
"code": "// C# program to compute// sum of digits in number.using System; class GFG { static int getSum(int n) { int sum; /* Single line that calculates sum */ for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } // Driver code public static void Main() { int n = 687; Console.Write(getSum(n)); }} // This code is contributed by Sam007",
"e": 5857,
"s": 5445,
"text": null
},
{
"code": "<?php// PHP Code for Sum the// digits of a given number // Function to get sum of digitsfunction getsum($n){ // Single line that calculates $sum for ($sum = 0; $n > 0; $sum += $n % 10, $n /= 10); return $sum;} // Driver Code$n = 687;echo(getsum($n)); // This code is contributed by// Smitha Dinesh Semwal.?>",
"e": 6208,
"s": 5857,
"text": null
},
{
"code": "<script> // Javascript program to compute// sum of digits in number. // Function to get sum of digitsfunction getSum(n){ let sum; // Single line that calculates sum for(sum = 0; n > 0; sum += n % 10, n = parseInt(n / 10)) ; return sum;} // Driver codelet n = 687; document.write(getSum(n)); // This code is contributed by subhammahato348 </script>",
"e": 6590,
"s": 6208,
"text": null
},
{
"code": null,
"e": 6593,
"s": 6590,
"text": "21"
},
{
"code": null,
"e": 6619,
"s": 6593,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 6641,
"s": 6619,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6716,
"s": 6641,
"text": "2. Recursive Thanks to Ayesha for providing the below recursive solution. "
},
{
"code": null,
"e": 6728,
"s": 6716,
"text": "Algorithm :"
},
{
"code": null,
"e": 7068,
"s": 6728,
"text": "1) Get the number\n2) Get the remainder and pass the next remaining digits\n3) Get the rightmost digit of the number with help of the remainder '%' operator by dividing it by 10 and add it to sum.\n Divide the number by 10 with help of '/' operator to remove the rightmost digit.\n4) Check the base case with n = 0\n5) Print or return the sum"
},
{
"code": null,
"e": 7072,
"s": 7068,
"text": "C++"
},
{
"code": null,
"e": 7074,
"s": 7072,
"text": "C"
},
{
"code": null,
"e": 7079,
"s": 7074,
"text": "Java"
},
{
"code": null,
"e": 7087,
"s": 7079,
"text": "Python3"
},
{
"code": null,
"e": 7090,
"s": 7087,
"text": "C#"
},
{
"code": null,
"e": 7094,
"s": 7090,
"text": "PHP"
},
{
"code": null,
"e": 7105,
"s": 7094,
"text": "Javascript"
},
{
"code": "// C++ program to compute// sum of digits in number.#include <iostream>using namespace std;class gfg {public: int sumDigits(int no) { if(no == 0){ return 0 ; } return (no % 10) + sumDigits(no / 10) ; }}; // Driver codeint main(void){ gfg g; cout << g.sumDigits(687); return 0;}",
"e": 7438,
"s": 7105,
"text": null
},
{
"code": "// C program to compute// sum of digits in number.#include <stdio.h> int sumDigits(int no){ if(no == 0){ return 0 ; } return (no % 10) + sumDigits(no / 10) ;} int main(){ printf(\"%d\", sumDigits(687)); return 0;}",
"e": 7663,
"s": 7438,
"text": null
},
{
"code": "// Java program to compute// sum of digits in number.import java.io.*; class GFG { /* Function to get sum of digits */ static int sumDigits(int no) { if(no == 0){ return 0 ; } return (no % 10) + sumDigits(no / 10) ; } // Driver code public static void main(String[] args) { System.out.println(sumDigits(687)); }} // This code is contributed by Gitanjali",
"e": 8082,
"s": 7663,
"text": null
},
{
"code": "# Python program to compute# sum of digits in number. def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no/10)) # Driver codeprint(sumDigits(687)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 8309,
"s": 8082,
"text": null
},
{
"code": "// C# program to compute// sum of digits in number.using System; class GFG { /* Function to get sum of digits */ static int sumDigits(int no) { return no == 0 ? 0 : no % 10 + sumDigits(no / 10); } // Driver code public static void Main() { Console.Write(sumDigits(687)); }} // This code is contributed by Sam007",
"e": 8660,
"s": 8309,
"text": null
},
{
"code": "<?php// PHP program to compute// sum of digits in number.function sumDigits($no){return $no == 0 ? 0 : $no % 10 + sumDigits($no / 10) ;} // Driver Codeecho sumDigits(687); // This code is contributed by aj_36?>",
"e": 8892,
"s": 8660,
"text": null
},
{
"code": "<script>// Program to compute// sum of digits in number // Function to get sum of digits function sumDigits(no) { if(no == 0){ return 0 ; } return (no % 10) + sumDigits(parseInt(no/10)) ; } // Driver code document.write(sumDigits(687)); // This is code is contributed by simranarora5sos</script>",
"e": 9260,
"s": 8892,
"text": null
},
{
"code": null,
"e": 9263,
"s": 9260,
"text": "21"
},
{
"code": null,
"e": 9289,
"s": 9263,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 9314,
"s": 9289,
"text": "Auxiliary Space: O(logn)"
},
{
"code": null,
"e": 9339,
"s": 9314,
"text": "3.Taking input as String"
},
{
"code": null,
"e": 9648,
"s": 9339,
"text": "When the number of digits of that number exceeds 1019 , we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric)"
},
{
"code": null,
"e": 9698,
"s": 9648,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 9704,
"s": 9698,
"text": "C++14"
},
{
"code": null,
"e": 9709,
"s": 9704,
"text": "Java"
},
{
"code": null,
"e": 9717,
"s": 9709,
"text": "Python3"
},
{
"code": null,
"e": 9720,
"s": 9717,
"text": "C#"
},
{
"code": null,
"e": 9731,
"s": 9720,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <iostream>using namespace std;int getSum(string str){ int sum = 0; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + str[i] - 48; } return sum;} // Driver Codeint main(){ string st = \"123456789123456789123422\"; cout << getSum(st); return 0;}",
"e": 10194,
"s": 9731,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.io.*;class GFG { static int getSum(String str) { int sum = 0; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + str.charAt(i) - 48; } return sum; } // Driver Code public static void main(String[] args) { String st = \"123456789123456789123422\"; System.out.print(getSum(st)); }} // This code is contributed by Dharanendra L V.",
"e": 10809,
"s": 10194,
"text": null
},
{
"code": "# Python implementation of the above approachdef getSum(n): # Initializing sum to 0 sum = 0 # Traversing through string for i in n: # Converting char to int sum = sum + int(i) return sum n = \"123456789123456789123422\"print(getSum(n))",
"e": 11074,
"s": 10809,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;public class GFG { static int getSum(String str) { int sum = 0; // Traversing through the string for (int i = 0; i < str.Length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + str[i] - 48; } return sum; } // Driver Code static public void Main() { String st = \"123456789123456789123422\"; Console.Write(getSum(st)); }} // This code is contributed by Dharanendra L V.",
"e": 11664,
"s": 11074,
"text": null
},
{
"code": "<script>// Javascript implementation of the above approach function getSum(str){ let sum = 0; // Traversing through the string for (let i = 0; i < str.length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum sum = sum + parseInt(str[i]); } return sum;} // Driver Codelet st = \"123456789123456789123422\";document.write(getSum(st)); // This code is contributed by subhammahato348.</script>",
"e": 12142,
"s": 11664,
"text": null
},
{
"code": null,
"e": 12146,
"s": 12142,
"text": "104"
},
{
"code": null,
"e": 12172,
"s": 12146,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 12194,
"s": 12172,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12219,
"s": 12194,
"text": "4. Using Tail Recursion "
},
{
"code": null,
"e": 12308,
"s": 12219,
"text": "This problem can also be solved using Tail Recursion. Here is an approach to solving it."
},
{
"code": null,
"e": 12387,
"s": 12308,
"text": "1. Add another variable “Val” to the function and initialize it to ( val = 0 )"
},
{
"code": null,
"e": 12548,
"s": 12387,
"text": "2. On every call to the function add the mod value (n%10) to the variable as “(n%10)+val” which is the last digit in n. Along with pass the variable n as n/10. "
},
{
"code": null,
"e": 12680,
"s": 12548,
"text": "3. So on the First call it will have the last digit. As we are passing n/10 as n, It follows until n is reduced to a single digit. "
},
{
"code": null,
"e": 12829,
"s": 12680,
"text": "4. n<10 is the base case so When n < 10, then add the n to the variable as it is the last digit and return the val which will have the sum of digits"
},
{
"code": null,
"e": 12833,
"s": 12829,
"text": "C++"
},
{
"code": null,
"e": 12838,
"s": 12833,
"text": "Java"
},
{
"code": null,
"e": 12846,
"s": 12838,
"text": "Python3"
},
{
"code": null,
"e": 12849,
"s": 12846,
"text": "C#"
},
{
"code": null,
"e": 12860,
"s": 12849,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to check sum// of digit using tail recursionint sum_of_digit(int n, int val){ if (n < 10) { val = val + n; return val; } return sum_of_digit(n / 10, (n % 10) + val);} // Driver codeint main(){ int num = 12345; int result = sum_of_digit(num, 0); cout << \"Sum of digits is \" << result; return 0;} // This code is contributed by subhammahato348",
"e": 13339,
"s": 12860,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class sum_of_digits { // Function to check sum // of digit using tail recursion static int sum_of_digit(int n, int val) { if (n < 10) { val = val + n; return val; } return sum_of_digit(n / 10, (n % 10) + val); } // Driven Program to check above public static void main(String args[]) { int num = 12345; int result = sum_of_digit(num, 0); System.out.println(\"Sum of digits is \" + result); }}",
"e": 13919,
"s": 13339,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check sum# of digit using tail recursiondef sum_of_digit(n, val): if (n < 10): val = val + n return val return sum_of_digit(n // 10, (n % 10) + val) # Driver codenum = 12345result = sum_of_digit(num, 0) print(\"Sum of digits is\", result) # This code is contributed by subhammahato348",
"e": 14291,
"s": 13919,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to check sum// of digit using tail recursionstatic int sum_of_digit(int n, int val){ if (n < 10) { val = val + n; return val; } return sum_of_digit(n / 10, (n % 10) + val);} // Driver codepublic static void Main(){ int num = 12345; int result = sum_of_digit(num, 0); Console.Write(\"Sum of digits is \" + result);}} // This code is contributed by subhammahato348",
"e": 14761,
"s": 14291,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to check sum// of digit using tail recursionfunction sum_of_digit(n, val){ if (n < 10) { val = val + n; return val; } return sum_of_digit(parseInt(n / 10), (n % 10) + val);} // Driver code let num = 12345; let result = sum_of_digit(num, 0); document.write(\"Sum of digits is \" + result); // This code is contributed by subhammahato348 </script>",
"e": 15214,
"s": 14761,
"text": null
},
{
"code": null,
"e": 15234,
"s": 15214,
"text": "Sum of digits is 15"
},
{
"code": null,
"e": 15260,
"s": 15234,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 15285,
"s": 15260,
"text": "Auxiliary Space: O(logn)"
},
{
"code": null,
"e": 15404,
"s": 15285,
"text": "Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem."
},
{
"code": null,
"e": 15410,
"s": 15404,
"text": "jit_t"
},
{
"code": null,
"e": 15423,
"s": 15410,
"text": "SoumikMondal"
},
{
"code": null,
"e": 15437,
"s": 15423,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 15448,
"s": 15437,
"text": "vikkycirus"
},
{
"code": null,
"e": 15464,
"s": 15448,
"text": "dharanendralv23"
},
{
"code": null,
"e": 15480,
"s": 15464,
"text": "SatheeshKumarMR"
},
{
"code": null,
"e": 15496,
"s": 15480,
"text": "gauravl3hardwaj"
},
{
"code": null,
"e": 15506,
"s": 15496,
"text": "rutvik_56"
},
{
"code": null,
"e": 15522,
"s": 15506,
"text": "subhammahato348"
},
{
"code": null,
"e": 15538,
"s": 15522,
"text": "simranarora5sos"
},
{
"code": null,
"e": 15548,
"s": 15538,
"text": "ruhelaa48"
},
{
"code": null,
"e": 15561,
"s": 15548,
"text": "prasanna1995"
},
{
"code": null,
"e": 15576,
"s": 15561,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 15590,
"s": 15576,
"text": "helderdacosta"
},
{
"code": null,
"e": 15601,
"s": 15590,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 15615,
"s": 15601,
"text": "number-digits"
},
{
"code": null,
"e": 15626,
"s": 15615,
"text": "C Language"
},
{
"code": null,
"e": 15630,
"s": 15626,
"text": "C++"
},
{
"code": null,
"e": 15640,
"s": 15630,
"text": "Recursion"
},
{
"code": null,
"e": 15650,
"s": 15640,
"text": "Recursion"
},
{
"code": null,
"e": 15654,
"s": 15650,
"text": "CPP"
},
{
"code": null,
"e": 15752,
"s": 15654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15775,
"s": 15752,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 15802,
"s": 15775,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 15818,
"s": 15802,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 15835,
"s": 15818,
"text": "Substring in C++"
},
{
"code": null,
"e": 15913,
"s": 15835,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 15931,
"s": 15913,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 15974,
"s": 15931,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 16020,
"s": 15974,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 16043,
"s": 16020,
"text": "std::sort() in C++ STL"
}
] |
Components of a URL | 29 Jun, 2021
If you are SpongeBob then your URL is Bikini Bottom on the floor of the Pacific Ocean but if you’re not, your URL is definitely the address of the house you live in! URL stands for Uniform Resource Locator. For a website, a URL is basically where the website lives online and it helps visitors to identify the site easily as well as get an idea about its contents.
A typical website has at least 3 parts in its URL like www.google.com but some complex URLs might also have 8 to 9 parts namely scheme, subdomain, domain name, top-level domain, port number, path, query, parameters, and fragment.
Components of a URL
1. Scheme :
https://
The protocol or scheme part of the URL and indicates the set of rules that will decide the transmission and exchange of data. HTTPS which stands for Hyper Text Transfer Protocol Secure tells the browser to display the page in Hyper Text (HTML) format as well as encrypt any information that the user enters in the page. Other protocols include the FTP or File Transfer Protocol which is used for transferring files between client and server, SMTP or Single Mail Transfer Protocol which is used for sending emails.
2. Subdomain :
https://www.
The subdomain is used to separate different sections of the website as it specifies the type of resource to be delivered to the client. Here the subdomain used ‘www’ is a general symbol for any resource on the web. Subdomains like ‘blog’ direct to a blog page, ‘audio’ indicates the resource type as audio.
3. Domain Name :
https://www.example.
Domain name specifies the organization or entity that the URL belongs to. Like in www.facebook.com the domain name ‘facebook’ indicates the organization that owns the site.
4. Top-level Domain :
https://www.example.co.uk
The TLD (top-level domain) indicates the type of organization the website is registered to. Like the .com in www.facebook.com indicates a commercial entity. Similarly, .org indicates organization, .co.uk a commercial entity in the UK.
5. Port Number :
https://www.example.co.uk:443
A port number specifies the type of service that is requested by the client since servers often deliver multiple services. Some default port numbers include 80 for HTTP and 443 for HTTPS servers.
6. Path :
https://www.example.co.uk:443/blog/article/search
Path specifies the exact location of the web page, file, or any resource that the user wants access to. Like here the path indicates a specific article in the blog webpage.
7. Query String Separator :
https://www.example.co.uk:443/blog/article/search?
The query string which contains specific parameters of the search is preceded by a question mark (?). The question mark tells the browser that a specific query is being performed.
8. Query String :
https://www.example.co.uk:443/blog/article/search?docid=720&hl=en
The query string specifies the parameters of the data that is being queried from a website’s database. Each query string is made up of a parameter and a value joined by the equals (=) sign. In case of multiple parameters, query strings are joined using the ampersand (&) sign. The parameter can be a number, string, encrypted value, or any other form of data on the database.
9. Fragment :
https://www.example.co.uk:443/blog/article/search?docid=720&hl=en#dayone
The fragment identifier of a URL is optional, usually appears at the end, and begins with a hash (#). It indicates a specific location within a page such as the ‘id’ or ‘name’ attribute for an HTML element.
You might be surprised that though URLs seem to be trivial in nature, what your URL looks like is actually a significant factor in Search Engine Optimization (SEO). Feel free to check out more on URLs from here:
https://developer.mozilla.org/enUS/docs/Learn/Common_questions/What_is_a_URL
https://www.hostgator.com/blog/best-url-structure-seo/
Source: https://amberwilson.co.uk/blog/urls/
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
Introduction of Mobile Ad hoc Network (MANET)
Intrusion Detection System (IDS)
Cryptography and its Types
Bluetooth
Difference between URL and URI | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 418,
"s": 53,
"text": "If you are SpongeBob then your URL is Bikini Bottom on the floor of the Pacific Ocean but if you’re not, your URL is definitely the address of the house you live in! URL stands for Uniform Resource Locator. For a website, a URL is basically where the website lives online and it helps visitors to identify the site easily as well as get an idea about its contents."
},
{
"code": null,
"e": 648,
"s": 418,
"text": "A typical website has at least 3 parts in its URL like www.google.com but some complex URLs might also have 8 to 9 parts namely scheme, subdomain, domain name, top-level domain, port number, path, query, parameters, and fragment."
},
{
"code": null,
"e": 668,
"s": 648,
"text": "Components of a URL"
},
{
"code": null,
"e": 680,
"s": 668,
"text": "1. Scheme :"
},
{
"code": null,
"e": 689,
"s": 680,
"text": "https://"
},
{
"code": null,
"e": 1203,
"s": 689,
"text": "The protocol or scheme part of the URL and indicates the set of rules that will decide the transmission and exchange of data. HTTPS which stands for Hyper Text Transfer Protocol Secure tells the browser to display the page in Hyper Text (HTML) format as well as encrypt any information that the user enters in the page. Other protocols include the FTP or File Transfer Protocol which is used for transferring files between client and server, SMTP or Single Mail Transfer Protocol which is used for sending emails."
},
{
"code": null,
"e": 1218,
"s": 1203,
"text": "2. Subdomain :"
},
{
"code": null,
"e": 1231,
"s": 1218,
"text": "https://www."
},
{
"code": null,
"e": 1538,
"s": 1231,
"text": "The subdomain is used to separate different sections of the website as it specifies the type of resource to be delivered to the client. Here the subdomain used ‘www’ is a general symbol for any resource on the web. Subdomains like ‘blog’ direct to a blog page, ‘audio’ indicates the resource type as audio."
},
{
"code": null,
"e": 1555,
"s": 1538,
"text": "3. Domain Name :"
},
{
"code": null,
"e": 1576,
"s": 1555,
"text": "https://www.example."
},
{
"code": null,
"e": 1751,
"s": 1576,
"text": "Domain name specifies the organization or entity that the URL belongs to. Like in www.facebook.com the domain name ‘facebook’ indicates the organization that owns the site. "
},
{
"code": null,
"e": 1773,
"s": 1751,
"text": "4. Top-level Domain :"
},
{
"code": null,
"e": 1799,
"s": 1773,
"text": "https://www.example.co.uk"
},
{
"code": null,
"e": 2034,
"s": 1799,
"text": "The TLD (top-level domain) indicates the type of organization the website is registered to. Like the .com in www.facebook.com indicates a commercial entity. Similarly, .org indicates organization, .co.uk a commercial entity in the UK."
},
{
"code": null,
"e": 2051,
"s": 2034,
"text": "5. Port Number :"
},
{
"code": null,
"e": 2081,
"s": 2051,
"text": "https://www.example.co.uk:443"
},
{
"code": null,
"e": 2277,
"s": 2081,
"text": "A port number specifies the type of service that is requested by the client since servers often deliver multiple services. Some default port numbers include 80 for HTTP and 443 for HTTPS servers."
},
{
"code": null,
"e": 2287,
"s": 2277,
"text": "6. Path :"
},
{
"code": null,
"e": 2337,
"s": 2287,
"text": "https://www.example.co.uk:443/blog/article/search"
},
{
"code": null,
"e": 2512,
"s": 2337,
"text": "Path specifies the exact location of the web page, file, or any resource that the user wants access to. Like here the path indicates a specific article in the blog webpage. "
},
{
"code": null,
"e": 2540,
"s": 2512,
"text": "7. Query String Separator :"
},
{
"code": null,
"e": 2591,
"s": 2540,
"text": "https://www.example.co.uk:443/blog/article/search?"
},
{
"code": null,
"e": 2771,
"s": 2591,
"text": "The query string which contains specific parameters of the search is preceded by a question mark (?). The question mark tells the browser that a specific query is being performed."
},
{
"code": null,
"e": 2789,
"s": 2771,
"text": "8. Query String :"
},
{
"code": null,
"e": 2855,
"s": 2789,
"text": "https://www.example.co.uk:443/blog/article/search?docid=720&hl=en"
},
{
"code": null,
"e": 3231,
"s": 2855,
"text": "The query string specifies the parameters of the data that is being queried from a website’s database. Each query string is made up of a parameter and a value joined by the equals (=) sign. In case of multiple parameters, query strings are joined using the ampersand (&) sign. The parameter can be a number, string, encrypted value, or any other form of data on the database."
},
{
"code": null,
"e": 3245,
"s": 3231,
"text": "9. Fragment :"
},
{
"code": null,
"e": 3318,
"s": 3245,
"text": "https://www.example.co.uk:443/blog/article/search?docid=720&hl=en#dayone"
},
{
"code": null,
"e": 3526,
"s": 3318,
"text": "The fragment identifier of a URL is optional, usually appears at the end, and begins with a hash (#). It indicates a specific location within a page such as the ‘id’ or ‘name’ attribute for an HTML element."
},
{
"code": null,
"e": 3738,
"s": 3526,
"text": "You might be surprised that though URLs seem to be trivial in nature, what your URL looks like is actually a significant factor in Search Engine Optimization (SEO). Feel free to check out more on URLs from here:"
},
{
"code": null,
"e": 3815,
"s": 3738,
"text": "https://developer.mozilla.org/enUS/docs/Learn/Common_questions/What_is_a_URL"
},
{
"code": null,
"e": 3870,
"s": 3815,
"text": "https://www.hostgator.com/blog/best-url-structure-seo/"
},
{
"code": null,
"e": 3915,
"s": 3870,
"text": "Source: https://amberwilson.co.uk/blog/urls/"
},
{
"code": null,
"e": 3933,
"s": 3915,
"text": "Computer Networks"
},
{
"code": null,
"e": 3951,
"s": 3933,
"text": "Computer Networks"
},
{
"code": null,
"e": 4049,
"s": 3951,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4079,
"s": 4049,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 4105,
"s": 4079,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 4135,
"s": 4105,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 4175,
"s": 4135,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 4210,
"s": 4175,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 4256,
"s": 4210,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 4289,
"s": 4256,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 4316,
"s": 4289,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 4326,
"s": 4316,
"text": "Bluetooth"
}
] |
Java Program for Leaders in an array | 13 Dec, 2021
Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. Let the input array be arr[] and size of the array be size.
Method 1 (Simple) Use two loops. The outer loop runs from 0 to size – 1 and one by one picks all elements from left to right. The inner loop compares the picked element to all the elements to its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader.
Java
class LeadersInArray { /*Java Function to print leaders in an array */ void printLeaders(int arr[], int size) { for (int i = 0; i < size; i++) { int j; for (j = i + 1; j < size; j++) { if (arr[i] <=arr[j]) break; } if (j == size) // the loop didn't break System.out.print(arr[i] + " "); } } /* Driver program to test above functions */ public static void main(String[] args) { LeadersInArray lead = new LeadersInArray(); int arr[] = new int[]{16, 17, 4, 3, 5, 2}; int n = arr.length; lead.printLeaders(arr, n); }}
Output:
17 5 2
Time Complexity: O(n*n)Method 2 (Scan from right) Scan all the elements from right to left in an array and keep track of maximum till now. When maximum changes its value, print it.Below image is a dry run of the above approach:
Below is the implementation of the above approach:
Java
class LeadersInArray { /* Java Function to print leaders in an array */ void printLeaders(int arr[], int size) { int max_from_right = arr[size-1]; /* Rightmost element is always leader */ System.out.print(max_from_right + " "); for (int i = size-2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; System.out.print(max_from_right + " "); } } } /* Driver program to test above functions */ public static void main(String[] args) { LeadersInArray lead = new LeadersInArray(); int arr[] = new int[]{16, 17, 4, 3, 5, 2}; int n = arr.length; lead.printLeaders(arr, n); }}
Output:
2 5 17
Time Complexity: O(n)
Please refer complete article on Leaders in an array for more details!
Amazon
Payu
Arrays
Java
Java Programs
Amazon
Payu
Arrays
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. Let the input array be arr[] and size of the array be size. "
},
{
"code": null,
"e": 665,
"s": 342,
"text": "Method 1 (Simple) Use two loops. The outer loop runs from 0 to size – 1 and one by one picks all elements from left to right. The inner loop compares the picked element to all the elements to its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader. "
},
{
"code": null,
"e": 670,
"s": 665,
"text": "Java"
},
{
"code": "class LeadersInArray { /*Java Function to print leaders in an array */ void printLeaders(int arr[], int size) { for (int i = 0; i < size; i++) { int j; for (j = i + 1; j < size; j++) { if (arr[i] <=arr[j]) break; } if (j == size) // the loop didn't break System.out.print(arr[i] + \" \"); } } /* Driver program to test above functions */ public static void main(String[] args) { LeadersInArray lead = new LeadersInArray(); int arr[] = new int[]{16, 17, 4, 3, 5, 2}; int n = arr.length; lead.printLeaders(arr, n); }}",
"e": 1367,
"s": 670,
"text": null
},
{
"code": null,
"e": 1376,
"s": 1367,
"text": "Output: "
},
{
"code": null,
"e": 1383,
"s": 1376,
"text": "17 5 2"
},
{
"code": null,
"e": 1612,
"s": 1383,
"text": "Time Complexity: O(n*n)Method 2 (Scan from right) Scan all the elements from right to left in an array and keep track of maximum till now. When maximum changes its value, print it.Below image is a dry run of the above approach: "
},
{
"code": null,
"e": 1664,
"s": 1612,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1669,
"s": 1664,
"text": "Java"
},
{
"code": "class LeadersInArray { /* Java Function to print leaders in an array */ void printLeaders(int arr[], int size) { int max_from_right = arr[size-1]; /* Rightmost element is always leader */ System.out.print(max_from_right + \" \"); for (int i = size-2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; System.out.print(max_from_right + \" \"); } } } /* Driver program to test above functions */ public static void main(String[] args) { LeadersInArray lead = new LeadersInArray(); int arr[] = new int[]{16, 17, 4, 3, 5, 2}; int n = arr.length; lead.printLeaders(arr, n); }}",
"e": 2436,
"s": 1669,
"text": null
},
{
"code": null,
"e": 2444,
"s": 2436,
"text": "Output:"
},
{
"code": null,
"e": 2451,
"s": 2444,
"text": "2 5 17"
},
{
"code": null,
"e": 2474,
"s": 2451,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 2545,
"s": 2474,
"text": "Please refer complete article on Leaders in an array for more details!"
},
{
"code": null,
"e": 2552,
"s": 2545,
"text": "Amazon"
},
{
"code": null,
"e": 2557,
"s": 2552,
"text": "Payu"
},
{
"code": null,
"e": 2564,
"s": 2557,
"text": "Arrays"
},
{
"code": null,
"e": 2569,
"s": 2564,
"text": "Java"
},
{
"code": null,
"e": 2583,
"s": 2569,
"text": "Java Programs"
},
{
"code": null,
"e": 2590,
"s": 2583,
"text": "Amazon"
},
{
"code": null,
"e": 2595,
"s": 2590,
"text": "Payu"
},
{
"code": null,
"e": 2602,
"s": 2595,
"text": "Arrays"
},
{
"code": null,
"e": 2607,
"s": 2602,
"text": "Java"
},
{
"code": null,
"e": 2705,
"s": 2607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2737,
"s": 2705,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 2762,
"s": 2737,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 2809,
"s": 2762,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 2873,
"s": 2809,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 2904,
"s": 2873,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 2940,
"s": 2904,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 2984,
"s": 2940,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 3009,
"s": 2984,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3060,
"s": 3009,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Python | Substring removal in String list | 30 Jan, 2020
While working with strings, one of the most used application is removing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the removing of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + replace()The replace method can be coupled with the list comprehension technique to achieve this particular task. List comprehension performs the task of iterating through the list and replace method replaces the section of substring with empty string.
# Python3 code to demonstrate# Substring removal in String list# using list comprehension + replace() # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print("The original list : " + str(test_list )) # using list comprehension + replace()# Substring removal in String listres = [sub.replace('4', '') for sub in test_list] # print resultprint("The list after substring removal : " + str(res))
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring removal : ['', 'kg', 'butter', 'for', '0', 'bucks']
Method #2 : Using map() + lambda + replace()The combination of these functions can also be used to perform this particular task. The map and lambda help to perform the task same as list comprehension and replace method is used to perform the remove functionality. But this method is poor when it comes to performance than method above.
# Python3 code to demonstrate# Substring removal in String list# using list comprehension + map() + lambda # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print("The original list : " + str(test_list )) # using list comprehension + map() + lambda# Substring removal in String listres = list(map(lambda st: str.replace(st, "4", ""), test_list)) # print resultprint("The list after substring removal : " + str(res))
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring removal : ['', 'kg', 'butter', 'for', '0', 'bucks']
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 352,
"s": 28,
"text": "While working with strings, one of the most used application is removing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the removing of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 644,
"s": 352,
"text": "Method #1 : Using list comprehension + replace()The replace method can be coupled with the list comprehension technique to achieve this particular task. List comprehension performs the task of iterating through the list and replace method replaces the section of substring with empty string."
},
{
"code": "# Python3 code to demonstrate# Substring removal in String list# using list comprehension + replace() # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print(\"The original list : \" + str(test_list )) # using list comprehension + replace()# Substring removal in String listres = [sub.replace('4', '') for sub in test_list] # print resultprint(\"The list after substring removal : \" + str(res))",
"e": 1095,
"s": 644,
"text": null
},
{
"code": null,
"e": 1237,
"s": 1095,
"text": "The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']\nThe list after substring removal : ['', 'kg', 'butter', 'for', '0', 'bucks']\n"
},
{
"code": null,
"e": 1575,
"s": 1239,
"text": "Method #2 : Using map() + lambda + replace()The combination of these functions can also be used to perform this particular task. The map and lambda help to perform the task same as list comprehension and replace method is used to perform the remove functionality. But this method is poor when it comes to performance than method above."
},
{
"code": "# Python3 code to demonstrate# Substring removal in String list# using list comprehension + map() + lambda # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks'] # printing original list print(\"The original list : \" + str(test_list )) # using list comprehension + map() + lambda# Substring removal in String listres = list(map(lambda st: str.replace(st, \"4\", \"\"), test_list)) # print resultprint(\"The list after substring removal : \" + str(res))",
"e": 2050,
"s": 1575,
"text": null
},
{
"code": null,
"e": 2192,
"s": 2050,
"text": "The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']\nThe list after substring removal : ['', 'kg', 'butter', 'for', '0', 'bucks']\n"
},
{
"code": null,
"e": 2213,
"s": 2192,
"text": "Python list-programs"
},
{
"code": null,
"e": 2220,
"s": 2213,
"text": "Python"
},
{
"code": null,
"e": 2236,
"s": 2220,
"text": "Python Programs"
},
{
"code": null,
"e": 2334,
"s": 2236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2366,
"s": 2334,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2393,
"s": 2366,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2414,
"s": 2393,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2437,
"s": 2414,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2493,
"s": 2437,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2515,
"s": 2493,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2554,
"s": 2515,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2592,
"s": 2554,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2641,
"s": 2592,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Coding-Decoding | 30 Sep, 2020
CODING-DECODING is an important part of Logical reasoning section in all aptitude related examinations. Coding is a process used to encrypt a word, a number in a particular code or pattern based on some set of rules. Decoding is a process to decrypt the pattern into its original form from the given codes.
Letter Coding In this type of questions, alphabets of a word are replaced by some other alphabets according to specific rule to form code.
Number Coding In this type of questions, a word is replaced by certain numbers according to some specific rule.
Question 1: If EARTH is written as FCUXM in a certain code. How is MOON written in that code? Solution :
Question 2: If DELHI is written as EDMGJ in a certain code. How is NEPAL written in that code? Solution :
Question 3: If SYMBOL is written as NZTMPC is a certain code. How is NUMBER written in that code? Solution : Acc. to question
Question 4: In a certain code, COMPUTER is written as PMOCRETU, how is DECIPHER written in that code? Solution : Acc. to question
Question 5: In a certain code, NEWYORK is written as 111, how is NEWJERSEY written in that code? Solution : In NEWYORK N = 14, E = 5, W = 23, Y = 25, O = 15, R = 18, K = 11 Total = 14 + 5 + 23 + 25 + 15 + 18 + 11 = 111 In NEWJERSEY Total = 14 + 5 + 23 + 10 + 5 + 18 + 19 + 5 + 25 = 124
Question 6: In a certain code, HARYANA is written as 8197151, how is DELHI written in that code? Solution : We used the number of alphabets here. H = 8 A = 1 R = 18 = 1+8 = 9 Y = 25 = 2+5 = 7 For DELHI D = 4 E = 5 L = 12 = 1+2 = 3 H = 8 I = 9 Hence, DELHI is written as 45389.
Question 7: In a certain code BOMB is written as 5745 and BAY is written as 529, how is BOMBAY written in that code? Solution : Acc. to question Use the numbers to relate the words
B O M B B A Y -> B O M B A Y
5 7 4 5 5 2 9 5 7 4 5 2 9
Practice Problems:
Q1: If in a certain language, MADRAS is coded as NBESBT, how is BOMBAY coded in that code?
(a) CPNCBX (6) CPNCBZ (c) CPOCBZ (d) CQOCBZ (e) None of these
Q2: In a certain code, TRIPPLE is written as SQHOOKD. How is DISPOSE written in that code?
(a) CHRONRD (6) DSOESPI (c) ESJTPTF (d) ESOPSID (e) None of these
Q3: If in a code language. COULD is written as BNTKC and MARGIN is written as LZQFHM, how will MOULDING be written in that code?
(a) CHMFINTK (6) LNKTCHMF (c) LNTKCHMF (d) NITKHCMF (e) None of these
Q4: In a certain code, MONKEY is written as XDJMNL. How is TIGER written in that code?
(a) QDFHS (6) SDFHS (c) SHFDQ (d) UJHFS (e) None of these
Q5: If FRAGRANCE is written as SBHSBODFG, how can IMPOSING be written?
(a) NQPTJHOJ (6) NQPTJOHI (c) NQTPJOHJ (d) NQPTJOHJ (c) None of these
Find Your Answers Here
Q1: (b), Q2: (a), Q3: (c), Q4: (a), Q5: (d)
mansi_modi
Aptitude
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Aptitude | Arithmetic Aptitude 4 | Question 5
Aptitude | Probability | Question 1
Aptitude | Arithmetic Aptitude | Question 2
Order and Ranking Questions & Answers
Puzzle | How much money did the man have before entering the bank?
Aptitude | Arithmetic Aptitude 4 | Question 6
Aptitude | Arithmetic Aptitude | Question 4
Aptitude | Arithmetic Aptitude 2 | Question 8
Seating Arrangement | Aptitude
Aptitude | Arithmetic Aptitude | Question 1 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 360,
"s": 52,
"text": "CODING-DECODING is an important part of Logical reasoning section in all aptitude related examinations. Coding is a process used to encrypt a word, a number in a particular code or pattern based on some set of rules. Decoding is a process to decrypt the pattern into its original form from the given codes. "
},
{
"code": null,
"e": 500,
"s": 360,
"text": "Letter Coding In this type of questions, alphabets of a word are replaced by some other alphabets according to specific rule to form code. "
},
{
"code": null,
"e": 613,
"s": 500,
"text": "Number Coding In this type of questions, a word is replaced by certain numbers according to some specific rule. "
},
{
"code": null,
"e": 726,
"s": 619,
"text": "Question 1: If EARTH is written as FCUXM in a certain code. How is MOON written in that code? Solution : "
},
{
"code": null,
"e": 834,
"s": 726,
"text": "Question 2: If DELHI is written as EDMGJ in a certain code. How is NEPAL written in that code? Solution : "
},
{
"code": null,
"e": 962,
"s": 834,
"text": "Question 3: If SYMBOL is written as NZTMPC is a certain code. How is NUMBER written in that code? Solution : Acc. to question "
},
{
"code": null,
"e": 1094,
"s": 962,
"text": "Question 4: In a certain code, COMPUTER is written as PMOCRETU, how is DECIPHER written in that code? Solution : Acc. to question "
},
{
"code": null,
"e": 1381,
"s": 1094,
"text": "Question 5: In a certain code, NEWYORK is written as 111, how is NEWJERSEY written in that code? Solution : In NEWYORK N = 14, E = 5, W = 23, Y = 25, O = 15, R = 18, K = 11 Total = 14 + 5 + 23 + 25 + 15 + 18 + 11 = 111 In NEWJERSEY Total = 14 + 5 + 23 + 10 + 5 + 18 + 19 + 5 + 25 = 124 "
},
{
"code": null,
"e": 1659,
"s": 1381,
"text": "Question 6: In a certain code, HARYANA is written as 8197151, how is DELHI written in that code? Solution : We used the number of alphabets here. H = 8 A = 1 R = 18 = 1+8 = 9 Y = 25 = 2+5 = 7 For DELHI D = 4 E = 5 L = 12 = 1+2 = 3 H = 8 I = 9 Hence, DELHI is written as 45389. "
},
{
"code": null,
"e": 1842,
"s": 1659,
"text": "Question 7: In a certain code BOMB is written as 5745 and BAY is written as 529, how is BOMBAY written in that code? Solution : Acc. to question Use the numbers to relate the words "
},
{
"code": null,
"e": 1955,
"s": 1842,
"text": " B O M B B A Y -> B O M B A Y \n 5 7 4 5 5 2 9 5 7 4 5 2 9\n\n\n\n"
},
{
"code": null,
"e": 1974,
"s": 1955,
"text": "Practice Problems:"
},
{
"code": null,
"e": 2065,
"s": 1974,
"text": "Q1: If in a certain language, MADRAS is coded as NBESBT, how is BOMBAY coded in that code?"
},
{
"code": null,
"e": 2127,
"s": 2065,
"text": "(a) CPNCBX (6) CPNCBZ (c) CPOCBZ (d) CQOCBZ (e) None of these"
},
{
"code": null,
"e": 2218,
"s": 2127,
"text": "Q2: In a certain code, TRIPPLE is written as SQHOOKD. How is DISPOSE written in that code?"
},
{
"code": null,
"e": 2284,
"s": 2218,
"text": "(a) CHRONRD (6) DSOESPI (c) ESJTPTF (d) ESOPSID (e) None of these"
},
{
"code": null,
"e": 2413,
"s": 2284,
"text": "Q3: If in a code language. COULD is written as BNTKC and MARGIN is written as LZQFHM, how will MOULDING be written in that code?"
},
{
"code": null,
"e": 2483,
"s": 2413,
"text": "(a) CHMFINTK (6) LNKTCHMF (c) LNTKCHMF (d) NITKHCMF (e) None of these"
},
{
"code": null,
"e": 2570,
"s": 2483,
"text": "Q4: In a certain code, MONKEY is written as XDJMNL. How is TIGER written in that code?"
},
{
"code": null,
"e": 2628,
"s": 2570,
"text": "(a) QDFHS (6) SDFHS (c) SHFDQ (d) UJHFS (e) None of these"
},
{
"code": null,
"e": 2699,
"s": 2628,
"text": "Q5: If FRAGRANCE is written as SBHSBODFG, how can IMPOSING be written?"
},
{
"code": null,
"e": 2769,
"s": 2699,
"text": "(a) NQPTJHOJ (6) NQPTJOHI (c) NQTPJOHJ (d) NQPTJOHJ (c) None of these"
},
{
"code": null,
"e": 2792,
"s": 2769,
"text": "Find Your Answers Here"
},
{
"code": null,
"e": 2836,
"s": 2792,
"text": "Q1: (b), Q2: (a), Q3: (c), Q4: (a), Q5: (d)"
},
{
"code": null,
"e": 2847,
"s": 2836,
"text": "mansi_modi"
},
{
"code": null,
"e": 2856,
"s": 2847,
"text": "Aptitude"
},
{
"code": null,
"e": 2954,
"s": 2856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3000,
"s": 2954,
"text": "Aptitude | Arithmetic Aptitude 4 | Question 5"
},
{
"code": null,
"e": 3036,
"s": 3000,
"text": "Aptitude | Probability | Question 1"
},
{
"code": null,
"e": 3080,
"s": 3036,
"text": "Aptitude | Arithmetic Aptitude | Question 2"
},
{
"code": null,
"e": 3118,
"s": 3080,
"text": "Order and Ranking Questions & Answers"
},
{
"code": null,
"e": 3185,
"s": 3118,
"text": "Puzzle | How much money did the man have before entering the bank?"
},
{
"code": null,
"e": 3231,
"s": 3185,
"text": "Aptitude | Arithmetic Aptitude 4 | Question 6"
},
{
"code": null,
"e": 3275,
"s": 3231,
"text": "Aptitude | Arithmetic Aptitude | Question 4"
},
{
"code": null,
"e": 3321,
"s": 3275,
"text": "Aptitude | Arithmetic Aptitude 2 | Question 8"
},
{
"code": null,
"e": 3352,
"s": 3321,
"text": "Seating Arrangement | Aptitude"
}
] |
Ellipsis in C++ with Examples | 19 Aug, 2020
Ellipsis in C++ allows the function to accept an indeterminate number of arguments. It is also known as the variable argument list. Ellipsis tells the compiler to not check the type and number of parameters the function should accept which allows the user to pass the variable argument list. By default, functions can only take a fixed number of parameters that are known to the function beforehand. The user cannot pass a variable number of arguments.
Program 1:
Below is the code that gives compilation error:
C++
// C++ program to demonstrate the// compilation error as max function// doesn't take more than 2 arguments#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Below Line will given Compilation // Error as 4 arguments are passed // instead of 2 int l = max(4, 5, 6, 7); cout << l; return 0;}
Output:Below is the output of the above program:
Explanation:
max() function can take only 2 arguments. So when 4 arguments were used to it in the function call, the compiler threw an error. However, there may be some situations a function has to take a variable number of arguments.
We can pass number of arguments using Ellipsis. It is defined under the cstdarg header file. Ellipsis is not a keyword rather it is denoted by ‘...’ sign.
Below is the program to illustrate the use of Ellipsis:
C++
// C++ program to demonstrate the// use of Ellipsis#include <cstdarg>#include <iostream>using namespace std; // Function accepting variable number// of arguments using Ellipsisdouble average(int count, ...){ // va_list found in <cstdarg> and // list is its type, used to // iterate on ellipsis va_list list; // Initialize position of va_list va_start(list, count); double avg = 0.0; // Iterate through every argument for (int i = 0; i < count; i++) { avg += static_cast<double>(va_arg(list, int)) / count; } // Ends the use of va_list va_end(list); // Return the average return avg;} // Driver Codeint main(){ // Function call double avg = average(6, 1, 2, 3, 4, 5, 6); // Print Average cout << "Average is " << avg; return 0;}
Average is 3.5
Explanation:
Here, average() takes six arguments and calculates the average. Let us see how it works.
va_list type is used to access the values in the ellipsis. It will be conceptually easy for you if you think of ellipsis as an array. In that case, va_list will act as the iterator type. The va_list is not a special type. It is a macro definition.
va_start points to the va_list at the starting point of the ellipsis. It takes two arguments: va_list itself and the last normal parameter (non-ellipsis).
va_arg returns the value which va_list is currently referring to and also moves va_list to the next parameter. It also takes two arguments: va_list itself and the type of the parameter we are trying to access.
va_end takes only one argument: va_list itself. It is used to clean up the va_list macro.
Though ellipsis gives us some useful functionality, it is quite dangerous to use them. When using ellipsis, the compiler does not check the type of arguments passed to the function. So the compiler does not throw any error if arguments are of different types. Even if pass string, double, or bool type values are passed to the average() function it returns return an unexpected value, the compiler does not throw any error.
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 507,
"s": 54,
"text": "Ellipsis in C++ allows the function to accept an indeterminate number of arguments. It is also known as the variable argument list. Ellipsis tells the compiler to not check the type and number of parameters the function should accept which allows the user to pass the variable argument list. By default, functions can only take a fixed number of parameters that are known to the function beforehand. The user cannot pass a variable number of arguments."
},
{
"code": null,
"e": 518,
"s": 507,
"text": "Program 1:"
},
{
"code": null,
"e": 566,
"s": 518,
"text": "Below is the code that gives compilation error:"
},
{
"code": null,
"e": 570,
"s": 566,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// compilation error as max function// doesn't take more than 2 arguments#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Below Line will given Compilation // Error as 4 arguments are passed // instead of 2 int l = max(4, 5, 6, 7); cout << l; return 0;}",
"e": 901,
"s": 570,
"text": null
},
{
"code": null,
"e": 950,
"s": 901,
"text": "Output:Below is the output of the above program:"
},
{
"code": null,
"e": 963,
"s": 950,
"text": "Explanation:"
},
{
"code": null,
"e": 1186,
"s": 963,
"text": "max() function can take only 2 arguments. So when 4 arguments were used to it in the function call, the compiler threw an error. However, there may be some situations a function has to take a variable number of arguments. "
},
{
"code": null,
"e": 1342,
"s": 1186,
"text": "We can pass number of arguments using Ellipsis. It is defined under the cstdarg header file. Ellipsis is not a keyword rather it is denoted by ‘...’ sign. "
},
{
"code": null,
"e": 1398,
"s": 1342,
"text": "Below is the program to illustrate the use of Ellipsis:"
},
{
"code": null,
"e": 1402,
"s": 1398,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// use of Ellipsis#include <cstdarg>#include <iostream>using namespace std; // Function accepting variable number// of arguments using Ellipsisdouble average(int count, ...){ // va_list found in <cstdarg> and // list is its type, used to // iterate on ellipsis va_list list; // Initialize position of va_list va_start(list, count); double avg = 0.0; // Iterate through every argument for (int i = 0; i < count; i++) { avg += static_cast<double>(va_arg(list, int)) / count; } // Ends the use of va_list va_end(list); // Return the average return avg;} // Driver Codeint main(){ // Function call double avg = average(6, 1, 2, 3, 4, 5, 6); // Print Average cout << \"Average is \" << avg; return 0;}",
"e": 2222,
"s": 1402,
"text": null
},
{
"code": null,
"e": 2238,
"s": 2222,
"text": "Average is 3.5\n"
},
{
"code": null,
"e": 2251,
"s": 2238,
"text": "Explanation:"
},
{
"code": null,
"e": 2340,
"s": 2251,
"text": "Here, average() takes six arguments and calculates the average. Let us see how it works."
},
{
"code": null,
"e": 2589,
"s": 2340,
"text": "va_list type is used to access the values in the ellipsis. It will be conceptually easy for you if you think of ellipsis as an array. In that case, va_list will act as the iterator type. The va_list is not a special type. It is a macro definition."
},
{
"code": null,
"e": 2744,
"s": 2589,
"text": "va_start points to the va_list at the starting point of the ellipsis. It takes two arguments: va_list itself and the last normal parameter (non-ellipsis)."
},
{
"code": null,
"e": 2954,
"s": 2744,
"text": "va_arg returns the value which va_list is currently referring to and also moves va_list to the next parameter. It also takes two arguments: va_list itself and the type of the parameter we are trying to access."
},
{
"code": null,
"e": 3044,
"s": 2954,
"text": "va_end takes only one argument: va_list itself. It is used to clean up the va_list macro."
},
{
"code": null,
"e": 3468,
"s": 3044,
"text": "Though ellipsis gives us some useful functionality, it is quite dangerous to use them. When using ellipsis, the compiler does not check the type of arguments passed to the function. So the compiler does not throw any error if arguments are of different types. Even if pass string, double, or bool type values are passed to the average() function it returns return an unexpected value, the compiler does not throw any error."
},
{
"code": null,
"e": 3472,
"s": 3468,
"text": "C++"
},
{
"code": null,
"e": 3485,
"s": 3472,
"text": "C++ Programs"
},
{
"code": null,
"e": 3489,
"s": 3485,
"text": "CPP"
},
{
"code": null,
"e": 3587,
"s": 3489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3611,
"s": 3587,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3631,
"s": 3611,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3675,
"s": 3631,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3708,
"s": 3675,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3733,
"s": 3708,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3768,
"s": 3733,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 3802,
"s": 3768,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 3846,
"s": 3802,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 3905,
"s": 3846,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Get specific elements from embedded array in MongoDB? | To get specific elements, use $match with dot notation. Let us create a collection with documents −
> db.demo641.insert(
... {
... ProductId:101,
... "ProductInformation":
... ( [
... {
... ProductName:"Product-1",
... "ProductPrice":1000
... },
... {
... ProductName:"Product-2",
... "ProductPrice":500
... },
... {
... ProductName:"Product-3",
... "ProductPrice":2000
... },
... {
... ProductName:"Product-4",
... "ProductPrice":3000
... }
... ]
... }
... );
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo641.find();
This will produce the following output −
{
"_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
[
{ "ProductName" : "Product-1", "ProductPrice" : 1000 },
{ "ProductName" : "Product-2", "ProductPrice" : 500 },
{ "ProductName" : "Product-3", "ProductPrice" : 2000 },
{ "ProductName" : "Product-4", "ProductPrice" : 3000 }
]
}
Following is the query to get specific elements from embedded array in MongoDB
> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty();
This will produce the following output −
{
"ProductInformation" : {
"ProductName" : "Product-1",
"ProductPrice" : 1000
}
}
{
"ProductInformation" : {
"ProductName" : "Product-3",
"ProductPrice" : 2000
}
} | [
{
"code": null,
"e": 1287,
"s": 1187,
"text": "To get specific elements, use $match with dot notation. Let us create a collection with documents −"
},
{
"code": null,
"e": 1905,
"s": 1287,
"text": "> db.demo641.insert(\n... {\n... ProductId:101,\n... \"ProductInformation\":\n... ( [\n... {\n... ProductName:\"Product-1\",\n... \"ProductPrice\":1000\n... },\n... {\n... ProductName:\"Product-2\",\n... \"ProductPrice\":500\n... },\n... {\n... ProductName:\"Product-3\",\n... \"ProductPrice\":2000\n... },\n... {\n... ProductName:\"Product-4\",\n... \"ProductPrice\":3000\n... }\n... ]\n... }\n... );\nWriteResult({ \"nInserted\" : 1 })"
},
{
"code": null,
"e": 1978,
"s": 1905,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1999,
"s": 1978,
"text": "> db.demo641.find();"
},
{
"code": null,
"e": 2040,
"s": 1999,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2392,
"s": 2040,
"text": "{\n \"_id\" : ObjectId(\"5e9c31d46c954c74be91e6e2\"), \"ProductId\" : 101, \"ProductInformation\" :\n [\n { \"ProductName\" : \"Product-1\", \"ProductPrice\" : 1000 },\n { \"ProductName\" : \"Product-2\", \"ProductPrice\" : 500 },\n { \"ProductName\" : \"Product-3\", \"ProductPrice\" : 2000 },\n { \"ProductName\" : \"Product-4\", \"ProductPrice\" : 3000 }\n ] \n}"
},
{
"code": null,
"e": 2471,
"s": 2392,
"text": "Following is the query to get specific elements from embedded array in MongoDB"
},
{
"code": null,
"e": 2674,
"s": 2471,
"text": "> db.demo641.aggregate([\n... {$unwind: \"$ProductInformation\"},\n... {$match: { \"ProductInformation.ProductPrice\": {$in :[1000, 2000]}} },\n... {$project: {_id: 0, ProductInformation: 1} }\n... ]).pretty();"
},
{
"code": null,
"e": 2715,
"s": 2674,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2915,
"s": 2715,
"text": "{\n \"ProductInformation\" : {\n \"ProductName\" : \"Product-1\",\n \"ProductPrice\" : 1000\n }\n}\n{\n \"ProductInformation\" : {\n \"ProductName\" : \"Product-3\",\n \"ProductPrice\" : 2000\n }\n}"
}
] |
Python Seaborn Tutorial | 02 Mar, 2022
Seaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.
In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of seaborn basics, concepts, and different graphs that can be plotted.
Table Of Content
Getting Started
Using Seaborn with Matplotlib
Customizing Seaborn Plots Changing Figure AestheticRemoval of SpinesChanging the figure SizeScaling the plotsSetting the Style Temporarily
Changing Figure Aesthetic
Removal of Spines
Changing the figure Size
Scaling the plots
Setting the Style Temporarily
Color Palette Diverging Color PaletteSequential Color PaletteSetting the default Color Palette
Diverging Color Palette
Sequential Color Palette
Setting the default Color Palette
Multiple plots with Seaborn Using MatplotlibUsing Seaborn
Using Matplotlib
Using Seaborn
Creating Different Types of Plots Relational PlotsCategorical PlotsDistribution PlotsRegression Plots
Relational Plots
Categorical Plots
Distribution Plots
Regression Plots
More Gaphs in Seaborn
More Topics on Seaborn
Recent articles on Seaborn !!
First of all, let us install Seaborn. Seaborn can be installed using the pip. Type the below command in the terminal.
pip install seaborn
In the terminal, it will look like this –
After the installation is completed you will get a successfully installed message at the end of the terminal as shown below.
Note: Seaborn has the following dependencies –
Python 2.7 or 3.4+
numpy
scipy
pandas
matplotlib
After the installation let us see an example of a simple plot using Seaborn. We will be plotting a simple line plot using the iris dataset. Iris dataset contains five columns such as Petal Length, Petal Width, Sepal Length, Sepal Width and Species Type. Iris is a flowering plant, the researchers have measured various features of the different iris flowers and recorded them digitally.
Example:
Python3
# importing packages import seaborn as sns # loading dataset data = sns.load_dataset("iris") # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data)
Output:
In the above example, a simple line plot is created using the lineplot() method. Do not worry about these functions as we will be discussing them in detail in the below sections. Now after going through a simple example let us see a brief introduction about the Seaborn. Refer to the below articles to get detailed information about the same.
Introduction to Seaborn – Python
Plotting graph using Seaborn
In the introduction, you must have read that Seaborn is built on the top of Matplotlib. It means that Seaborn can be used with Matplotlib.
Using both Matplotlib and Seaborn together is a very simple process. We just have to invoke the Seaborn Plotting function as normal, and then we can use Matplotlib’s customization function.
Example 1: We will be using the above example and will add the title to the plot using the Matplotlib.
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data) # setting the title using Matplotlibplt.title('Title using Matplotlib Function') plt.show()
Output:
Example 2: Setting the xlim and ylim
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data) # setting the x limit of the plotplt.xlim(5) plt.show()
Output:
Seaborn comes with some customized themes and a high-level interface for customizing the looks of the graphs. Consider the above example where the default of the Seaborn is used. It still looks nice and pretty but we can customize the graph according to our own needs. So let’s see the styling of plots in detail.
set_style() method is used to set the aesthetic of the plot. It means it affects things like the color of the axes, whether the grid is active or not, or other aesthetic elements. There are five themes available in Seaborn.
darkgrid
whitegrid
dark
white
ticks
Syntax:
set_style(style=None, rc=None)
Example: Using the dark theme
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data) # changing the theme to darksns.set_style("dark")plt.show()
Output:
Spines are the lines noting the data boundaries and connecting the axis tick marks. It can be removed using the despine() method.
Syntax:
sns.despine(left = True)
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data) # Removing the spinessns.despine()plt.show()
Output:
The figure size can be changed using the figure() method of Matplotlib. figure() method creates a new figure of the specified size passed in the figsize parameter.
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") # changing the figure sizeplt.figure(figsize = (2, 4)) # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data) # Removing the spinessns.despine() plt.show()
Output:
It can be done using the set_context() method. It allows us to override default parameters. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The base context is “notebook”, and the other contexts are “paper”, “talk”, and “poster”. font_scale sets the font size.
Syntax:
set_context(context=None, font_scale=1, rc=None)
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data) # Setting the scale of the plotsns.set_context("paper") plt.show()
Output:
axes_style() method is used to set the style temporarily. It is used along with the with statement.
Syntax:
axes_style(style=None, rc=None)
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") def plot(): sns.lineplot(x="sepal_length", y="sepal_width", data=data) with sns.axes_style('darkgrid'): # Adding the subplot plt.subplot(211) plot() plt.subplot(212)plot()
Output:
Refer to the below article for detailed information about styling Seaborn Plot.
Seaborn | Style And Color
Colormaps are used to visualize plots effectively and easily. One might use different sorts of colormaps for different kinds of plots. color_palette() method is used to give colors to the plot. Another function palplot() is used to deal with the color palettes and plots the color palette as a horizontal array.
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # current colot palettepalette = sns.color_palette() # plots the color palette as a# horizontal arraysns.palplot(palette) plt.show()
Output:
This type of color palette uses two different colors where each color depicts different points ranging from a common point in either direction. Consider a range of -10 to 10 so the value from -10 to 0 takes one color and values from 0 to 10 take another.
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # current colot palettepalette = sns.color_palette('PiYG', 11) # diverging color palettesns.palplot(palette) plt.show()
Output:
In the above example, we have used an in-built diverging color palette which shows 11 different points of color. The color on the left shows pink color and color on the right shows green color.
A sequential palette is used where the distribution ranges from a lower value to a higher value. To do this add the character ‘s’ to the color passed in the color palette.
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # current colot palettepalette = sns.color_palette('Greens', 11) # sequential color palettesns.palplot(palette) plt.show()
Output:
set_palette() method is used to set the default color palette for all the plots. The arguments for both color_palette() and set_palette() is same. set_palette() changes the default matplotlib parameters.
Example:
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") def plot(): sns.lineplot(x="sepal_length", y="sepal_width", data=data) # setting the default color palettesns.set_palette('vlag')plt.subplot(211) # plotting with the color palette# as vlagplot() # setting another default color palettesns.set_palette('Accent')plt.subplot(212)plot() plt.show()
Output:
Refer to the below article to get detailed information about the color palette.
Seaborn – Color Palette
You might have seen multiple plots in the above examples and some of you might have got confused. Don’t worry we will cover multiple plots in this section. Multiple plots in Seaborn can also be created using the Matplotlib as well as Seaborn also provides some functions for the same.
Matplotlib provides various functions for plotting subplots. Some of them are add_axes(), subplot(), and subplot2grid(). Let’s see an example of each function for better understanding.
Example 1: Using add_axes() method
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") def graph(): sns.lineplot(x="sepal_length", y="sepal_width", data=data) # Creating a new figure with width = 5 inches# and height = 4 inchesfig = plt.figure(figsize =(5, 4)) # Creating first axes for the figureax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # plotting the graphgraph() # Creating second axes for the figureax2 = fig.add_axes([0.5, 0.5, 0.3, 0.3]) # plotting the graphgraph() plt.show()
Output:
Example 2: Using subplot() method
Python3
# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") def graph(): sns.lineplot(x="sepal_length", y="sepal_width", data=data) # Adding the subplot at the specified# grid positionplt.subplot(121)graph() # Adding the subplot at the specified# grid positionplt.subplot(122)graph() plt.show()
Output:
Example 3: Using subplot2grid() method
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") def graph(): sns.lineplot(x="sepal_length", y="sepal_width", data=data) # adding the subplotsaxes1 = plt.subplot2grid ( (7, 1), (0, 0), rowspan = 2, colspan = 1) graph() axes2 = plt.subplot2grid ( (7, 1), (2, 0), rowspan = 2, colspan = 1) graph() axes3 = plt.subplot2grid ( (7, 1), (4, 0), rowspan = 2, colspan = 1)graph()
Output:
Seaborn also provides some functions for plotting multiple plots. Let’s see them in detail
Method 1: Using FacetGrid() method
FacetGrid class helps in visualizing distribution of one variable as well as the relationship between multiple variables separately within subsets of your dataset using multiple panels.
A FacetGrid can be drawn with up to three dimensions ? row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.
FacetGrid object takes a dataframe as input and the names of the variables that will form the row, column, or hue dimensions of the grid. The variables should be categorical and the data at each level of the variable will be used for a facet along that axis.
Syntax:
seaborn.FacetGrid( data, \*\*kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") plot = sns.FacetGrid(data, col="species")plot.map(plt.plot, "sepal_width") plt.show()
Output:
Method 2: Using PairGrid() method
Subplot grid for plotting pairwise relationships in a dataset.
This class maps each variable in a dataset onto a column and row in a grid of multiple axes. Different axes-level plotting functions can be used to draw bivariate plots in the upper and lower triangles, and the marginal distribution of each variable can be shown on the diagonal.
It can also represent an additional level of conventionalization with the hue parameter, which plots different subsets of data in different colors. This uses color to resolve elements on a third dimension, but only draws subsets on top of each other and will not tailor the hue parameter for the specific visualization the way that axes-level functions that accept hue will.
Syntax:
seaborn.PairGrid( data, \*\*kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("flights") plot = sns.PairGrid(data)plot.map(plt.plot) plt.show()
Output:
Refer to the below articles to get detailed information about the multiple plots
Python – seaborn.FacetGrid() method
Python – seaborn.PairGrid() method
Relational plots are used for visualizing the statistical relationship between the data points. Visualization is necessary because it allows the human to see trends and patterns in the data. The process of understanding how the variables in the dataset relate each other and their relationships are termed as Statistical analysis. Refer to the below articles for detailed information.
Relational plots in Seaborn – Part I
Relational plots in Seaborn – Part II
There are different types of Relational Plots. We will discuss each of them in detail –
This function provides us the access to some other different axes-level functions which shows the relationships between two variables with semantic mappings of subsets. It is plotted using the relplot() method.
Syntax:
seaborn.relplot(x=None, y=None, data=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") # creating the relplotsns.relplot(x='sepal_width', y='species', data=data) plt.show()
Output:
The scatter plot is a mainstay of statistical visualization. It depicts the joint distribution of two variables using a cloud of points, where each point represents an observation in the dataset. This depiction allows the eye to infer a substantial amount of information about whether there is any meaningful relationship between them. It is plotted using the scatterplot() method.
Syntax:
seaborn.scatterplot(x=None, y=None, data=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.scatterplot(x='sepal_length', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about Scatter plot.
Scatterplot using Seaborn in Python
Visualizing Relationship between variables with scatter plots in Seaborn
How To Make Scatter Plot with Regression Line using Seaborn in Python?
Scatter Plot with Marginal Histograms in Python with Seaborn
For certain datasets, you may want to consider changes as a function of time in one variable, or as a similarly continuous variable. In this case, drawing a line-plot is a better option. It is plotted using the lineplot() method.
Syntax:
seaborn.lineplot(x=None, y=None, data=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.lineplot(x='sepal_length', y='species', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about line plot.
seaborn.lineplot() method in Python
Data Visualization with Seaborn Line Plot
Creating A Time Series Plot With Seaborn And Pandas
How to Make a Time Series Plot with Rolling Average in Python?
Categorical Plots are used where we have to visualize relationship between two numerical values. A more specialized approach can be used if one of the main variable is categorical which means such variables that take on a fixed and limited number of possible values.
Refer to the below articles to get detailed information.
Categorical Plots
There are various types of categorical plots let’s discuss each one them in detail.
A barplot is basically used to aggregate the categorical data according to some methods and by default its the mean. It can also be understood as a visualization of the group by action. To use this plot we choose a categorical column for the x axis and a numerical column for the y axis and we see that it creates a plot taking a mean per categorical column. It can be created using the barplot() method.
Syntax:
barplot([x, y, hue, data, order, hue_order, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.barplot(x='species', y='sepal_length', data=data)plt.show()
Output:
Refer to the below article to get detailed information about the topic.
Seaborn.barplot() method in Python
Barplot using seaborn in Python
Seaborn – Sort Bars in Barplot
A countplot basically counts the categories and returns a count of their occurrences. It is one of the most simple plots provided by the seaborn library. It can be created using the countplot() method.
Syntax:
countplot([x, y, hue, data, order, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.countplot(x='species', data=data)plt.show()
Output:
Refer to the below articles t get detailed information about the count plot.
Countplot using seaborn in Python
A boxplot is sometimes known as the box and whisker plot.It shows the distribution of the quantitative data that represents the comparisons between variables. boxplot shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution i.e. the dots indicating the presence of outliers. It is created using the boxplot() method.
Syntax:
boxplot([x, y, hue, data, order, hue_order, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.boxplot(x='species', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about box plot.
Boxplot using Seaborn in Python
Horizontal Boxplots with Seaborn in Python
How To Use Seaborn Color Palette to Color Boxplot?
Seaborn – Coloring Boxplots with Palettes
How to Show Mean on Boxplot using Seaborn in Python?
Sort Boxplot by Mean with Seaborn in Python
How To Manually Order Boxplot in Seaborn?
Grouped Boxplots in Python with Seaborn
Horizontal Boxplots with Points using Seaborn in Python
How to Make Boxplots with Data Points using Seaborn in Python?
Box plot visualization with Pandas and Seaborn
It is similar to the boxplot except that it provides a higher, more advanced visualization and uses the kernel density estimation to give a better description about the data distribution. It is created using the violinplot() method.
Syntax:
violinplot([x, y, hue, data, order, ...]
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.violinplot(x='species', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about violin plot.
Violinplot using Seaborn in Python
How to Make Horizontal Violin Plot with Seaborn in Python?
Make Violinplot with data points using Seaborn
How To Make Violinpot with data points in Seaborn?
How to Make Grouped Violinplot with Seaborn in Python?
It basically creates a scatter plot based on the category. It is created using the stripplot() method.
Syntax:
stripplot([x, y, hue, data, order, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.stripplot(x='species', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to detailed information about strip plot.
Stripplot using Seaborn in Python
Swarmplot is very similar to the stripplot except the fact that the points are adjusted so that they do not overlap.Some people also like combining the idea of a violin plot and a stripplot to form this plot. One drawback to using swarmplot is that sometimes they dont scale well to really large numbers and takes a lot of computation to arrange them. So in case we want to visualize a swarmplot properly we can plot it on top of a violinplot. It is plotted using the swarmplot() method.
Syntax:
swarmplot([x, y, hue, data, order, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.swarmplot(x='species', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about swarmplot.
Python – seaborn.swarmplot() method
Swarmplot using Seaborn in Python
Factorplot is the most general of all these plots and provides a parameter called kind to choose the kind of plot we want thus saving us from the trouble of writing these plots separately. The kind parameter can be bar, violin, swarm etc. It is plotted using the factorplot() method.
Syntax:
sns.factorplot([x, y, hue, data, row, col, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.factorplot(x='species', y='sepal_width', data=data)plt.show()
Refer to the below articles to get dtailed information about the factor plot.
Python – seaborn.factorplot() method
Plotting different types of plots using Factor plot in seaborn
Distribution Plots are used for examining univariate and bivariate distributions meaning such distributions that involve one variable or two discrete variables.
Refer to the below article to get detailed informaon about the distribution plots.
Distribution Plots
There are various types of distribution plots let’s discuss each one them in detail.
A histogram is basically used to represent data provided in a form of some groups.It is accurate method for the graphical representation of numerical data distribution. It can be plotted using the histplot() function.
Syntax:
histplot(data=None, *, x=None, y=None, hue=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.histplot(x='species', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about histplot.
How to Make Histograms with Density Plots with Seaborn histplot?
How to Add Outline or Edge Color to Histogram in Seaborn?
Scatter Plot with Marginal Histograms in Python with Seaborn
Distplot is used basically for univariant set of observations and visualizes it through a histogram i.e. only one observation and hence we choose one particular column of the dataset. It is potted using the distplot() method.
Syntax:
distplot(a[, bins, hist, kde, rug, fit, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.distplot(data['sepal_width'])plt.show()
Output:
Jointplot is used to draw a plot of two variables with bivariate and univariate graphs. It basically combines two different plots. It is plotted using the jointplot() method.
Syntax:
jointplot(x, y[, data, kind, stat_func, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.jointplot(x='species', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about the topic.
Python – seaborn.jointplot() method
Pairplot represents pairwise relation across the entire dataframe and supports an additional argument called hue for categorical separation. What it does basically is create a jointplot between every possible numerical column and takes a while if the dataframe is really huge. It is plotted using the pairplot() method.
Syntax:
pairplot(data[, hue, hue_order, palette, ...])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.pairplot(data=data, hue='species')plt.show()
Output:
Refer to the below articles to get detailed information about the pairplot.
Python – seaborn.pairplot() method
Data visualization with Pairplot Seaborn and Pandas
Rugplot plots datapoints in an array as sticks on an axis.Just like a distplot it takes a single column. Instead of drawing a histogram it creates dashes all across the plot. If you compare it with the joinplot you can see that what a jointplot does is that it counts the dashes and shows it as bins. It is plotted using the rugplot() method.
Syntax:
rugplot(a[, height, axis, ax])
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.rugplot(data=data)plt.show()
Output:
KDE Plot described as Kernel Density Estimate is used for visualizing the Probability Density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can also plot a single graph for multiple samples which helps in more efficient data visualization.
Syntax:
seaborn.kdeplot(x=None, *, y=None, vertical=False, palette=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") sns.kdeplot(x='sepal_length', y='sepal_width', data=data)plt.show()
Output:
Refer to the below articles to getdetailed information about the topic.
Seaborn Kdeplot – A Comprehensive Guide
KDE Plot Visualization with Pandas and Seaborn
The regression plots are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses. Regression plots as the name suggests creates a regression line between two parameters and helps to visualize their linear relationships.
Refer to the below article to get detailed information about the regression plots.
Regression Plots
there are two main functions that are used to draw linear regression models. These functions are lmplot(), and regplot(), are closely related to each other. They even share their core functionality.
lmplot() method can be understood as a function that basically creates a linear model plot. It creates a scatter plot with a linear fit on top of it.
Syntax:
seaborn.lmplot(x, y, data, hue=None, col=None, row=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") sns.lmplot(x='total_bill', y='tip', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about the lmplot.
Python – seaborn.lmplot() method
regplot() method is also similar to lmplot which creates linear regression model.
Syntax:
seaborn.regplot( x, y, data=None, x_estimator=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") sns.regplot(x='total_bill', y='tip', data=data)plt.show()
Output:
Refer to the below articles to get detailed information about regplot.
Python – seaborn.regplot() method
Note: The difference between both the function is that regplot accepts the x, y variables in different format including NumPy arrays, Pandas objects, whereas, the lmplot only accepts the value as strings.
A matrix plot means plotting matrix data where color coded diagrams shows rows data, column data and values. It can shown using the heatmap and clustermap.
Refer to the below articles to get detailed information about the matrix plots.
Matrix plots
Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. In this, to represent more common values or higher activities brighter colors basically reddish colors are used and to represent less common or activity values, darker colors are preferred. it can be plotted using the heatmap() function.
Syntax:
seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # correlation between the different parameters tc = data.corr() sns.heatmap(tc)plt.show()
Output:
Refer to the below articles to get detailed information about the heatmap.
Seaborn Heatmap – A comprehensive guide
How to create a seaborn correlation heatmap in Python?
How to create a Triangle Correlation Heatmap in seaborn – Python?
ColorMaps in Seaborn HeatMaps
How to change the colorbar size of a seaborn heatmap figure in Python?
How to add a frame to a seaborn heatmap figure in Python?
How to increase the size of the annotations of a seaborn heatmap in Python?
The clustermap() function of seaborn plots the hierarchically-clustered heatmap of the given matrix dataset. Clustering simply means grouping data based on relationship among the variables in the data.
Syntax:
clustermap(data, *, pivot_kws=None, **kwargs)
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # correlation between the different parameters tc = data.corr() sns.clustermap(tc)plt.show()
Output:
Refer to the below articles to get detailed information about clustermap.
Hierarchically-clustered Heatmap in Python with Seaborn Clustermap
Exploring Correlation in Python
Seaborn – Bubble Plot
Python – seaborn.residplot() method
Python – seaborn.boxenplot() method
Python – seaborn.pointplot() method
Python Seaborn – Catplot
How to Make Countplot or barplot with Seaborn Catplot?
How To Make Grouped Boxplot with Seaborn Catplot?
Python Seaborn – Strip plot illustration using Catplot
How To Make Simple Facet Plots with Seaborn Catplot in Python?
How To Make Ridgeline plot in Python with Seaborn?
Change Axis Labels, Set Title and Figure Size to Plots with Seaborn
How To Place Legend Outside the Plot with Seaborn in Python?
How to Plot a Confidence Interval in Python?
Creating A Time Series Plot With Seaborn And Pandas
How to Make a Time Series Plot with Rolling Average in Python?
How To Add Regression Line Per Group with Seaborn in Python?
Data Visualization with Python Seaborn and Pandas
Data Visualization in Python using Matplotlib and Seaborn
Visualizing ML DataSet Through Seaborn Plots and Matplotlib
as5853535
prachisoda1234
sumitgumber28
varshagumber28
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "Seaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive."
},
{
"code": null,
"e": 398,
"s": 230,
"text": "In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of seaborn basics, concepts, and different graphs that can be plotted."
},
{
"code": null,
"e": 416,
"s": 398,
"text": "Table Of Content "
},
{
"code": null,
"e": 432,
"s": 416,
"text": "Getting Started"
},
{
"code": null,
"e": 462,
"s": 432,
"text": "Using Seaborn with Matplotlib"
},
{
"code": null,
"e": 601,
"s": 462,
"text": "Customizing Seaborn Plots Changing Figure AestheticRemoval of SpinesChanging the figure SizeScaling the plotsSetting the Style Temporarily"
},
{
"code": null,
"e": 627,
"s": 601,
"text": "Changing Figure Aesthetic"
},
{
"code": null,
"e": 645,
"s": 627,
"text": "Removal of Spines"
},
{
"code": null,
"e": 670,
"s": 645,
"text": "Changing the figure Size"
},
{
"code": null,
"e": 688,
"s": 670,
"text": "Scaling the plots"
},
{
"code": null,
"e": 718,
"s": 688,
"text": "Setting the Style Temporarily"
},
{
"code": null,
"e": 813,
"s": 718,
"text": "Color Palette Diverging Color PaletteSequential Color PaletteSetting the default Color Palette"
},
{
"code": null,
"e": 837,
"s": 813,
"text": "Diverging Color Palette"
},
{
"code": null,
"e": 862,
"s": 837,
"text": "Sequential Color Palette"
},
{
"code": null,
"e": 896,
"s": 862,
"text": "Setting the default Color Palette"
},
{
"code": null,
"e": 954,
"s": 896,
"text": "Multiple plots with Seaborn Using MatplotlibUsing Seaborn"
},
{
"code": null,
"e": 971,
"s": 954,
"text": "Using Matplotlib"
},
{
"code": null,
"e": 985,
"s": 971,
"text": "Using Seaborn"
},
{
"code": null,
"e": 1087,
"s": 985,
"text": "Creating Different Types of Plots Relational PlotsCategorical PlotsDistribution PlotsRegression Plots"
},
{
"code": null,
"e": 1104,
"s": 1087,
"text": "Relational Plots"
},
{
"code": null,
"e": 1122,
"s": 1104,
"text": "Categorical Plots"
},
{
"code": null,
"e": 1141,
"s": 1122,
"text": "Distribution Plots"
},
{
"code": null,
"e": 1158,
"s": 1141,
"text": "Regression Plots"
},
{
"code": null,
"e": 1180,
"s": 1158,
"text": "More Gaphs in Seaborn"
},
{
"code": null,
"e": 1203,
"s": 1180,
"text": "More Topics on Seaborn"
},
{
"code": null,
"e": 1235,
"s": 1205,
"text": "Recent articles on Seaborn !!"
},
{
"code": null,
"e": 1355,
"s": 1237,
"text": "First of all, let us install Seaborn. Seaborn can be installed using the pip. Type the below command in the terminal."
},
{
"code": null,
"e": 1377,
"s": 1357,
"text": "pip install seaborn"
},
{
"code": null,
"e": 1422,
"s": 1379,
"text": "In the terminal, it will look like this – "
},
{
"code": null,
"e": 1549,
"s": 1424,
"text": "After the installation is completed you will get a successfully installed message at the end of the terminal as shown below."
},
{
"code": null,
"e": 1601,
"s": 1553,
"text": "Note: Seaborn has the following dependencies – "
},
{
"code": null,
"e": 1622,
"s": 1603,
"text": "Python 2.7 or 3.4+"
},
{
"code": null,
"e": 1628,
"s": 1622,
"text": "numpy"
},
{
"code": null,
"e": 1634,
"s": 1628,
"text": "scipy"
},
{
"code": null,
"e": 1641,
"s": 1634,
"text": "pandas"
},
{
"code": null,
"e": 1652,
"s": 1641,
"text": "matplotlib"
},
{
"code": null,
"e": 2039,
"s": 1652,
"text": "After the installation let us see an example of a simple plot using Seaborn. We will be plotting a simple line plot using the iris dataset. Iris dataset contains five columns such as Petal Length, Petal Width, Sepal Length, Sepal Width and Species Type. Iris is a flowering plant, the researchers have measured various features of the different iris flowers and recorded them digitally."
},
{
"code": null,
"e": 2050,
"s": 2041,
"text": "Example:"
},
{
"code": null,
"e": 2060,
"s": 2052,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns # loading dataset data = sns.load_dataset(\"iris\") # draw lineplot sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data)",
"e": 2232,
"s": 2060,
"text": null
},
{
"code": null,
"e": 2240,
"s": 2232,
"text": "Output:"
},
{
"code": null,
"e": 2583,
"s": 2240,
"text": "In the above example, a simple line plot is created using the lineplot() method. Do not worry about these functions as we will be discussing them in detail in the below sections. Now after going through a simple example let us see a brief introduction about the Seaborn. Refer to the below articles to get detailed information about the same."
},
{
"code": null,
"e": 2616,
"s": 2583,
"text": "Introduction to Seaborn – Python"
},
{
"code": null,
"e": 2645,
"s": 2616,
"text": "Plotting graph using Seaborn"
},
{
"code": null,
"e": 2785,
"s": 2645,
"text": "In the introduction, you must have read that Seaborn is built on the top of Matplotlib. It means that Seaborn can be used with Matplotlib. "
},
{
"code": null,
"e": 2975,
"s": 2785,
"text": "Using both Matplotlib and Seaborn together is a very simple process. We just have to invoke the Seaborn Plotting function as normal, and then we can use Matplotlib’s customization function."
},
{
"code": null,
"e": 3078,
"s": 2975,
"text": "Example 1: We will be using the above example and will add the title to the plot using the Matplotlib."
},
{
"code": null,
"e": 3086,
"s": 3078,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") # draw lineplot sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # setting the title using Matplotlibplt.title('Title using Matplotlib Function') plt.show()",
"e": 3385,
"s": 3086,
"text": null
},
{
"code": null,
"e": 3396,
"s": 3388,
"text": "Output:"
},
{
"code": null,
"e": 3437,
"s": 3400,
"text": "Example 2: Setting the xlim and ylim"
},
{
"code": null,
"e": 3447,
"s": 3439,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") # draw lineplot sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # setting the x limit of the plotplt.xlim(5) plt.show()",
"e": 3710,
"s": 3447,
"text": null
},
{
"code": null,
"e": 3721,
"s": 3713,
"text": "Output:"
},
{
"code": null,
"e": 4039,
"s": 3725,
"text": "Seaborn comes with some customized themes and a high-level interface for customizing the looks of the graphs. Consider the above example where the default of the Seaborn is used. It still looks nice and pretty but we can customize the graph according to our own needs. So let’s see the styling of plots in detail."
},
{
"code": null,
"e": 4265,
"s": 4041,
"text": "set_style() method is used to set the aesthetic of the plot. It means it affects things like the color of the axes, whether the grid is active or not, or other aesthetic elements. There are five themes available in Seaborn."
},
{
"code": null,
"e": 4276,
"s": 4267,
"text": "darkgrid"
},
{
"code": null,
"e": 4286,
"s": 4276,
"text": "whitegrid"
},
{
"code": null,
"e": 4291,
"s": 4286,
"text": "dark"
},
{
"code": null,
"e": 4297,
"s": 4291,
"text": "white"
},
{
"code": null,
"e": 4303,
"s": 4297,
"text": "ticks"
},
{
"code": null,
"e": 4311,
"s": 4303,
"text": "Syntax:"
},
{
"code": null,
"e": 4344,
"s": 4313,
"text": "set_style(style=None, rc=None)"
},
{
"code": null,
"e": 4374,
"s": 4344,
"text": "Example: Using the dark theme"
},
{
"code": null,
"e": 4384,
"s": 4376,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") # draw lineplot sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # changing the theme to darksns.set_style(\"dark\")plt.show()",
"e": 4650,
"s": 4384,
"text": null
},
{
"code": null,
"e": 4661,
"s": 4653,
"text": "Output:"
},
{
"code": null,
"e": 4795,
"s": 4665,
"text": "Spines are the lines noting the data boundaries and connecting the axis tick marks. It can be removed using the despine() method."
},
{
"code": null,
"e": 4805,
"s": 4797,
"text": "Syntax:"
},
{
"code": null,
"e": 4832,
"s": 4807,
"text": "sns.despine(left = True)"
},
{
"code": null,
"e": 4841,
"s": 4832,
"text": "Example:"
},
{
"code": null,
"e": 4851,
"s": 4843,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") # draw lineplot sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # Removing the spinessns.despine()plt.show()",
"e": 5102,
"s": 4851,
"text": null
},
{
"code": null,
"e": 5113,
"s": 5105,
"text": "Output:"
},
{
"code": null,
"e": 5281,
"s": 5117,
"text": "The figure size can be changed using the figure() method of Matplotlib. figure() method creates a new figure of the specified size passed in the figsize parameter."
},
{
"code": null,
"e": 5292,
"s": 5283,
"text": "Example:"
},
{
"code": null,
"e": 5302,
"s": 5294,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") # changing the figure sizeplt.figure(figsize = (2, 4)) # draw lineplot sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # Removing the spinessns.despine() plt.show()",
"e": 5611,
"s": 5302,
"text": null
},
{
"code": null,
"e": 5622,
"s": 5614,
"text": "Output:"
},
{
"code": null,
"e": 5954,
"s": 5626,
"text": "It can be done using the set_context() method. It allows us to override default parameters. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The base context is “notebook”, and the other contexts are “paper”, “talk”, and “poster”. font_scale sets the font size."
},
{
"code": null,
"e": 5964,
"s": 5956,
"text": "Syntax:"
},
{
"code": null,
"e": 6015,
"s": 5966,
"text": "set_context(context=None, font_scale=1, rc=None)"
},
{
"code": null,
"e": 6024,
"s": 6015,
"text": "Example:"
},
{
"code": null,
"e": 6034,
"s": 6026,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") # draw lineplot sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # Setting the scale of the plotsns.set_context(\"paper\") plt.show()",
"e": 6308,
"s": 6034,
"text": null
},
{
"code": null,
"e": 6319,
"s": 6311,
"text": "Output:"
},
{
"code": null,
"e": 6423,
"s": 6323,
"text": "axes_style() method is used to set the style temporarily. It is used along with the with statement."
},
{
"code": null,
"e": 6433,
"s": 6425,
"text": "Syntax:"
},
{
"code": null,
"e": 6467,
"s": 6435,
"text": "axes_style(style=None, rc=None)"
},
{
"code": null,
"e": 6476,
"s": 6467,
"text": "Example:"
},
{
"code": null,
"e": 6486,
"s": 6478,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") def plot(): sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) with sns.axes_style('darkgrid'): # Adding the subplot plt.subplot(211) plot() plt.subplot(212)plot()",
"e": 6814,
"s": 6486,
"text": null
},
{
"code": null,
"e": 6825,
"s": 6817,
"text": "Output:"
},
{
"code": null,
"e": 6909,
"s": 6829,
"text": "Refer to the below article for detailed information about styling Seaborn Plot."
},
{
"code": null,
"e": 6937,
"s": 6911,
"text": "Seaborn | Style And Color"
},
{
"code": null,
"e": 7251,
"s": 6939,
"text": "Colormaps are used to visualize plots effectively and easily. One might use different sorts of colormaps for different kinds of plots. color_palette() method is used to give colors to the plot. Another function palplot() is used to deal with the color palettes and plots the color palette as a horizontal array."
},
{
"code": null,
"e": 7262,
"s": 7253,
"text": "Example:"
},
{
"code": null,
"e": 7272,
"s": 7264,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # current colot palettepalette = sns.color_palette() # plots the color palette as a# horizontal arraysns.palplot(palette) plt.show()",
"e": 7483,
"s": 7272,
"text": null
},
{
"code": null,
"e": 7494,
"s": 7486,
"text": "Output:"
},
{
"code": null,
"e": 7751,
"s": 7496,
"text": "This type of color palette uses two different colors where each color depicts different points ranging from a common point in either direction. Consider a range of -10 to 10 so the value from -10 to 0 takes one color and values from 0 to 10 take another."
},
{
"code": null,
"e": 7762,
"s": 7753,
"text": "Example:"
},
{
"code": null,
"e": 7772,
"s": 7764,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # current colot palettepalette = sns.color_palette('PiYG', 11) # diverging color palettesns.palplot(palette) plt.show()",
"e": 7970,
"s": 7772,
"text": null
},
{
"code": null,
"e": 7981,
"s": 7973,
"text": "Output:"
},
{
"code": null,
"e": 8177,
"s": 7983,
"text": "In the above example, we have used an in-built diverging color palette which shows 11 different points of color. The color on the left shows pink color and color on the right shows green color."
},
{
"code": null,
"e": 8351,
"s": 8179,
"text": "A sequential palette is used where the distribution ranges from a lower value to a higher value. To do this add the character ‘s’ to the color passed in the color palette."
},
{
"code": null,
"e": 8363,
"s": 8353,
"text": "Example: "
},
{
"code": null,
"e": 8373,
"s": 8365,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # current colot palettepalette = sns.color_palette('Greens', 11) # sequential color palettesns.palplot(palette) plt.show()",
"e": 8574,
"s": 8373,
"text": null
},
{
"code": null,
"e": 8585,
"s": 8577,
"text": "Output:"
},
{
"code": null,
"e": 8793,
"s": 8589,
"text": "set_palette() method is used to set the default color palette for all the plots. The arguments for both color_palette() and set_palette() is same. set_palette() changes the default matplotlib parameters."
},
{
"code": null,
"e": 8804,
"s": 8795,
"text": "Example:"
},
{
"code": null,
"e": 8814,
"s": 8806,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") def plot(): sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # setting the default color palettesns.set_palette('vlag')plt.subplot(211) # plotting with the color palette# as vlagplot() # setting another default color palettesns.set_palette('Accent')plt.subplot(212)plot() plt.show()",
"e": 9242,
"s": 8814,
"text": null
},
{
"code": null,
"e": 9253,
"s": 9245,
"text": "Output:"
},
{
"code": null,
"e": 9337,
"s": 9257,
"text": "Refer to the below article to get detailed information about the color palette."
},
{
"code": null,
"e": 9363,
"s": 9339,
"text": "Seaborn – Color Palette"
},
{
"code": null,
"e": 9650,
"s": 9365,
"text": "You might have seen multiple plots in the above examples and some of you might have got confused. Don’t worry we will cover multiple plots in this section. Multiple plots in Seaborn can also be created using the Matplotlib as well as Seaborn also provides some functions for the same."
},
{
"code": null,
"e": 9837,
"s": 9652,
"text": "Matplotlib provides various functions for plotting subplots. Some of them are add_axes(), subplot(), and subplot2grid(). Let’s see an example of each function for better understanding."
},
{
"code": null,
"e": 9874,
"s": 9839,
"text": "Example 1: Using add_axes() method"
},
{
"code": null,
"e": 9884,
"s": 9876,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") def graph(): sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # Creating a new figure with width = 5 inches# and height = 4 inchesfig = plt.figure(figsize =(5, 4)) # Creating first axes for the figureax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # plotting the graphgraph() # Creating second axes for the figureax2 = fig.add_axes([0.5, 0.5, 0.3, 0.3]) # plotting the graphgraph() plt.show()",
"e": 10417,
"s": 9884,
"text": null
},
{
"code": null,
"e": 10428,
"s": 10420,
"text": "Output:"
},
{
"code": null,
"e": 10466,
"s": 10432,
"text": "Example 2: Using subplot() method"
},
{
"code": null,
"e": 10476,
"s": 10468,
"text": "Python3"
},
{
"code": "# importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset(\"iris\") def graph(): sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # Adding the subplot at the specified# grid positionplt.subplot(121)graph() # Adding the subplot at the specified# grid positionplt.subplot(122)graph() plt.show()",
"e": 10845,
"s": 10476,
"text": null
},
{
"code": null,
"e": 10856,
"s": 10848,
"text": "Output:"
},
{
"code": null,
"e": 10899,
"s": 10860,
"text": "Example 3: Using subplot2grid() method"
},
{
"code": null,
"e": 10909,
"s": 10901,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") def graph(): sns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data) # adding the subplotsaxes1 = plt.subplot2grid ( (7, 1), (0, 0), rowspan = 2, colspan = 1) graph() axes2 = plt.subplot2grid ( (7, 1), (2, 0), rowspan = 2, colspan = 1) graph() axes3 = plt.subplot2grid ( (7, 1), (4, 0), rowspan = 2, colspan = 1)graph()",
"e": 11368,
"s": 10909,
"text": null
},
{
"code": null,
"e": 11379,
"s": 11371,
"text": "Output:"
},
{
"code": null,
"e": 11474,
"s": 11383,
"text": "Seaborn also provides some functions for plotting multiple plots. Let’s see them in detail"
},
{
"code": null,
"e": 11511,
"s": 11476,
"text": "Method 1: Using FacetGrid() method"
},
{
"code": null,
"e": 11699,
"s": 11513,
"text": "FacetGrid class helps in visualizing distribution of one variable as well as the relationship between multiple variables separately within subsets of your dataset using multiple panels."
},
{
"code": null,
"e": 11974,
"s": 11699,
"text": "A FacetGrid can be drawn with up to three dimensions ? row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors."
},
{
"code": null,
"e": 12233,
"s": 11974,
"text": "FacetGrid object takes a dataframe as input and the names of the variables that will form the row, column, or hue dimensions of the grid. The variables should be categorical and the data at each level of the variable will be used for a facet along that axis."
},
{
"code": null,
"e": 12243,
"s": 12235,
"text": "Syntax:"
},
{
"code": null,
"e": 12282,
"s": 12245,
"text": "seaborn.FacetGrid( data, \\*\\*kwargs)"
},
{
"code": null,
"e": 12293,
"s": 12284,
"text": "Example:"
},
{
"code": null,
"e": 12303,
"s": 12295,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") plot = sns.FacetGrid(data, col=\"species\")plot.map(plt.plot, \"sepal_width\") plt.show()",
"e": 12514,
"s": 12303,
"text": null
},
{
"code": null,
"e": 12525,
"s": 12517,
"text": "Output:"
},
{
"code": null,
"e": 12563,
"s": 12529,
"text": "Method 2: Using PairGrid() method"
},
{
"code": null,
"e": 12628,
"s": 12565,
"text": "Subplot grid for plotting pairwise relationships in a dataset."
},
{
"code": null,
"e": 12908,
"s": 12628,
"text": "This class maps each variable in a dataset onto a column and row in a grid of multiple axes. Different axes-level plotting functions can be used to draw bivariate plots in the upper and lower triangles, and the marginal distribution of each variable can be shown on the diagonal."
},
{
"code": null,
"e": 13283,
"s": 12908,
"text": "It can also represent an additional level of conventionalization with the hue parameter, which plots different subsets of data in different colors. This uses color to resolve elements on a third dimension, but only draws subsets on top of each other and will not tailor the hue parameter for the specific visualization the way that axes-level functions that accept hue will."
},
{
"code": null,
"e": 13293,
"s": 13285,
"text": "Syntax:"
},
{
"code": null,
"e": 13331,
"s": 13295,
"text": "seaborn.PairGrid( data, \\*\\*kwargs)"
},
{
"code": null,
"e": 13342,
"s": 13333,
"text": "Example:"
},
{
"code": null,
"e": 13352,
"s": 13344,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"flights\") plot = sns.PairGrid(data)plot.map(plt.plot) plt.show()",
"e": 13535,
"s": 13352,
"text": null
},
{
"code": null,
"e": 13546,
"s": 13538,
"text": "Output:"
},
{
"code": null,
"e": 13631,
"s": 13550,
"text": "Refer to the below articles to get detailed information about the multiple plots"
},
{
"code": null,
"e": 13669,
"s": 13633,
"text": "Python – seaborn.FacetGrid() method"
},
{
"code": null,
"e": 13704,
"s": 13669,
"text": "Python – seaborn.PairGrid() method"
},
{
"code": null,
"e": 14093,
"s": 13708,
"text": "Relational plots are used for visualizing the statistical relationship between the data points. Visualization is necessary because it allows the human to see trends and patterns in the data. The process of understanding how the variables in the dataset relate each other and their relationships are termed as Statistical analysis. Refer to the below articles for detailed information."
},
{
"code": null,
"e": 14132,
"s": 14095,
"text": "Relational plots in Seaborn – Part I"
},
{
"code": null,
"e": 14170,
"s": 14132,
"text": "Relational plots in Seaborn – Part II"
},
{
"code": null,
"e": 14258,
"s": 14170,
"text": "There are different types of Relational Plots. We will discuss each of them in detail –"
},
{
"code": null,
"e": 14471,
"s": 14260,
"text": "This function provides us the access to some other different axes-level functions which shows the relationships between two variables with semantic mappings of subsets. It is plotted using the relplot() method."
},
{
"code": null,
"e": 14481,
"s": 14473,
"text": "Syntax:"
},
{
"code": null,
"e": 14537,
"s": 14483,
"text": "seaborn.relplot(x=None, y=None, data=None, **kwargs) "
},
{
"code": null,
"e": 14546,
"s": 14537,
"text": "Example:"
},
{
"code": null,
"e": 14556,
"s": 14548,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") # creating the relplotsns.relplot(x='sepal_width', y='species', data=data) plt.show()",
"e": 14767,
"s": 14556,
"text": null
},
{
"code": null,
"e": 14778,
"s": 14770,
"text": "Output:"
},
{
"code": null,
"e": 15162,
"s": 14780,
"text": "The scatter plot is a mainstay of statistical visualization. It depicts the joint distribution of two variables using a cloud of points, where each point represents an observation in the dataset. This depiction allows the eye to infer a substantial amount of information about whether there is any meaningful relationship between them. It is plotted using the scatterplot() method."
},
{
"code": null,
"e": 15172,
"s": 15164,
"text": "Syntax:"
},
{
"code": null,
"e": 15231,
"s": 15174,
"text": "seaborn.scatterplot(x=None, y=None, data=None, **kwargs)"
},
{
"code": null,
"e": 15240,
"s": 15231,
"text": "Example:"
},
{
"code": null,
"e": 15250,
"s": 15242,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.scatterplot(x='sepal_length', y='sepal_width', data=data)plt.show()",
"e": 15446,
"s": 15250,
"text": null
},
{
"code": null,
"e": 15457,
"s": 15449,
"text": "Output:"
},
{
"code": null,
"e": 15537,
"s": 15461,
"text": "Refer to the below articles to get detailed information about Scatter plot."
},
{
"code": null,
"e": 15575,
"s": 15539,
"text": "Scatterplot using Seaborn in Python"
},
{
"code": null,
"e": 15648,
"s": 15575,
"text": "Visualizing Relationship between variables with scatter plots in Seaborn"
},
{
"code": null,
"e": 15719,
"s": 15648,
"text": "How To Make Scatter Plot with Regression Line using Seaborn in Python?"
},
{
"code": null,
"e": 15780,
"s": 15719,
"text": "Scatter Plot with Marginal Histograms in Python with Seaborn"
},
{
"code": null,
"e": 16012,
"s": 15782,
"text": "For certain datasets, you may want to consider changes as a function of time in one variable, or as a similarly continuous variable. In this case, drawing a line-plot is a better option. It is plotted using the lineplot() method."
},
{
"code": null,
"e": 16022,
"s": 16014,
"text": "Syntax:"
},
{
"code": null,
"e": 16078,
"s": 16024,
"text": "seaborn.lineplot(x=None, y=None, data=None, **kwargs)"
},
{
"code": null,
"e": 16089,
"s": 16080,
"text": "Example:"
},
{
"code": null,
"e": 16099,
"s": 16091,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.lineplot(x='sepal_length', y='species', data=data)plt.show()",
"e": 16288,
"s": 16099,
"text": null
},
{
"code": null,
"e": 16299,
"s": 16291,
"text": "Output:"
},
{
"code": null,
"e": 16376,
"s": 16303,
"text": "Refer to the below articles to get detailed information about line plot."
},
{
"code": null,
"e": 16414,
"s": 16378,
"text": "seaborn.lineplot() method in Python"
},
{
"code": null,
"e": 16456,
"s": 16414,
"text": "Data Visualization with Seaborn Line Plot"
},
{
"code": null,
"e": 16508,
"s": 16456,
"text": "Creating A Time Series Plot With Seaborn And Pandas"
},
{
"code": null,
"e": 16571,
"s": 16508,
"text": "How to Make a Time Series Plot with Rolling Average in Python?"
},
{
"code": null,
"e": 16842,
"s": 16575,
"text": "Categorical Plots are used where we have to visualize relationship between two numerical values. A more specialized approach can be used if one of the main variable is categorical which means such variables that take on a fixed and limited number of possible values."
},
{
"code": null,
"e": 16901,
"s": 16844,
"text": "Refer to the below articles to get detailed information."
},
{
"code": null,
"e": 16921,
"s": 16903,
"text": "Categorical Plots"
},
{
"code": null,
"e": 17008,
"s": 16923,
"text": " There are various types of categorical plots let’s discuss each one them in detail."
},
{
"code": null,
"e": 17417,
"s": 17012,
"text": "A barplot is basically used to aggregate the categorical data according to some methods and by default its the mean. It can also be understood as a visualization of the group by action. To use this plot we choose a categorical column for the x axis and a numerical column for the y axis and we see that it creates a plot taking a mean per categorical column. It can be created using the barplot() method."
},
{
"code": null,
"e": 17427,
"s": 17419,
"text": "Syntax:"
},
{
"code": null,
"e": 17479,
"s": 17429,
"text": "barplot([x, y, hue, data, order, hue_order, ...])"
},
{
"code": null,
"e": 17490,
"s": 17481,
"text": "Example:"
},
{
"code": null,
"e": 17500,
"s": 17492,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.barplot(x='species', y='sepal_length', data=data)plt.show()",
"e": 17688,
"s": 17500,
"text": null
},
{
"code": null,
"e": 17699,
"s": 17691,
"text": "Output:"
},
{
"code": null,
"e": 17775,
"s": 17703,
"text": "Refer to the below article to get detailed information about the topic."
},
{
"code": null,
"e": 17812,
"s": 17777,
"text": "Seaborn.barplot() method in Python"
},
{
"code": null,
"e": 17844,
"s": 17812,
"text": "Barplot using seaborn in Python"
},
{
"code": null,
"e": 17875,
"s": 17844,
"text": "Seaborn – Sort Bars in Barplot"
},
{
"code": null,
"e": 18079,
"s": 17877,
"text": "A countplot basically counts the categories and returns a count of their occurrences. It is one of the most simple plots provided by the seaborn library. It can be created using the countplot() method."
},
{
"code": null,
"e": 18089,
"s": 18081,
"text": "Syntax:"
},
{
"code": null,
"e": 18132,
"s": 18091,
"text": "countplot([x, y, hue, data, order, ...])"
},
{
"code": null,
"e": 18143,
"s": 18134,
"text": "Example:"
},
{
"code": null,
"e": 18153,
"s": 18145,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.countplot(x='species', data=data)plt.show()",
"e": 18325,
"s": 18153,
"text": null
},
{
"code": null,
"e": 18336,
"s": 18328,
"text": "Output:"
},
{
"code": null,
"e": 18417,
"s": 18340,
"text": "Refer to the below articles t get detailed information about the count plot."
},
{
"code": null,
"e": 18453,
"s": 18419,
"text": "Countplot using seaborn in Python"
},
{
"code": null,
"e": 18813,
"s": 18455,
"text": "A boxplot is sometimes known as the box and whisker plot.It shows the distribution of the quantitative data that represents the comparisons between variables. boxplot shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution i.e. the dots indicating the presence of outliers. It is created using the boxplot() method."
},
{
"code": null,
"e": 18823,
"s": 18815,
"text": "Syntax:"
},
{
"code": null,
"e": 18875,
"s": 18825,
"text": "boxplot([x, y, hue, data, order, hue_order, ...])"
},
{
"code": null,
"e": 18886,
"s": 18877,
"text": "Example:"
},
{
"code": null,
"e": 18896,
"s": 18888,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.boxplot(x='species', y='sepal_width', data=data)plt.show()",
"e": 19083,
"s": 18896,
"text": null
},
{
"code": null,
"e": 19094,
"s": 19086,
"text": "Output:"
},
{
"code": null,
"e": 19170,
"s": 19098,
"text": "Refer to the below articles to get detailed information about box plot."
},
{
"code": null,
"e": 19204,
"s": 19172,
"text": "Boxplot using Seaborn in Python"
},
{
"code": null,
"e": 19247,
"s": 19204,
"text": "Horizontal Boxplots with Seaborn in Python"
},
{
"code": null,
"e": 19298,
"s": 19247,
"text": "How To Use Seaborn Color Palette to Color Boxplot?"
},
{
"code": null,
"e": 19340,
"s": 19298,
"text": "Seaborn – Coloring Boxplots with Palettes"
},
{
"code": null,
"e": 19393,
"s": 19340,
"text": "How to Show Mean on Boxplot using Seaborn in Python?"
},
{
"code": null,
"e": 19437,
"s": 19393,
"text": "Sort Boxplot by Mean with Seaborn in Python"
},
{
"code": null,
"e": 19479,
"s": 19437,
"text": "How To Manually Order Boxplot in Seaborn?"
},
{
"code": null,
"e": 19519,
"s": 19479,
"text": "Grouped Boxplots in Python with Seaborn"
},
{
"code": null,
"e": 19575,
"s": 19519,
"text": "Horizontal Boxplots with Points using Seaborn in Python"
},
{
"code": null,
"e": 19638,
"s": 19575,
"text": "How to Make Boxplots with Data Points using Seaborn in Python?"
},
{
"code": null,
"e": 19685,
"s": 19638,
"text": "Box plot visualization with Pandas and Seaborn"
},
{
"code": null,
"e": 19918,
"s": 19685,
"text": "It is similar to the boxplot except that it provides a higher, more advanced visualization and uses the kernel density estimation to give a better description about the data distribution. It is created using the violinplot() method."
},
{
"code": null,
"e": 19928,
"s": 19920,
"text": "Syntax:"
},
{
"code": null,
"e": 19971,
"s": 19930,
"text": "violinplot([x, y, hue, data, order, ...]"
},
{
"code": null,
"e": 19980,
"s": 19971,
"text": "Example:"
},
{
"code": null,
"e": 19990,
"s": 19982,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.violinplot(x='species', y='sepal_width', data=data)plt.show()",
"e": 20180,
"s": 19990,
"text": null
},
{
"code": null,
"e": 20191,
"s": 20183,
"text": "Output:"
},
{
"code": null,
"e": 20270,
"s": 20195,
"text": "Refer to the below articles to get detailed information about violin plot."
},
{
"code": null,
"e": 20307,
"s": 20272,
"text": "Violinplot using Seaborn in Python"
},
{
"code": null,
"e": 20366,
"s": 20307,
"text": "How to Make Horizontal Violin Plot with Seaborn in Python?"
},
{
"code": null,
"e": 20413,
"s": 20366,
"text": "Make Violinplot with data points using Seaborn"
},
{
"code": null,
"e": 20464,
"s": 20413,
"text": "How To Make Violinpot with data points in Seaborn?"
},
{
"code": null,
"e": 20519,
"s": 20464,
"text": "How to Make Grouped Violinplot with Seaborn in Python?"
},
{
"code": null,
"e": 20624,
"s": 20521,
"text": "It basically creates a scatter plot based on the category. It is created using the stripplot() method."
},
{
"code": null,
"e": 20634,
"s": 20626,
"text": "Syntax:"
},
{
"code": null,
"e": 20677,
"s": 20636,
"text": "stripplot([x, y, hue, data, order, ...])"
},
{
"code": null,
"e": 20688,
"s": 20679,
"text": "Example:"
},
{
"code": null,
"e": 20698,
"s": 20690,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.stripplot(x='species', y='sepal_width', data=data)plt.show()",
"e": 20887,
"s": 20698,
"text": null
},
{
"code": null,
"e": 20898,
"s": 20890,
"text": "Output:"
},
{
"code": null,
"e": 20972,
"s": 20902,
"text": "Refer to the below articles to detailed information about strip plot."
},
{
"code": null,
"e": 21008,
"s": 20974,
"text": "Stripplot using Seaborn in Python"
},
{
"code": null,
"e": 21496,
"s": 21008,
"text": "Swarmplot is very similar to the stripplot except the fact that the points are adjusted so that they do not overlap.Some people also like combining the idea of a violin plot and a stripplot to form this plot. One drawback to using swarmplot is that sometimes they dont scale well to really large numbers and takes a lot of computation to arrange them. So in case we want to visualize a swarmplot properly we can plot it on top of a violinplot. It is plotted using the swarmplot() method."
},
{
"code": null,
"e": 21506,
"s": 21498,
"text": "Syntax:"
},
{
"code": null,
"e": 21549,
"s": 21508,
"text": "swarmplot([x, y, hue, data, order, ...])"
},
{
"code": null,
"e": 21558,
"s": 21549,
"text": "Example:"
},
{
"code": null,
"e": 21568,
"s": 21560,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.swarmplot(x='species', y='sepal_width', data=data)plt.show()",
"e": 21757,
"s": 21568,
"text": null
},
{
"code": null,
"e": 21768,
"s": 21760,
"text": "Output:"
},
{
"code": null,
"e": 21845,
"s": 21772,
"text": "Refer to the below articles to get detailed information about swarmplot."
},
{
"code": null,
"e": 21883,
"s": 21847,
"text": "Python – seaborn.swarmplot() method"
},
{
"code": null,
"e": 21917,
"s": 21883,
"text": "Swarmplot using Seaborn in Python"
},
{
"code": null,
"e": 22203,
"s": 21919,
"text": "Factorplot is the most general of all these plots and provides a parameter called kind to choose the kind of plot we want thus saving us from the trouble of writing these plots separately. The kind parameter can be bar, violin, swarm etc. It is plotted using the factorplot() method."
},
{
"code": null,
"e": 22213,
"s": 22205,
"text": "Syntax:"
},
{
"code": null,
"e": 22264,
"s": 22215,
"text": "sns.factorplot([x, y, hue, data, row, col, ...])"
},
{
"code": null,
"e": 22275,
"s": 22266,
"text": "Example:"
},
{
"code": null,
"e": 22285,
"s": 22277,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.factorplot(x='species', y='sepal_width', data=data)plt.show()",
"e": 22475,
"s": 22285,
"text": null
},
{
"code": null,
"e": 22558,
"s": 22480,
"text": "Refer to the below articles to get dtailed information about the factor plot."
},
{
"code": null,
"e": 22597,
"s": 22560,
"text": "Python – seaborn.factorplot() method"
},
{
"code": null,
"e": 22660,
"s": 22597,
"text": "Plotting different types of plots using Factor plot in seaborn"
},
{
"code": null,
"e": 22821,
"s": 22660,
"text": "Distribution Plots are used for examining univariate and bivariate distributions meaning such distributions that involve one variable or two discrete variables."
},
{
"code": null,
"e": 22906,
"s": 22823,
"text": "Refer to the below article to get detailed informaon about the distribution plots."
},
{
"code": null,
"e": 22927,
"s": 22908,
"text": "Distribution Plots"
},
{
"code": null,
"e": 23015,
"s": 22929,
"text": " There are various types of distribution plots let’s discuss each one them in detail."
},
{
"code": null,
"e": 23235,
"s": 23017,
"text": "A histogram is basically used to represent data provided in a form of some groups.It is accurate method for the graphical representation of numerical data distribution. It can be plotted using the histplot() function."
},
{
"code": null,
"e": 23245,
"s": 23237,
"text": "Syntax:"
},
{
"code": null,
"e": 23307,
"s": 23247,
"text": "histplot(data=None, *, x=None, y=None, hue=None, **kwargs)"
},
{
"code": null,
"e": 23316,
"s": 23307,
"text": "Example:"
},
{
"code": null,
"e": 23326,
"s": 23318,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.histplot(x='species', y='sepal_width', data=data)plt.show()",
"e": 23514,
"s": 23326,
"text": null
},
{
"code": null,
"e": 23525,
"s": 23517,
"text": "Output:"
},
{
"code": null,
"e": 23601,
"s": 23529,
"text": "Refer to the below articles to get detailed information about histplot."
},
{
"code": null,
"e": 23668,
"s": 23603,
"text": "How to Make Histograms with Density Plots with Seaborn histplot?"
},
{
"code": null,
"e": 23726,
"s": 23668,
"text": "How to Add Outline or Edge Color to Histogram in Seaborn?"
},
{
"code": null,
"e": 23787,
"s": 23726,
"text": "Scatter Plot with Marginal Histograms in Python with Seaborn"
},
{
"code": null,
"e": 24015,
"s": 23789,
"text": "Distplot is used basically for univariant set of observations and visualizes it through a histogram i.e. only one observation and hence we choose one particular column of the dataset. It is potted using the distplot() method."
},
{
"code": null,
"e": 24025,
"s": 24017,
"text": "Syntax:"
},
{
"code": null,
"e": 24073,
"s": 24027,
"text": "distplot(a[, bins, hist, kde, rug, fit, ...])"
},
{
"code": null,
"e": 24084,
"s": 24075,
"text": "Example:"
},
{
"code": null,
"e": 24094,
"s": 24086,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.distplot(data['sepal_width'])plt.show()",
"e": 24262,
"s": 24094,
"text": null
},
{
"code": null,
"e": 24273,
"s": 24265,
"text": "Output:"
},
{
"code": null,
"e": 24450,
"s": 24275,
"text": "Jointplot is used to draw a plot of two variables with bivariate and univariate graphs. It basically combines two different plots. It is plotted using the jointplot() method."
},
{
"code": null,
"e": 24460,
"s": 24452,
"text": "Syntax:"
},
{
"code": null,
"e": 24508,
"s": 24462,
"text": "jointplot(x, y[, data, kind, stat_func, ...])"
},
{
"code": null,
"e": 24517,
"s": 24508,
"text": "Example:"
},
{
"code": null,
"e": 24527,
"s": 24519,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.jointplot(x='species', y='sepal_width', data=data)plt.show()",
"e": 24716,
"s": 24527,
"text": null
},
{
"code": null,
"e": 24727,
"s": 24719,
"text": "Output:"
},
{
"code": null,
"e": 24804,
"s": 24731,
"text": "Refer to the below articles to get detailed information about the topic."
},
{
"code": null,
"e": 24842,
"s": 24806,
"text": "Python – seaborn.jointplot() method"
},
{
"code": null,
"e": 25164,
"s": 24844,
"text": "Pairplot represents pairwise relation across the entire dataframe and supports an additional argument called hue for categorical separation. What it does basically is create a jointplot between every possible numerical column and takes a while if the dataframe is really huge. It is plotted using the pairplot() method."
},
{
"code": null,
"e": 25174,
"s": 25166,
"text": "Syntax:"
},
{
"code": null,
"e": 25223,
"s": 25176,
"text": "pairplot(data[, hue, hue_order, palette, ...])"
},
{
"code": null,
"e": 25234,
"s": 25225,
"text": "Example:"
},
{
"code": null,
"e": 25244,
"s": 25236,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.pairplot(data=data, hue='species')plt.show()",
"e": 25417,
"s": 25244,
"text": null
},
{
"code": null,
"e": 25428,
"s": 25420,
"text": "Output:"
},
{
"code": null,
"e": 25508,
"s": 25432,
"text": "Refer to the below articles to get detailed information about the pairplot."
},
{
"code": null,
"e": 25545,
"s": 25510,
"text": "Python – seaborn.pairplot() method"
},
{
"code": null,
"e": 25597,
"s": 25545,
"text": "Data visualization with Pairplot Seaborn and Pandas"
},
{
"code": null,
"e": 25942,
"s": 25599,
"text": "Rugplot plots datapoints in an array as sticks on an axis.Just like a distplot it takes a single column. Instead of drawing a histogram it creates dashes all across the plot. If you compare it with the joinplot you can see that what a jointplot does is that it counts the dashes and shows it as bins. It is plotted using the rugplot() method."
},
{
"code": null,
"e": 25952,
"s": 25944,
"text": "Syntax:"
},
{
"code": null,
"e": 25985,
"s": 25954,
"text": "rugplot(a[, height, axis, ax])"
},
{
"code": null,
"e": 25996,
"s": 25987,
"text": "Example:"
},
{
"code": null,
"e": 26006,
"s": 25998,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.rugplot(data=data)plt.show()",
"e": 26163,
"s": 26006,
"text": null
},
{
"code": null,
"e": 26174,
"s": 26166,
"text": "Output:"
},
{
"code": null,
"e": 26480,
"s": 26176,
"text": "KDE Plot described as Kernel Density Estimate is used for visualizing the Probability Density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can also plot a single graph for multiple samples which helps in more efficient data visualization."
},
{
"code": null,
"e": 26490,
"s": 26482,
"text": "Syntax:"
},
{
"code": null,
"e": 26567,
"s": 26492,
"text": "seaborn.kdeplot(x=None, *, y=None, vertical=False, palette=None, **kwargs)"
},
{
"code": null,
"e": 26578,
"s": 26569,
"text": "Example:"
},
{
"code": null,
"e": 26588,
"s": 26580,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") sns.kdeplot(x='sepal_length', y='sepal_width', data=data)plt.show()",
"e": 26780,
"s": 26588,
"text": null
},
{
"code": null,
"e": 26791,
"s": 26783,
"text": "Output:"
},
{
"code": null,
"e": 26867,
"s": 26795,
"text": "Refer to the below articles to getdetailed information about the topic."
},
{
"code": null,
"e": 26909,
"s": 26869,
"text": "Seaborn Kdeplot – A Comprehensive Guide"
},
{
"code": null,
"e": 26956,
"s": 26909,
"text": "KDE Plot Visualization with Pandas and Seaborn"
},
{
"code": null,
"e": 27242,
"s": 26958,
"text": "The regression plots are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses. Regression plots as the name suggests creates a regression line between two parameters and helps to visualize their linear relationships."
},
{
"code": null,
"e": 27327,
"s": 27244,
"text": "Refer to the below article to get detailed information about the regression plots."
},
{
"code": null,
"e": 27346,
"s": 27329,
"text": "Regression Plots"
},
{
"code": null,
"e": 27547,
"s": 27348,
"text": "there are two main functions that are used to draw linear regression models. These functions are lmplot(), and regplot(), are closely related to each other. They even share their core functionality."
},
{
"code": null,
"e": 27699,
"s": 27549,
"text": "lmplot() method can be understood as a function that basically creates a linear model plot. It creates a scatter plot with a linear fit on top of it."
},
{
"code": null,
"e": 27709,
"s": 27701,
"text": "Syntax:"
},
{
"code": null,
"e": 27778,
"s": 27711,
"text": "seaborn.lmplot(x, y, data, hue=None, col=None, row=None, **kwargs)"
},
{
"code": null,
"e": 27787,
"s": 27778,
"text": "Example:"
},
{
"code": null,
"e": 27797,
"s": 27789,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") sns.lmplot(x='total_bill', y='tip', data=data)plt.show()",
"e": 27978,
"s": 27797,
"text": null
},
{
"code": null,
"e": 27989,
"s": 27981,
"text": "Output:"
},
{
"code": null,
"e": 28067,
"s": 27993,
"text": "Refer to the below articles to get detailed information about the lmplot."
},
{
"code": null,
"e": 28102,
"s": 28069,
"text": "Python – seaborn.lmplot() method"
},
{
"code": null,
"e": 28184,
"s": 28102,
"text": "regplot() method is also similar to lmplot which creates linear regression model."
},
{
"code": null,
"e": 28194,
"s": 28186,
"text": "Syntax:"
},
{
"code": null,
"e": 28260,
"s": 28196,
"text": "seaborn.regplot( x, y, data=None, x_estimator=None, **kwargs)"
},
{
"code": null,
"e": 28269,
"s": 28260,
"text": "Example:"
},
{
"code": null,
"e": 28279,
"s": 28271,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") sns.regplot(x='total_bill', y='tip', data=data)plt.show()",
"e": 28461,
"s": 28279,
"text": null
},
{
"code": null,
"e": 28472,
"s": 28464,
"text": "Output:"
},
{
"code": null,
"e": 28547,
"s": 28476,
"text": "Refer to the below articles to get detailed information about regplot."
},
{
"code": null,
"e": 28583,
"s": 28549,
"text": "Python – seaborn.regplot() method"
},
{
"code": null,
"e": 28788,
"s": 28583,
"text": "Note: The difference between both the function is that regplot accepts the x, y variables in different format including NumPy arrays, Pandas objects, whereas, the lmplot only accepts the value as strings."
},
{
"code": null,
"e": 28946,
"s": 28790,
"text": "A matrix plot means plotting matrix data where color coded diagrams shows rows data, column data and values. It can shown using the heatmap and clustermap."
},
{
"code": null,
"e": 29028,
"s": 28948,
"text": "Refer to the below articles to get detailed information about the matrix plots."
},
{
"code": null,
"e": 29043,
"s": 29030,
"text": "Matrix plots"
},
{
"code": null,
"e": 29389,
"s": 29043,
"text": "Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. In this, to represent more common values or higher activities brighter colors basically reddish colors are used and to represent less common or activity values, darker colors are preferred. it can be plotted using the heatmap() function."
},
{
"code": null,
"e": 29399,
"s": 29391,
"text": "Syntax:"
},
{
"code": null,
"e": 29542,
"s": 29401,
"text": "seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs)"
},
{
"code": null,
"e": 29551,
"s": 29542,
"text": "Example:"
},
{
"code": null,
"e": 29561,
"s": 29553,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # correlation between the different parameters tc = data.corr() sns.heatmap(tc)plt.show()",
"e": 29776,
"s": 29561,
"text": null
},
{
"code": null,
"e": 29787,
"s": 29779,
"text": "Output:"
},
{
"code": null,
"e": 29866,
"s": 29791,
"text": "Refer to the below articles to get detailed information about the heatmap."
},
{
"code": null,
"e": 29908,
"s": 29868,
"text": "Seaborn Heatmap – A comprehensive guide"
},
{
"code": null,
"e": 29963,
"s": 29908,
"text": "How to create a seaborn correlation heatmap in Python?"
},
{
"code": null,
"e": 30029,
"s": 29963,
"text": "How to create a Triangle Correlation Heatmap in seaborn – Python?"
},
{
"code": null,
"e": 30059,
"s": 30029,
"text": "ColorMaps in Seaborn HeatMaps"
},
{
"code": null,
"e": 30130,
"s": 30059,
"text": "How to change the colorbar size of a seaborn heatmap figure in Python?"
},
{
"code": null,
"e": 30188,
"s": 30130,
"text": "How to add a frame to a seaborn heatmap figure in Python?"
},
{
"code": null,
"e": 30264,
"s": 30188,
"text": "How to increase the size of the annotations of a seaborn heatmap in Python?"
},
{
"code": null,
"e": 30466,
"s": 30264,
"text": "The clustermap() function of seaborn plots the hierarchically-clustered heatmap of the given matrix dataset. Clustering simply means grouping data based on relationship among the variables in the data."
},
{
"code": null,
"e": 30476,
"s": 30468,
"text": "Syntax:"
},
{
"code": null,
"e": 30525,
"s": 30478,
"text": "clustermap(data, *, pivot_kws=None, **kwargs)"
},
{
"code": null,
"e": 30534,
"s": 30525,
"text": "Example:"
},
{
"code": null,
"e": 30544,
"s": 30536,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # correlation between the different parameters tc = data.corr() sns.clustermap(tc)plt.show()",
"e": 30762,
"s": 30544,
"text": null
},
{
"code": null,
"e": 30773,
"s": 30765,
"text": "Output:"
},
{
"code": null,
"e": 30851,
"s": 30777,
"text": "Refer to the below articles to get detailed information about clustermap."
},
{
"code": null,
"e": 30920,
"s": 30853,
"text": "Hierarchically-clustered Heatmap in Python with Seaborn Clustermap"
},
{
"code": null,
"e": 30952,
"s": 30920,
"text": "Exploring Correlation in Python"
},
{
"code": null,
"e": 30976,
"s": 30954,
"text": "Seaborn – Bubble Plot"
},
{
"code": null,
"e": 31012,
"s": 30976,
"text": "Python – seaborn.residplot() method"
},
{
"code": null,
"e": 31048,
"s": 31012,
"text": "Python – seaborn.boxenplot() method"
},
{
"code": null,
"e": 31084,
"s": 31048,
"text": "Python – seaborn.pointplot() method"
},
{
"code": null,
"e": 31109,
"s": 31084,
"text": "Python Seaborn – Catplot"
},
{
"code": null,
"e": 31164,
"s": 31109,
"text": "How to Make Countplot or barplot with Seaborn Catplot?"
},
{
"code": null,
"e": 31214,
"s": 31164,
"text": "How To Make Grouped Boxplot with Seaborn Catplot?"
},
{
"code": null,
"e": 31269,
"s": 31214,
"text": "Python Seaborn – Strip plot illustration using Catplot"
},
{
"code": null,
"e": 31332,
"s": 31269,
"text": "How To Make Simple Facet Plots with Seaborn Catplot in Python?"
},
{
"code": null,
"e": 31383,
"s": 31332,
"text": "How To Make Ridgeline plot in Python with Seaborn?"
},
{
"code": null,
"e": 31453,
"s": 31385,
"text": "Change Axis Labels, Set Title and Figure Size to Plots with Seaborn"
},
{
"code": null,
"e": 31514,
"s": 31453,
"text": "How To Place Legend Outside the Plot with Seaborn in Python?"
},
{
"code": null,
"e": 31559,
"s": 31514,
"text": "How to Plot a Confidence Interval in Python?"
},
{
"code": null,
"e": 31611,
"s": 31559,
"text": "Creating A Time Series Plot With Seaborn And Pandas"
},
{
"code": null,
"e": 31674,
"s": 31611,
"text": "How to Make a Time Series Plot with Rolling Average in Python?"
},
{
"code": null,
"e": 31735,
"s": 31674,
"text": "How To Add Regression Line Per Group with Seaborn in Python?"
},
{
"code": null,
"e": 31785,
"s": 31735,
"text": "Data Visualization with Python Seaborn and Pandas"
},
{
"code": null,
"e": 31843,
"s": 31785,
"text": "Data Visualization in Python using Matplotlib and Seaborn"
},
{
"code": null,
"e": 31903,
"s": 31843,
"text": "Visualizing ML DataSet Through Seaborn Plots and Matplotlib"
},
{
"code": null,
"e": 31915,
"s": 31905,
"text": "as5853535"
},
{
"code": null,
"e": 31930,
"s": 31915,
"text": "prachisoda1234"
},
{
"code": null,
"e": 31944,
"s": 31930,
"text": "sumitgumber28"
},
{
"code": null,
"e": 31959,
"s": 31944,
"text": "varshagumber28"
},
{
"code": null,
"e": 31966,
"s": 31959,
"text": "Python"
}
] |
Decimal Equivalent of Binary Linked List | 01 Jul, 2022
Given a singly linked list of 0s and 1s find its decimal equivalent.
Input : 0->0->0->1->1->0->0->1->0
Output : 50
Input : 1->0->0
Output : 4
The decimal value of an empty linked list is considered as 0.
Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node’s data to it.
C++
C
Java
Python3
C#
Javascript
// C++ Program to find decimal value of// binary linked list#include <bits/stdc++.h>using namespace std; /* Link list Node */class Node{ public: bool data; Node* next;}; /* Returns decimal value of binary linked list */int decimalValue(Node *head){ // Initialized result int res = 0; // Traverse linked list while (head != NULL) { // Multiply result by 2 and add // head's data res = (res << 1) + head->data; // Move next head = head->next; } return res;} // Utility function to create a new node.Node *newNode(bool data){ Node *temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ Node* head = newNode(1); head->next = newNode(0); head->next->next = newNode(1); head->next->next->next = newNode(1); cout << "Decimal value is " << decimalValue(head); return 0;} // This is code is contributed by rathbhupendra
// C Program to find decimal value of// binary linked list#include<iostream>using namespace std; /* Link list Node */struct Node{ bool data; struct Node* next;}; /* Returns decimal value of binary linked list */int decimalValue(struct Node *head){ // Initialized result int res = 0; // Traverse linked list while (head != NULL) { // Multiply result by 2 and add // head's data res = (res << 1) + head->data; // Move next head = head->next; } return res;} // Utility function to create a new node.Node *newNode(bool data){ struct Node *temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(0); head->next->next = newNode(1); head->next->next->next = newNode(1); cout << "Decimal value is " << decimalValue(head); return 0;}
// Java Program to find decimal value of// binary linked listclass GFG{ // Link list Node /static class Node{ boolean data; Node next;}; // Returns decimal value of binary linked list /static int decimalValue( Node head){ // Initialized result int res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and add // head's data res = (res << 1) + (head.data?1:0); // Move next head = head.next; } return res;} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = (data==1? true:false); temp.next = null; return temp;} // Driver code/public static void main(String args[]){ // Start with the empty list / Node head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); System.out.print( "Decimal value is "+decimalValue(head));}} // This code is contributed by Arnab Kundu
# Python3 program to find decimal value# of binary linked list # Node Classclass Node: # Function to initialise the # node object def __init__(self, data): # Assign data self.data = data # Initialize next as null self.next = None # Linked List class contains# a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Returns decimal value of binary # linked list def decimalValue(self, head): # Initialized result res = 0 # Traverse linked list while head: # Multiply result by 2 and # add head's data res = (res << 1) + head.data # Move Next head = head.next return res # Driver codeif __name__ == '__main__': #Start with the empty list llist = LinkedList() llist.head = Node(1) llist.head.next = Node(0) llist.head.next.next = Node(1) llist.head.next.next.next = Node(1) print("Decimal Value is {}".format( llist.decimalValue(llist.head))) # This code is contributed by Mohit Jangra
// C# Program to find decimal value of// binary linked listusing System; class GFG{ // Link list Node /public class Node{ public Boolean data; public Node next;}; // Returns decimal value of binary linked liststatic int decimalValue( Node head){ // Initialized result int res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and add // head's data res = (res << 1) + (head.data ? 1 : 0); // Move next head = head.next; } return res;} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = (data == 1 ? true : false); temp.next = null; return temp;} // Driver codpublic static void Main(String []args){ // Start with the empty list Node head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); Console.WriteLine("Decimal value is " + decimalValue(head));}} // This code is contributed by Rajput-Ji
<script> // Javascript Program to find decimal value of// binary linked list // Link list Node / class Node { constructor(){ this.data = true; this.next = null; } } // Returns decimal value of binary linked list / function decimalValue(head) { // Initialized result var res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and add // head's data res = (res << 1) + (head.data ? 1 : 0); // Move next head = head.next; } return res; } // Utility function to create a new node. function newNode(data) {var temp = new Node(); temp.data = (data == 1 ? true : false); temp.next = null; return temp; } // Driver code/ // Start with the empty list /var head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); document.write("Decimal value is " + decimalValue(head)); // This code contributed by aashish1995 </script>
Decimal value is 11
Time Complexity: O(n) where n is the number of nodes in the given linked list.Auxiliary Space: O(1), no extra space is required, so it is a constant.
Decimal Equivalent of Binary Linked List | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersDecimal Equivalent of Binary Linked List | 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 / 6:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=k9x5UjTYi5I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
andrew1234
rathbhupendra
Rajput-Ji
Akanksha_Rai
itsmohitj
aashish1995
tamanna17122007
hardikkoriintern
Juniper Networks
Linked List
Juniper Networks
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion)
Merge two sorted linked lists
What is Data Structure: Types, Classifications and Applications
Linked List vs Array
Merge Sort for Linked Lists
Implementing a Linked List in Java using Class
Find Length of a Linked List (Iterative and Recursive)
Queue - Linked List Implementation | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 121,
"s": 52,
"text": "Given a singly linked list of 0s and 1s find its decimal equivalent."
},
{
"code": null,
"e": 212,
"s": 121,
"text": " Input : 0->0->0->1->1->0->0->1->0\n Output : 50 \n\n Input : 1->0->0\n Output : 4"
},
{
"code": null,
"e": 274,
"s": 212,
"text": "The decimal value of an empty linked list is considered as 0."
},
{
"code": null,
"e": 402,
"s": 274,
"text": "Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node’s data to it."
},
{
"code": null,
"e": 406,
"s": 402,
"text": "C++"
},
{
"code": null,
"e": 408,
"s": 406,
"text": "C"
},
{
"code": null,
"e": 413,
"s": 408,
"text": "Java"
},
{
"code": null,
"e": 421,
"s": 413,
"text": "Python3"
},
{
"code": null,
"e": 424,
"s": 421,
"text": "C#"
},
{
"code": null,
"e": 435,
"s": 424,
"text": "Javascript"
},
{
"code": "// C++ Program to find decimal value of// binary linked list#include <bits/stdc++.h>using namespace std; /* Link list Node */class Node{ public: bool data; Node* next;}; /* Returns decimal value of binary linked list */int decimalValue(Node *head){ // Initialized result int res = 0; // Traverse linked list while (head != NULL) { // Multiply result by 2 and add // head's data res = (res << 1) + head->data; // Move next head = head->next; } return res;} // Utility function to create a new node.Node *newNode(bool data){ Node *temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ Node* head = newNode(1); head->next = newNode(0); head->next->next = newNode(1); head->next->next->next = newNode(1); cout << \"Decimal value is \" << decimalValue(head); return 0;} // This is code is contributed by rathbhupendra",
"e": 1456,
"s": 435,
"text": null
},
{
"code": "// C Program to find decimal value of// binary linked list#include<iostream>using namespace std; /* Link list Node */struct Node{ bool data; struct Node* next;}; /* Returns decimal value of binary linked list */int decimalValue(struct Node *head){ // Initialized result int res = 0; // Traverse linked list while (head != NULL) { // Multiply result by 2 and add // head's data res = (res << 1) + head->data; // Move next head = head->next; } return res;} // Utility function to create a new node.Node *newNode(bool data){ struct Node *temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(0); head->next->next = newNode(1); head->next->next->next = newNode(1); cout << \"Decimal value is \" << decimalValue(head); return 0;}",
"e": 2442,
"s": 1456,
"text": null
},
{
"code": "// Java Program to find decimal value of// binary linked listclass GFG{ // Link list Node /static class Node{ boolean data; Node next;}; // Returns decimal value of binary linked list /static int decimalValue( Node head){ // Initialized result int res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and add // head's data res = (res << 1) + (head.data?1:0); // Move next head = head.next; } return res;} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = (data==1? true:false); temp.next = null; return temp;} // Driver code/public static void main(String args[]){ // Start with the empty list / Node head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); System.out.print( \"Decimal value is \"+decimalValue(head));}} // This code is contributed by Arnab Kundu",
"e": 3438,
"s": 2442,
"text": null
},
{
"code": "# Python3 program to find decimal value# of binary linked list # Node Classclass Node: # Function to initialise the # node object def __init__(self, data): # Assign data self.data = data # Initialize next as null self.next = None # Linked List class contains# a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Returns decimal value of binary # linked list def decimalValue(self, head): # Initialized result res = 0 # Traverse linked list while head: # Multiply result by 2 and # add head's data res = (res << 1) + head.data # Move Next head = head.next return res # Driver codeif __name__ == '__main__': #Start with the empty list llist = LinkedList() llist.head = Node(1) llist.head.next = Node(0) llist.head.next.next = Node(1) llist.head.next.next.next = Node(1) print(\"Decimal Value is {}\".format( llist.decimalValue(llist.head))) # This code is contributed by Mohit Jangra",
"e": 4612,
"s": 3438,
"text": null
},
{
"code": "// C# Program to find decimal value of// binary linked listusing System; class GFG{ // Link list Node /public class Node{ public Boolean data; public Node next;}; // Returns decimal value of binary linked liststatic int decimalValue( Node head){ // Initialized result int res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and add // head's data res = (res << 1) + (head.data ? 1 : 0); // Move next head = head.next; } return res;} // Utility function to create a new node.static Node newNode(int data){ Node temp = new Node(); temp.data = (data == 1 ? true : false); temp.next = null; return temp;} // Driver codpublic static void Main(String []args){ // Start with the empty list Node head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); Console.WriteLine(\"Decimal value is \" + decimalValue(head));}} // This code is contributed by Rajput-Ji",
"e": 5659,
"s": 4612,
"text": null
},
{
"code": "<script> // Javascript Program to find decimal value of// binary linked list // Link list Node / class Node { constructor(){ this.data = true; this.next = null; } } // Returns decimal value of binary linked list / function decimalValue(head) { // Initialized result var res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and add // head's data res = (res << 1) + (head.data ? 1 : 0); // Move next head = head.next; } return res; } // Utility function to create a new node. function newNode(data) {var temp = new Node(); temp.data = (data == 1 ? true : false); temp.next = null; return temp; } // Driver code/ // Start with the empty list /var head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); document.write(\"Decimal value is \" + decimalValue(head)); // This code contributed by aashish1995 </script>",
"e": 6774,
"s": 5659,
"text": null
},
{
"code": null,
"e": 6794,
"s": 6774,
"text": "Decimal value is 11"
},
{
"code": null,
"e": 6944,
"s": 6794,
"text": "Time Complexity: O(n) where n is the number of nodes in the given linked list.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 7842,
"s": 6944,
"text": "Decimal Equivalent of Binary Linked List | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersDecimal Equivalent of Binary Linked List | 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 / 6:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=k9x5UjTYi5I\" 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": 8110,
"s": 7842,
"text": "This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 8121,
"s": 8110,
"text": "andrew1234"
},
{
"code": null,
"e": 8135,
"s": 8121,
"text": "rathbhupendra"
},
{
"code": null,
"e": 8145,
"s": 8135,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8158,
"s": 8145,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8168,
"s": 8158,
"text": "itsmohitj"
},
{
"code": null,
"e": 8180,
"s": 8168,
"text": "aashish1995"
},
{
"code": null,
"e": 8196,
"s": 8180,
"text": "tamanna17122007"
},
{
"code": null,
"e": 8213,
"s": 8196,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 8230,
"s": 8213,
"text": "Juniper Networks"
},
{
"code": null,
"e": 8242,
"s": 8230,
"text": "Linked List"
},
{
"code": null,
"e": 8259,
"s": 8242,
"text": "Juniper Networks"
},
{
"code": null,
"e": 8271,
"s": 8259,
"text": "Linked List"
},
{
"code": null,
"e": 8369,
"s": 8271,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8388,
"s": 8369,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 8420,
"s": 8388,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8476,
"s": 8420,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 8506,
"s": 8476,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 8570,
"s": 8506,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 8591,
"s": 8570,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 8619,
"s": 8591,
"text": "Merge Sort for Linked Lists"
},
{
"code": null,
"e": 8666,
"s": 8619,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 8721,
"s": 8666,
"text": "Find Length of a Linked List (Iterative and Recursive)"
}
] |
Python | Pandas dataframe.memory_usage() | 22 Jun, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.memory_usage() function return the memory usage of each column in bytes. The memory usage can optionally include the contribution of the index and elements of object dtype. This value is displayed in DataFrame.info by default.
Syntax: DataFrame.memory_usage(index=True, deep=False)Parameters : index : Specifies whether to include the memory usage of the DataFrame’s index in returned Series. If index=True the memory usage of the index the first item in the output. deep : If True, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned values.Returns : A Series whose index is the original column names and whose values is the memory usage of each column in bytes
For link to the CSV file used in the code, click hereExample #1: Use memory_usage() function print the memory usage of each column in the dataframe along with the memory usage of the index.
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv("nba.csv") # Print the dataframedf
Let’s use the memory_usage() function to find the memory usage of each column.
Python3
# Function to find memory use of each# column along with the index# even if we do not set index = True,# it will show the index usage as well by default.df.memory_usage(index = True)
Output :
Example #2: Use memory_usage() function to find the memory use of each column but not of the index.
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv("nba.csv") # Function to find memory use of each# column but not of the index# we set index = Falsedf.memory_usage(index = False)
Output :
surinderdawra388
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.
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": "\n22 Jun, 2021"
},
{
"code": null,
"e": 487,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.memory_usage() function return the memory usage of each column in bytes. The memory usage can optionally include the contribution of the index and elements of object dtype. This value is displayed in DataFrame.info by default. "
},
{
"code": null,
"e": 999,
"s": 487,
"text": "Syntax: DataFrame.memory_usage(index=True, deep=False)Parameters : index : Specifies whether to include the memory usage of the DataFrame’s index in returned Series. If index=True the memory usage of the index the first item in the output. deep : If True, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned values.Returns : A Series whose index is the original column names and whose values is the memory usage of each column in bytes "
},
{
"code": null,
"e": 1190,
"s": 999,
"text": "For link to the CSV file used in the code, click hereExample #1: Use memory_usage() function print the memory usage of each column in the dataframe along with the memory usage of the index. "
},
{
"code": null,
"e": 1198,
"s": 1190,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv(\"nba.csv\") # Print the dataframedf",
"e": 1318,
"s": 1198,
"text": null
},
{
"code": null,
"e": 1400,
"s": 1318,
"text": " Let’s use the memory_usage() function to find the memory usage of each column. "
},
{
"code": null,
"e": 1408,
"s": 1400,
"text": "Python3"
},
{
"code": "# Function to find memory use of each# column along with the index# even if we do not set index = True,# it will show the index usage as well by default.df.memory_usage(index = True)",
"e": 1591,
"s": 1408,
"text": null
},
{
"code": null,
"e": 1602,
"s": 1591,
"text": "Output : "
},
{
"code": null,
"e": 1705,
"s": 1602,
"text": " Example #2: Use memory_usage() function to find the memory use of each column but not of the index. "
},
{
"code": null,
"e": 1713,
"s": 1705,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.read_csv(\"nba.csv\") # Function to find memory use of each# column but not of the index# we set index = Falsedf.memory_usage(index = False)",
"e": 1928,
"s": 1713,
"text": null
},
{
"code": null,
"e": 1939,
"s": 1928,
"text": "Output : "
},
{
"code": null,
"e": 1958,
"s": 1941,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1982,
"s": 1958,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2014,
"s": 1982,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2028,
"s": 2014,
"text": "Python-pandas"
},
{
"code": null,
"e": 2035,
"s": 2028,
"text": "Python"
},
{
"code": null,
"e": 2133,
"s": 2035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2151,
"s": 2133,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2193,
"s": 2151,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2215,
"s": 2193,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2250,
"s": 2215,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2276,
"s": 2250,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2308,
"s": 2276,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2337,
"s": 2308,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2364,
"s": 2337,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2394,
"s": 2364,
"text": "Iterate over a list in Python"
}
] |
Loop Vectorization in Julia | 10 May, 2020
Vectorization is used to speed up the code without using loop. Using such a function can help in minimizing the running time of code efficiently. There are two meanings of the word vectorization in the high-level languages, and they refer to different things.When we talk about vectorized code in Python/Numpy/Matlab/etc., we are usually referring to the fact that code be like:
x = [1, 2, 3]y = x + 1
is faster than:
x = [1, 2, 3]for i in 1:3 y[i] = x[i] + 1end
The kind of vectorization in the first code block is quite helpful in languages like Python and Matlab because generally, every operation in these languages tends to be slow. Each iteration involves calling + operator, making array lookups, type-conversions etc. and repeating this iteration for a given number of times makes the overall computation slow. So, it’s faster to vectorize the code and only paying the cost of looking up the + operation once for the entire vector x rather than once for each element x[i].We don’t come across such problems in Julia, where
y .= x .+ 1
and
for i in 1:3 y[i] = x[i] + 1end
both compile down to almost the same code and perform comparably. So the kind of vectorization needed in Python and Matlab is not necessary in Julia.
In fact, each vectorized operation ends up generating a new temporary array and executing a separate loop, which leads to a lot of overhead when multiple vectorized operations are combined.So in some cases, we may observe vectorized code to run slower.
The other kind of vectorization pertains to improving performance by using SIMD (Single Instruction, Multiple Data) instructions and refers to the CPU’s ability to operate on chunks of data.
The following code shows a simple sum function (returning the sum of all the elements in an array arr):
function mysum(arr::Vector) total = zero(eltype(arr)) for x in arr total += x end return totalend
This operation can be generally visualized as serial addition of total with an array element in every iteration.
# generate random dataarr = rand(10 ^ 5); using BenchmarkTools @benchmark mysum(arr)
Output :
Using SIMD macro:
function mysum1(arr::Vector) total = zero(eltype(arr)) @simd for x in arr total += x end return totalend # benchmark the mysum1 function@benchmark mysum1(arr)
Output:We can clearly see the performance increase after using the SIMD macro.So what’s actually happening ?By taking advantage of the SIMD instruction set(inbuilt feature of most Intel® CPU’s), the add operation is performed in two steps:
During the first step, intermediate values are accumulated n at a time (n depends on the CPU hardware).In a so called reduction step, the final n elements are summed together.
Now the question arises, how can we combine SIMD vectorization and the language’s vectorization capabilities to derive more performance both from the language’s compiler and the CPU? In Julia we answer it with the LoopVectorization.jl package.
LoopVectorization.jl is Julia package that provides macros and functions that combine SIMD vectorization and loop reordering so as to improve performance.
It annotates a for loop, or a set of nested for loops whose bounds are constant across iterations, to optimize the computation.Let’s consider the classical dot product problem. To know more about dot product and it’s vectorized implementation in python, check out this article.In the below examples we will benchmark the same code with different types of vectorization.Example:
# Without using any macrofunction dotProd(x, y) prod = zero(eltype(x)) for i in eachindex(x, y) prod += x[i] * y[i] end prodend # using the simd macrofunction dotProd_simd(x, y) prod = zero(eltype(x)) @simd for i in eachindex(x, y) prod += x[i] * y[i] end prodend # using the avx macrousing LoopVectorizationfunction dotProd_avx(x, y) prod = zero(eltype(x)) @avx for i in eachindex(x, y) prod += x[i] * y[i] end prodend
Output :
Comparing the three functions:
using BenchmarkTools # generating random datax = rand(10 ^ 5);y = rand(10 ^ 5); # benchmark the function without any macro@benchmark dotProd(x, y) # benchmark the function with simd macro@benchmark dotProd_simd(x, y) # benchmark the function with avx macro@benchmark dotProd_avx(x, y)
Output :
We observe that the @avx macro turns out to have the best performance! The time gap will generally increase for larger sizes of x and y.
This is simply a SIMD-vectorized map function.Syntax :
vmap!(f, destination_variable, x::AbstractArray)vmap!(f, destination_varaible, x::AbstractArray, yb::AbstractArray, ...)It applies f to each element of x (or paired elements of x, y, ...) and storing the result in destination-variable.If the ! symbol is removed a new array is returned instead of the destination_variable.vmap(f, x::AbstractArray)vmap(f, x::AbstractArray, yb::AbstractArray, ...)
Example:
# the function ff(x, y) = 1 / (1 + exp(x-y)) # generate random datax = rand(10^5);y = rand(10^5); # destination variable of the same dims as xz = similar(x);
Output :
# benchmark the map function@benchmark map!(f, $z, $x, $y) # benchmark the vmap function@benchmark vmap!(f, $z, $x, $y)
Output :We again observe that the vectorized map function performs quite faster.Let’s look at some tweaked versions of the vmap function.
It is variant of vmap that can improve performance where the destination_variable is not needed during the vmap process.Syntax :
vmapnt(f, x::AbstractArray)
vmapnt(f, x::AbstractArray, y::AbstractArray, ...)
vmapnt!(f, destination_variable, x::AbstractArray, y::AbstractArray, ...)
This is a vectorized map implementation using nontemporal store operations.It means if the arguments are very long(like in the previous example), the write operationsto the destination_variable will not go to the CPU’s cache. If we will not immediately be reading from these values, this can improve performance because the writes won’t pollute the cache.
It is a threaded variant of vmapnt.Syntax :
vmapntt(f, x::AbstractArray)
vmapntt(f, x::AbstractArray, y::AbstractArray, ...)
It is similar to vmapnt!, but uses Threads.@threads for parallel execution.Syntax :
vmapntt!(f, destination_variable, x::AbstractArray, y::AbstractArray, ...)
It is a SIMD-vectorized filter, returning an array containing the elements of x for which f returns true.Syntax :
vfilter(f, x::AbstractArray)
It is a SIMD-vectorized filter!, removing the element of x for which f is false.Syntax :
vfilter(f, x::AbstractArray)
Examples:
# benchmark the vmapnt function@benchmark vmapnt!(f, $z, $x, $y) # change the number of threadsThreads.nthreads()Threads.nthreads() = 8Threads.nthreads() # benchmark the vmapntt function@benchmark vmapntt!(f, $z, $x, $y) # benchmark the filter against vfilter construct@benchmark filter(a -> a < 0.67, $x)@benchmark vfilter(a -> a < 0.67, $x)
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
String concatenation in Julia
Getting rounded value of a number in Julia - round() Method
Reshaping array dimensions in Julia | Array reshape() Method
Storing Output on a File in Julia
Manipulating matrices in Julia
Exception handling in Julia
Formatting of Strings in Julia
Tuples in Julia
while loop in Julia | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 407,
"s": 28,
"text": "Vectorization is used to speed up the code without using loop. Using such a function can help in minimizing the running time of code efficiently. There are two meanings of the word vectorization in the high-level languages, and they refer to different things.When we talk about vectorized code in Python/Numpy/Matlab/etc., we are usually referring to the fact that code be like:"
},
{
"code": "x = [1, 2, 3]y = x + 1",
"e": 430,
"s": 407,
"text": null
},
{
"code": null,
"e": 446,
"s": 430,
"text": "is faster than:"
},
{
"code": "x = [1, 2, 3]for i in 1:3 y[i] = x[i] + 1end",
"e": 494,
"s": 446,
"text": null
},
{
"code": null,
"e": 1062,
"s": 494,
"text": "The kind of vectorization in the first code block is quite helpful in languages like Python and Matlab because generally, every operation in these languages tends to be slow. Each iteration involves calling + operator, making array lookups, type-conversions etc. and repeating this iteration for a given number of times makes the overall computation slow. So, it’s faster to vectorize the code and only paying the cost of looking up the + operation once for the entire vector x rather than once for each element x[i].We don’t come across such problems in Julia, where"
},
{
"code": "y .= x .+ 1",
"e": 1074,
"s": 1062,
"text": null
},
{
"code": null,
"e": 1078,
"s": 1074,
"text": "and"
},
{
"code": "for i in 1:3 y[i] = x[i] + 1end",
"e": 1113,
"s": 1078,
"text": null
},
{
"code": null,
"e": 1263,
"s": 1113,
"text": "both compile down to almost the same code and perform comparably. So the kind of vectorization needed in Python and Matlab is not necessary in Julia."
},
{
"code": null,
"e": 1516,
"s": 1263,
"text": "In fact, each vectorized operation ends up generating a new temporary array and executing a separate loop, which leads to a lot of overhead when multiple vectorized operations are combined.So in some cases, we may observe vectorized code to run slower."
},
{
"code": null,
"e": 1707,
"s": 1516,
"text": "The other kind of vectorization pertains to improving performance by using SIMD (Single Instruction, Multiple Data) instructions and refers to the CPU’s ability to operate on chunks of data."
},
{
"code": null,
"e": 1811,
"s": 1707,
"text": "The following code shows a simple sum function (returning the sum of all the elements in an array arr):"
},
{
"code": "function mysum(arr::Vector) total = zero(eltype(arr)) for x in arr total += x end return totalend",
"e": 1928,
"s": 1811,
"text": null
},
{
"code": null,
"e": 2041,
"s": 1928,
"text": "This operation can be generally visualized as serial addition of total with an array element in every iteration."
},
{
"code": "# generate random dataarr = rand(10 ^ 5); using BenchmarkTools @benchmark mysum(arr)",
"e": 2128,
"s": 2041,
"text": null
},
{
"code": null,
"e": 2137,
"s": 2128,
"text": "Output :"
},
{
"code": null,
"e": 2155,
"s": 2137,
"text": "Using SIMD macro:"
},
{
"code": "function mysum1(arr::Vector) total = zero(eltype(arr)) @simd for x in arr total += x end return totalend # benchmark the mysum1 function@benchmark mysum1(arr)",
"e": 2334,
"s": 2155,
"text": null
},
{
"code": null,
"e": 2574,
"s": 2334,
"text": "Output:We can clearly see the performance increase after using the SIMD macro.So what’s actually happening ?By taking advantage of the SIMD instruction set(inbuilt feature of most Intel® CPU’s), the add operation is performed in two steps:"
},
{
"code": null,
"e": 2750,
"s": 2574,
"text": "During the first step, intermediate values are accumulated n at a time (n depends on the CPU hardware).In a so called reduction step, the final n elements are summed together."
},
{
"code": null,
"e": 2994,
"s": 2750,
"text": "Now the question arises, how can we combine SIMD vectorization and the language’s vectorization capabilities to derive more performance both from the language’s compiler and the CPU? In Julia we answer it with the LoopVectorization.jl package."
},
{
"code": null,
"e": 3149,
"s": 2994,
"text": "LoopVectorization.jl is Julia package that provides macros and functions that combine SIMD vectorization and loop reordering so as to improve performance."
},
{
"code": null,
"e": 3527,
"s": 3149,
"text": "It annotates a for loop, or a set of nested for loops whose bounds are constant across iterations, to optimize the computation.Let’s consider the classical dot product problem. To know more about dot product and it’s vectorized implementation in python, check out this article.In the below examples we will benchmark the same code with different types of vectorization.Example:"
},
{
"code": "# Without using any macrofunction dotProd(x, y) prod = zero(eltype(x)) for i in eachindex(x, y) prod += x[i] * y[i] end prodend # using the simd macrofunction dotProd_simd(x, y) prod = zero(eltype(x)) @simd for i in eachindex(x, y) prod += x[i] * y[i] end prodend # using the avx macrousing LoopVectorizationfunction dotProd_avx(x, y) prod = zero(eltype(x)) @avx for i in eachindex(x, y) prod += x[i] * y[i] end prodend",
"e": 4110,
"s": 3527,
"text": null
},
{
"code": null,
"e": 4119,
"s": 4110,
"text": "Output :"
},
{
"code": null,
"e": 4150,
"s": 4119,
"text": "Comparing the three functions:"
},
{
"code": "using BenchmarkTools # generating random datax = rand(10 ^ 5);y = rand(10 ^ 5); # benchmark the function without any macro@benchmark dotProd(x, y) # benchmark the function with simd macro@benchmark dotProd_simd(x, y) # benchmark the function with avx macro@benchmark dotProd_avx(x, y)",
"e": 4442,
"s": 4150,
"text": null
},
{
"code": null,
"e": 4451,
"s": 4442,
"text": "Output :"
},
{
"code": null,
"e": 4588,
"s": 4451,
"text": "We observe that the @avx macro turns out to have the best performance! The time gap will generally increase for larger sizes of x and y."
},
{
"code": null,
"e": 4643,
"s": 4588,
"text": "This is simply a SIMD-vectorized map function.Syntax :"
},
{
"code": null,
"e": 5040,
"s": 4643,
"text": "vmap!(f, destination_variable, x::AbstractArray)vmap!(f, destination_varaible, x::AbstractArray, yb::AbstractArray, ...)It applies f to each element of x (or paired elements of x, y, ...) and storing the result in destination-variable.If the ! symbol is removed a new array is returned instead of the destination_variable.vmap(f, x::AbstractArray)vmap(f, x::AbstractArray, yb::AbstractArray, ...)"
},
{
"code": null,
"e": 5049,
"s": 5040,
"text": "Example:"
},
{
"code": "# the function ff(x, y) = 1 / (1 + exp(x-y)) # generate random datax = rand(10^5);y = rand(10^5); # destination variable of the same dims as xz = similar(x);",
"e": 5209,
"s": 5049,
"text": null
},
{
"code": null,
"e": 5218,
"s": 5209,
"text": "Output :"
},
{
"code": "# benchmark the map function@benchmark map!(f, $z, $x, $y) # benchmark the vmap function@benchmark vmap!(f, $z, $x, $y)",
"e": 5339,
"s": 5218,
"text": null
},
{
"code": null,
"e": 5477,
"s": 5339,
"text": "Output :We again observe that the vectorized map function performs quite faster.Let’s look at some tweaked versions of the vmap function."
},
{
"code": null,
"e": 5606,
"s": 5477,
"text": "It is variant of vmap that can improve performance where the destination_variable is not needed during the vmap process.Syntax :"
},
{
"code": null,
"e": 5761,
"s": 5606,
"text": "vmapnt(f, x::AbstractArray)\nvmapnt(f, x::AbstractArray, y::AbstractArray, ...)\n\nvmapnt!(f, destination_variable, x::AbstractArray, y::AbstractArray, ...)\n"
},
{
"code": null,
"e": 6117,
"s": 5761,
"text": "This is a vectorized map implementation using nontemporal store operations.It means if the arguments are very long(like in the previous example), the write operationsto the destination_variable will not go to the CPU’s cache. If we will not immediately be reading from these values, this can improve performance because the writes won’t pollute the cache."
},
{
"code": null,
"e": 6161,
"s": 6117,
"text": "It is a threaded variant of vmapnt.Syntax :"
},
{
"code": null,
"e": 6243,
"s": 6161,
"text": "vmapntt(f, x::AbstractArray)\nvmapntt(f, x::AbstractArray, y::AbstractArray, ...)\n"
},
{
"code": null,
"e": 6327,
"s": 6243,
"text": "It is similar to vmapnt!, but uses Threads.@threads for parallel execution.Syntax :"
},
{
"code": null,
"e": 6403,
"s": 6327,
"text": "vmapntt!(f, destination_variable, x::AbstractArray, y::AbstractArray, ...)\n"
},
{
"code": null,
"e": 6517,
"s": 6403,
"text": "It is a SIMD-vectorized filter, returning an array containing the elements of x for which f returns true.Syntax :"
},
{
"code": null,
"e": 6547,
"s": 6517,
"text": "vfilter(f, x::AbstractArray)\n"
},
{
"code": null,
"e": 6636,
"s": 6547,
"text": "It is a SIMD-vectorized filter!, removing the element of x for which f is false.Syntax :"
},
{
"code": null,
"e": 6666,
"s": 6636,
"text": "vfilter(f, x::AbstractArray)\n"
},
{
"code": null,
"e": 6676,
"s": 6666,
"text": "Examples:"
},
{
"code": "# benchmark the vmapnt function@benchmark vmapnt!(f, $z, $x, $y) # change the number of threadsThreads.nthreads()Threads.nthreads() = 8Threads.nthreads() # benchmark the vmapntt function@benchmark vmapntt!(f, $z, $x, $y) # benchmark the filter against vfilter construct@benchmark filter(a -> a < 0.67, $x)@benchmark vfilter(a -> a < 0.67, $x)",
"e": 7022,
"s": 6676,
"text": null
},
{
"code": null,
"e": 7030,
"s": 7022,
"text": "Output:"
},
{
"code": null,
"e": 7036,
"s": 7030,
"text": "Julia"
},
{
"code": null,
"e": 7134,
"s": 7036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7151,
"s": 7134,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 7181,
"s": 7151,
"text": "String concatenation in Julia"
},
{
"code": null,
"e": 7241,
"s": 7181,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 7302,
"s": 7241,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 7336,
"s": 7302,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 7367,
"s": 7336,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 7395,
"s": 7367,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 7426,
"s": 7395,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 7442,
"s": 7426,
"text": "Tuples in Julia"
}
] |
Third Normal Form (3NF) | 31 Jul, 2019
Although Second Normal Form (2NF) relations have less redundancy than those in 1NF, they may still suffer from update anomalies. If we update only one tuple and not the other, the database would be in an inconsistent state. This update anomaly is caused by a transitive dependency. We need to remove such dependencies by progressing to Third Normal Form (3NF).
Third Normal Form (3NF):A relation is in third normal form, if there is no transitive dependency for non-prime attributes as well as it is in second normal form.
A relation is in 3NF if at least one of the following condition holds in every non-trivial function dependency X –> Y:
X is a super key.Y is a prime attribute (each element of Y is part of some candidate key).
X is a super key.
Y is a prime attribute (each element of Y is part of some candidate key).
In other words,
A relation that is in First and Second Normal Form and in which no non-primary-key attribute is transitively dependent on the primary key, then it is in Third Normal Form (3NF).
Note – If A->B and B->C are two FDs then A->C is called transitive dependency.
The normalization of 2NF relations to 3NF involves the removal of transitive dependencies. If a transitive dependency exists, we remove the transitively dependent attribute(s) from the relation by placing the attribute(s) in a new relation along with a copy of the determinant.
Consider the examples given below.
Example-1:In relation STUDENT given in Table 4,
FD set:{STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}
Candidate Key:{STUD_NO}
For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:
STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)
STATE_COUNTRY (STATE, COUNTRY)
Example-2:Consider relation R(A, B, C, D, E)
A -> BC,
CD -> E,
B -> D,
E -> A
All possible candidate keys in above relation are {A, E, CD, BC} All attribute are on right sides of all functional dependencies are prime.
Note –Third Normal Form (3NF) is considered adequate for normal relational database design because most of the 3NF tables are free of insertion, update, and deletion anomalies. Moreover, 3NF always ensures functional dependency preserving and lossless.
DBMS-Normalization
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL Trigger | Student Database
Introduction of B-Tree
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Jul, 2019"
},
{
"code": null,
"e": 413,
"s": 52,
"text": "Although Second Normal Form (2NF) relations have less redundancy than those in 1NF, they may still suffer from update anomalies. If we update only one tuple and not the other, the database would be in an inconsistent state. This update anomaly is caused by a transitive dependency. We need to remove such dependencies by progressing to Third Normal Form (3NF)."
},
{
"code": null,
"e": 575,
"s": 413,
"text": "Third Normal Form (3NF):A relation is in third normal form, if there is no transitive dependency for non-prime attributes as well as it is in second normal form."
},
{
"code": null,
"e": 694,
"s": 575,
"text": "A relation is in 3NF if at least one of the following condition holds in every non-trivial function dependency X –> Y:"
},
{
"code": null,
"e": 785,
"s": 694,
"text": "X is a super key.Y is a prime attribute (each element of Y is part of some candidate key)."
},
{
"code": null,
"e": 803,
"s": 785,
"text": "X is a super key."
},
{
"code": null,
"e": 877,
"s": 803,
"text": "Y is a prime attribute (each element of Y is part of some candidate key)."
},
{
"code": null,
"e": 893,
"s": 877,
"text": "In other words,"
},
{
"code": null,
"e": 1071,
"s": 893,
"text": "A relation that is in First and Second Normal Form and in which no non-primary-key attribute is transitively dependent on the primary key, then it is in Third Normal Form (3NF)."
},
{
"code": null,
"e": 1150,
"s": 1071,
"text": "Note – If A->B and B->C are two FDs then A->C is called transitive dependency."
},
{
"code": null,
"e": 1428,
"s": 1150,
"text": "The normalization of 2NF relations to 3NF involves the removal of transitive dependencies. If a transitive dependency exists, we remove the transitively dependent attribute(s) from the relation by placing the attribute(s) in a new relation along with a copy of the determinant."
},
{
"code": null,
"e": 1463,
"s": 1428,
"text": "Consider the examples given below."
},
{
"code": null,
"e": 1511,
"s": 1463,
"text": "Example-1:In relation STUDENT given in Table 4,"
},
{
"code": null,
"e": 1613,
"s": 1511,
"text": "FD set:{STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}"
},
{
"code": null,
"e": 1637,
"s": 1613,
"text": "Candidate Key:{STUD_NO}"
},
{
"code": null,
"e": 1966,
"s": 1637,
"text": "For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:"
},
{
"code": null,
"e": 2062,
"s": 1966,
"text": "STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE) \nSTATE_COUNTRY (STATE, COUNTRY) "
},
{
"code": null,
"e": 2107,
"s": 2062,
"text": "Example-2:Consider relation R(A, B, C, D, E)"
},
{
"code": null,
"e": 2143,
"s": 2107,
"text": "A -> BC,\nCD -> E, \nB -> D, \nE -> A "
},
{
"code": null,
"e": 2283,
"s": 2143,
"text": "All possible candidate keys in above relation are {A, E, CD, BC} All attribute are on right sides of all functional dependencies are prime."
},
{
"code": null,
"e": 2536,
"s": 2283,
"text": "Note –Third Normal Form (3NF) is considered adequate for normal relational database design because most of the 3NF tables are free of insertion, update, and deletion anomalies. Moreover, 3NF always ensures functional dependency preserving and lossless."
},
{
"code": null,
"e": 2555,
"s": 2536,
"text": "DBMS-Normalization"
},
{
"code": null,
"e": 2560,
"s": 2555,
"text": "DBMS"
},
{
"code": null,
"e": 2568,
"s": 2560,
"text": "GATE CS"
},
{
"code": null,
"e": 2573,
"s": 2568,
"text": "DBMS"
},
{
"code": null,
"e": 2671,
"s": 2573,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2682,
"s": 2671,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2735,
"s": 2682,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2793,
"s": 2735,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 2824,
"s": 2793,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 2847,
"s": 2824,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 2867,
"s": 2847,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 2880,
"s": 2867,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 2907,
"s": 2880,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 2956,
"s": 2907,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
How to Make Changes to The Application Deployed on Heroku ? | 11 Jul, 2022
Many of the times we need to make changes to our deployed project for some reason. Either we want to have a new version of the project, add new features to the project, remove a bug, or for some other reasons. If your project is deployed on Heroku Cloud Platform, you can easily make your changes using the CLI and deploy them to Heroku. In this blog, we will discuss the step-by-step process to make changes in your project and deploy it on Heroku. Let’s start first with the short introduction of Heroku...
Heroku is a cloud platform service that allows you to build, deliver, monitor, and scale apps. It is a container-based cloud Platform as a Service (PaaS). It provides the freedom to the developers to focus on the core product instead of getting distracted from maintaining servers, hardware, or infrastructure.
Prerequisite: Introduction and Installation of Heroku CLI
Heroku CLI can easily be downloaded and installed by the following the steps given here. Make sure to log in to Heroku CLI.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
After successful login, you will see the following in the terminal :
Open another terminal and use git to clone your repository.
$ heroku git:clone -a your_app
$ cd your_app
Make all the required changes in your project
$ git add .
$ git commit -am "changes made to the project"
$ git push heroku master
Enjoy! Your project is now successfully updated and deployed.
Now, in case if you want to change your main deploy branch from “master” to “main”(any other branch) for both manual and automatic deploys, you can do so by following these simple steps:
To do this we first need to create a new branch locally.
$ git checkout -b main
We need to delete the old branch so that the local environment only knows about the main branch.
$ git branch -D master
This will empty the remote repository but it will not impact the running application.
$ heroku repo:reset -a your_app
Finally, using the new default branch you can redeploy the application.
$ git push heroku main
Heroku Cloud
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 563,
"s": 53,
"text": "Many of the times we need to make changes to our deployed project for some reason. Either we want to have a new version of the project, add new features to the project, remove a bug, or for some other reasons. If your project is deployed on Heroku Cloud Platform, you can easily make your changes using the CLI and deploy them to Heroku. In this blog, we will discuss the step-by-step process to make changes in your project and deploy it on Heroku. Let’s start first with the short introduction of Heroku..."
},
{
"code": null,
"e": 875,
"s": 563,
"text": "Heroku is a cloud platform service that allows you to build, deliver, monitor, and scale apps. It is a container-based cloud Platform as a Service (PaaS). It provides the freedom to the developers to focus on the core product instead of getting distracted from maintaining servers, hardware, or infrastructure. "
},
{
"code": null,
"e": 933,
"s": 875,
"text": "Prerequisite: Introduction and Installation of Heroku CLI"
},
{
"code": null,
"e": 1057,
"s": 933,
"text": "Heroku CLI can easily be downloaded and installed by the following the steps given here. Make sure to log in to Heroku CLI."
},
{
"code": null,
"e": 1066,
"s": 1057,
"text": "Chapters"
},
{
"code": null,
"e": 1093,
"s": 1066,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1143,
"s": 1093,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1166,
"s": 1143,
"text": "captions off, selected"
},
{
"code": null,
"e": 1174,
"s": 1166,
"text": "English"
},
{
"code": null,
"e": 1198,
"s": 1174,
"text": "This is a modal window."
},
{
"code": null,
"e": 1267,
"s": 1198,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1289,
"s": 1267,
"text": "End of dialog window."
},
{
"code": null,
"e": 1358,
"s": 1289,
"text": "After successful login, you will see the following in the terminal :"
},
{
"code": null,
"e": 1418,
"s": 1358,
"text": "Open another terminal and use git to clone your repository."
},
{
"code": null,
"e": 1464,
"s": 1418,
"text": "$ heroku git:clone -a your_app\n$ cd your_app\n"
},
{
"code": null,
"e": 1511,
"s": 1464,
"text": "Make all the required changes in your project "
},
{
"code": null,
"e": 1596,
"s": 1511,
"text": "$ git add .\n$ git commit -am \"changes made to the project\"\n$ git push heroku master\n"
},
{
"code": null,
"e": 1658,
"s": 1596,
"text": "Enjoy! Your project is now successfully updated and deployed."
},
{
"code": null,
"e": 1845,
"s": 1658,
"text": "Now, in case if you want to change your main deploy branch from “master” to “main”(any other branch) for both manual and automatic deploys, you can do so by following these simple steps:"
},
{
"code": null,
"e": 1902,
"s": 1845,
"text": "To do this we first need to create a new branch locally."
},
{
"code": null,
"e": 1926,
"s": 1902,
"text": "$ git checkout -b main\n"
},
{
"code": null,
"e": 2023,
"s": 1926,
"text": "We need to delete the old branch so that the local environment only knows about the main branch."
},
{
"code": null,
"e": 2047,
"s": 2023,
"text": "$ git branch -D master\n"
},
{
"code": null,
"e": 2133,
"s": 2047,
"text": "This will empty the remote repository but it will not impact the running application."
},
{
"code": null,
"e": 2166,
"s": 2133,
"text": "$ heroku repo:reset -a your_app\n"
},
{
"code": null,
"e": 2238,
"s": 2166,
"text": "Finally, using the new default branch you can redeploy the application."
},
{
"code": null,
"e": 2262,
"s": 2238,
"text": "$ git push heroku main\n"
},
{
"code": null,
"e": 2275,
"s": 2262,
"text": "Heroku Cloud"
},
{
"code": null,
"e": 2282,
"s": 2275,
"text": "How To"
}
] |
Stream In Java | 09 Oct, 2019
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.The features of Java stream are –
A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Different Operations On Streams-Intermediate Operations:
map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.List number = Arrays.asList(2,3,4,5);List square = number.stream().map(x->x*x).collect(Collectors.toList());filter: The filter method is used to select elements as per the Predicate passed as argument.List names = Arrays.asList("Reflection","Collection","Stream");List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());sorted: The sorted method is used to sort the stream.List names = Arrays.asList("Reflection","Collection","Stream");List result = names.stream().sorted().collect(Collectors.toList());
map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.List number = Arrays.asList(2,3,4,5);List square = number.stream().map(x->x*x).collect(Collectors.toList());
filter: The filter method is used to select elements as per the Predicate passed as argument.List names = Arrays.asList("Reflection","Collection","Stream");List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
sorted: The sorted method is used to sort the stream.List names = Arrays.asList("Reflection","Collection","Stream");List result = names.stream().sorted().collect(Collectors.toList());
Terminal Operations:
collect: The collect method is used to return the result of the intermediate operations performed on the stream.List number = Arrays.asList(2,3,4,5,3);Set square = number.stream().map(x->x*x).collect(Collectors.toSet());forEach: The forEach method is used to iterate through every element of the stream.List number = Arrays.asList(2,3,4,5);number.stream().map(x->x*x).forEach(y->System.out.println(y));reduce: The reduce method is used to reduce the elements of a stream to a single value.The reduce method takes a BinaryOperator as a parameter.List number = Arrays.asList(2,3,4,5);int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);Here ans variable is assigned 0 as the initial value and i is added to it .
collect: The collect method is used to return the result of the intermediate operations performed on the stream.List number = Arrays.asList(2,3,4,5,3);Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
forEach: The forEach method is used to iterate through every element of the stream.List number = Arrays.asList(2,3,4,5);number.stream().map(x->x*x).forEach(y->System.out.println(y));
reduce: The reduce method is used to reduce the elements of a stream to a single value.The reduce method takes a BinaryOperator as a parameter.List number = Arrays.asList(2,3,4,5);int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);Here ans variable is assigned 0 as the initial value and i is added to it .
List number = Arrays.asList(2,3,4,5);int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
Here ans variable is assigned 0 as the initial value and i is added to it .
Program to demonstrate the use of Stream
//a simple program to demonstrate the use of stream in javaimport java.util.*;import java.util.stream.*; class Demo{ public static void main(String args[]) { // create a list of integers List<Integer> number = Arrays.asList(2,3,4,5); // demonstration of map method List<Integer> square = number.stream().map(x -> x*x). collect(Collectors.toList()); System.out.println(square); // create a list of String List<String> names = Arrays.asList("Reflection","Collection","Stream"); // demonstration of filter method List<String> result = names.stream().filter(s->s.startsWith("S")). collect(Collectors.toList()); System.out.println(result); // demonstration of sorted method List<String> show = names.stream().sorted().collect(Collectors.toList()); System.out.println(show); // create a list of integers List<Integer> numbers = Arrays.asList(2,3,4,5,2); // collect method returns a set Set<Integer> squareSet = numbers.stream().map(x->x*x).collect(Collectors.toSet()); System.out.println(squareSet); // demonstration of forEach method number.stream().map(x->x*x).forEach(y->System.out.println(y)); // demonstration of reduce method int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i); System.out.println(even); }}
Output:
[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6
Important Points/Observations:
A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described.Stream is used to compute elements as per the pipelined methods without altering the original value of the object.
A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described.
Stream is used to compute elements as per the pipelined methods without altering the original value of the object.
This article is contributed by Akash Ojha .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
KHEM RAJ MEENA
FredrikKemling
brij2804
Java - util package
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Oct, 2019"
},
{
"code": null,
"e": 285,
"s": 54,
"text": "Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.The features of Java stream are –"
},
{
"code": null,
"e": 387,
"s": 285,
"text": "A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels."
},
{
"code": null,
"e": 496,
"s": 387,
"text": "Streams don’t change the original data structure, they only provide the result as per the pipelined methods."
},
{
"code": null,
"e": 703,
"s": 496,
"text": "Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result."
},
{
"code": null,
"e": 760,
"s": 703,
"text": "Different Operations On Streams-Intermediate Operations:"
},
{
"code": null,
"e": 1431,
"s": 760,
"text": "map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.List number = Arrays.asList(2,3,4,5);List square = number.stream().map(x->x*x).collect(Collectors.toList());filter: The filter method is used to select elements as per the Predicate passed as argument.List names = Arrays.asList(\"Reflection\",\"Collection\",\"Stream\");List result = names.stream().filter(s->s.startsWith(\"S\")).collect(Collectors.toList());sorted: The sorted method is used to sort the stream.List names = Arrays.asList(\"Reflection\",\"Collection\",\"Stream\");List result = names.stream().sorted().collect(Collectors.toList());"
},
{
"code": null,
"e": 1676,
"s": 1431,
"text": "map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.List number = Arrays.asList(2,3,4,5);List square = number.stream().map(x->x*x).collect(Collectors.toList());"
},
{
"code": null,
"e": 1920,
"s": 1676,
"text": "filter: The filter method is used to select elements as per the Predicate passed as argument.List names = Arrays.asList(\"Reflection\",\"Collection\",\"Stream\");List result = names.stream().filter(s->s.startsWith(\"S\")).collect(Collectors.toList());"
},
{
"code": null,
"e": 2104,
"s": 1920,
"text": "sorted: The sorted method is used to sort the stream.List names = Arrays.asList(\"Reflection\",\"Collection\",\"Stream\");List result = names.stream().sorted().collect(Collectors.toList());"
},
{
"code": null,
"e": 2125,
"s": 2104,
"text": "Terminal Operations:"
},
{
"code": null,
"e": 2854,
"s": 2125,
"text": "collect: The collect method is used to return the result of the intermediate operations performed on the stream.List number = Arrays.asList(2,3,4,5,3);Set square = number.stream().map(x->x*x).collect(Collectors.toSet());forEach: The forEach method is used to iterate through every element of the stream.List number = Arrays.asList(2,3,4,5);number.stream().map(x->x*x).forEach(y->System.out.println(y));reduce: The reduce method is used to reduce the elements of a stream to a single value.The reduce method takes a BinaryOperator as a parameter.List number = Arrays.asList(2,3,4,5);int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);Here ans variable is assigned 0 as the initial value and i is added to it ."
},
{
"code": null,
"e": 3075,
"s": 2854,
"text": "collect: The collect method is used to return the result of the intermediate operations performed on the stream.List number = Arrays.asList(2,3,4,5,3);Set square = number.stream().map(x->x*x).collect(Collectors.toSet());"
},
{
"code": null,
"e": 3258,
"s": 3075,
"text": "forEach: The forEach method is used to iterate through every element of the stream.List number = Arrays.asList(2,3,4,5);number.stream().map(x->x*x).forEach(y->System.out.println(y));"
},
{
"code": null,
"e": 3585,
"s": 3258,
"text": "reduce: The reduce method is used to reduce the elements of a stream to a single value.The reduce method takes a BinaryOperator as a parameter.List number = Arrays.asList(2,3,4,5);int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);Here ans variable is assigned 0 as the initial value and i is added to it ."
},
{
"code": null,
"e": 3694,
"s": 3585,
"text": "List number = Arrays.asList(2,3,4,5);int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);"
},
{
"code": null,
"e": 3770,
"s": 3694,
"text": "Here ans variable is assigned 0 as the initial value and i is added to it ."
},
{
"code": null,
"e": 3811,
"s": 3770,
"text": "Program to demonstrate the use of Stream"
},
{
"code": "//a simple program to demonstrate the use of stream in javaimport java.util.*;import java.util.stream.*; class Demo{ public static void main(String args[]) { // create a list of integers List<Integer> number = Arrays.asList(2,3,4,5); // demonstration of map method List<Integer> square = number.stream().map(x -> x*x). collect(Collectors.toList()); System.out.println(square); // create a list of String List<String> names = Arrays.asList(\"Reflection\",\"Collection\",\"Stream\"); // demonstration of filter method List<String> result = names.stream().filter(s->s.startsWith(\"S\")). collect(Collectors.toList()); System.out.println(result); // demonstration of sorted method List<String> show = names.stream().sorted().collect(Collectors.toList()); System.out.println(show); // create a list of integers List<Integer> numbers = Arrays.asList(2,3,4,5,2); // collect method returns a set Set<Integer> squareSet = numbers.stream().map(x->x*x).collect(Collectors.toSet()); System.out.println(squareSet); // demonstration of forEach method number.stream().map(x->x*x).forEach(y->System.out.println(y)); // demonstration of reduce method int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i); System.out.println(even); }}",
"e": 5222,
"s": 3811,
"text": null
},
{
"code": null,
"e": 5230,
"s": 5222,
"text": "Output:"
},
{
"code": null,
"e": 5315,
"s": 5230,
"text": "[4, 9, 16, 25]\n[Stream]\n[Collection, Reflection, Stream]\n[16, 4, 9, 25]\n4\n9\n16\n25\n6\n"
},
{
"code": null,
"e": 5346,
"s": 5315,
"text": "Important Points/Observations:"
},
{
"code": null,
"e": 5664,
"s": 5346,
"text": "A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described.Stream is used to compute elements as per the pipelined methods without altering the original value of the object."
},
{
"code": null,
"e": 5868,
"s": 5664,
"text": "A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described."
},
{
"code": null,
"e": 5983,
"s": 5868,
"text": "Stream is used to compute elements as per the pipelined methods without altering the original value of the object."
},
{
"code": null,
"e": 6281,
"s": 5983,
"text": "This article is contributed by Akash Ojha .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6406,
"s": 6281,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6421,
"s": 6406,
"text": "KHEM RAJ MEENA"
},
{
"code": null,
"e": 6436,
"s": 6421,
"text": "FredrikKemling"
},
{
"code": null,
"e": 6445,
"s": 6436,
"text": "brij2804"
},
{
"code": null,
"e": 6465,
"s": 6445,
"text": "Java - util package"
},
{
"code": null,
"e": 6477,
"s": 6465,
"text": "java-stream"
},
{
"code": null,
"e": 6482,
"s": 6477,
"text": "Java"
},
{
"code": null,
"e": 6487,
"s": 6482,
"text": "Java"
}
] |
Python program to convert float decimal to Octal number | 30 Jun, 2020
Python doesn’t support any inbuilt function to easily convert floating point decimal numbers to octal representation. Let’s do this manually. Approach : To convert a decimal number having fractional part into octal, first convert the integer part into octal form and then fractional part into octal form and finally combine the two results to get the final answer.For Integer Part, Keep dividing the number by 8 and noting down the remainder until and unless the dividend is less than 8 and copy all the remainders together.For the Decimal Part, Keep multiplying the decimal part with 8 until and unless we get 0 left as fractional part. After multiplying the first time, note down an integral part and then again multiply the decimal part of new value by 8 and keep doing this until perfect number is reached.
Above steps can be written as :7(base 10) = 7(base 8) and .16(base 10) = .1217(base 8)
Now, to get the octal of the decimal number 7.16, merge the two octal results.(7)10 = (7)8
(0.16)10 = (0.1217...)8So, (7.16)10 = (7.1217...)8or, (7.16)10 = (7.1217)8 (approx. value)
Below is the implementation :
# Python3 program to demonstrate# octal type conversion # Function returns the octal representation# of the value passed as parameters. 'number'# is floating point decimal number and 'places'# is the number of decimal placesdef float_octal(number, places = 3): # split() separates whole number and decimal # part and stores it in two separate variables whole, dec = str(number).split(".") # Convert both whole number and decimal # part from string type to integer type whole = int(whole) dec = int (dec) # Convert the whole number part to it's # respective octal form and remove the # "0o" from it. res = oct(whole).lstrip("0o") + "." # Iterate the number of times we want # the number of decimal places to be for x in range(places): # Multiply the decimal value by 8 and separate # the whole number part and decimal part whole, dec = str((decimal_converter(dec)) * 8).split(".") # Convert the decimal part # to integer again dec = int(dec) # keep adding the integer parts # received to the result variable res += whole return res # Function converts the value passed as# parameter to it's respective decimal# representationdef decimal_converter(num): while num > 1: num /= 10 return num # Driver Code # Take the user input for # the floating point numbern = input("Enter your floating point value : \n") # Take user input for the number of decimal # places user would like the result asp = int(input("Enter the number of decimal places of the result : \n")) print(float_octal(n, places = p))
Output :
Enter your floating point value :
7.16
Enter the number of decimal places of the result :
10
7.1217273146
Enter your floating point value :
7.1234
Enter the number of decimal places of the result :
5
7.07713
nidhi_biet
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 839,
"s": 28,
"text": "Python doesn’t support any inbuilt function to easily convert floating point decimal numbers to octal representation. Let’s do this manually. Approach : To convert a decimal number having fractional part into octal, first convert the integer part into octal form and then fractional part into octal form and finally combine the two results to get the final answer.For Integer Part, Keep dividing the number by 8 and noting down the remainder until and unless the dividend is less than 8 and copy all the remainders together.For the Decimal Part, Keep multiplying the decimal part with 8 until and unless we get 0 left as fractional part. After multiplying the first time, note down an integral part and then again multiply the decimal part of new value by 8 and keep doing this until perfect number is reached."
},
{
"code": null,
"e": 926,
"s": 839,
"text": "Above steps can be written as :7(base 10) = 7(base 8) and .16(base 10) = .1217(base 8)"
},
{
"code": null,
"e": 1017,
"s": 926,
"text": "Now, to get the octal of the decimal number 7.16, merge the two octal results.(7)10 = (7)8"
},
{
"code": null,
"e": 1112,
"s": 1017,
"text": " (0.16)10 = (0.1217...)8So, (7.16)10 = (7.1217...)8or, (7.16)10 = (7.1217)8 (approx. value)"
},
{
"code": null,
"e": 1142,
"s": 1112,
"text": "Below is the implementation :"
},
{
"code": "# Python3 program to demonstrate# octal type conversion # Function returns the octal representation# of the value passed as parameters. 'number'# is floating point decimal number and 'places'# is the number of decimal placesdef float_octal(number, places = 3): # split() separates whole number and decimal # part and stores it in two separate variables whole, dec = str(number).split(\".\") # Convert both whole number and decimal # part from string type to integer type whole = int(whole) dec = int (dec) # Convert the whole number part to it's # respective octal form and remove the # \"0o\" from it. res = oct(whole).lstrip(\"0o\") + \".\" # Iterate the number of times we want # the number of decimal places to be for x in range(places): # Multiply the decimal value by 8 and separate # the whole number part and decimal part whole, dec = str((decimal_converter(dec)) * 8).split(\".\") # Convert the decimal part # to integer again dec = int(dec) # keep adding the integer parts # received to the result variable res += whole return res # Function converts the value passed as# parameter to it's respective decimal# representationdef decimal_converter(num): while num > 1: num /= 10 return num # Driver Code # Take the user input for # the floating point numbern = input(\"Enter your floating point value : \\n\") # Take user input for the number of decimal # places user would like the result asp = int(input(\"Enter the number of decimal places of the result : \\n\")) print(float_octal(n, places = p))",
"e": 2783,
"s": 1142,
"text": null
},
{
"code": null,
"e": 2792,
"s": 2783,
"text": "Output :"
},
{
"code": null,
"e": 2901,
"s": 2792,
"text": "Enter your floating point value :\n7.16\n\nEnter the number of decimal places of the result :\n10\n\n7.1217273146\n"
},
{
"code": null,
"e": 3007,
"s": 2901,
"text": "Enter your floating point value :\n7.1234\n\nEnter the number of decimal places of the result : \n5\n\n7.07713\n"
},
{
"code": null,
"e": 3018,
"s": 3007,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3025,
"s": 3018,
"text": "Python"
},
{
"code": null,
"e": 3041,
"s": 3025,
"text": "Python Programs"
},
{
"code": null,
"e": 3139,
"s": 3041,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3157,
"s": 3139,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3199,
"s": 3157,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3221,
"s": 3199,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3256,
"s": 3221,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3282,
"s": 3256,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3325,
"s": 3282,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3347,
"s": 3325,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3386,
"s": 3347,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3424,
"s": 3386,
"text": "Python | Convert a list to dictionary"
}
] |
LiveData in Android Architecture Components | 21 Sep, 2021
LiveData is one of the android architecture components. LiveData is an observable data holder class. What is the meaning of observable here the observable means live data can be observed by other components like activity and fragments (Ui Controller). The most important thing about LiveData is it has the knowledge about the Life cycle of its observers like activity or fragment. That means Live data only updates the app components like Activity or Fragments which are in active life cycle state. LiveData notifies the observer(Activity or Fragment) which are in Started or Resumed life cycle state. Inactive observers registered to watch LiveData objects aren’t notified about changes. Here inactive observers mean which are not in the state of Started or Resumed. One can register an observer paired with an object that implements the LifecycleOwner interface which we will see in our example. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED.
This component is an observable data holder class i.e, the contained value can be observed. LiveData is a lifecycle-aware component and thus it performs its functions according to the lifecycle state of other application components. Further, if the observer’s lifecycle state is active i.e., either STARTED or RESUMED, only then LiveData updates the app component. LiveData always checks the observer’s state before making any update to ensure that the observer must be active to receive it. If the observer’s lifecycle state is destroyed, LiveData is capable to remove it, and thus it avoids memory leaks. It makes the task of data synchronization easier.
It is necessary to implement onActive and onInactive methods by LiveData:
class LocationLiveData(context: Context)
: LiveData<Location>(), AnkoLogger, LocationListener {
private val locationManager: LocationManager =
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
override fun onActive() {
info(“onActive”)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, this)
}
override fun onInactive() {
info(“onInactive”)
locationManager.removeUpdates(this)
}
// ....
}
In order to observe a LiveData Component observer(LifecycleOwner, Observer<T>) method is called:
fun observeLocation() {
val location = LocationLiveData(this)
location.observe(this,
Observer { location ->
info(“location: $location”)
})
}
}
In this example we will just create a simple counter app, that just counts 5 seconds, you can do anything using LiveData but for now let’s build this small app.
Step 1: Add these dependencies in your build.gradle file
def lifecycle_version = “2.3.0”
// ViewModel
implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”
// LiveData
implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version”
implementation “androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version”
implementation “androidx.core:core-ktx:1.3.2”
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" android:textSize="25sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Create a Kotlin class file MainActivityViewModel.kt. Our MainActivity class file extends the ViewModel class.
Refer to this article: How to Create Classes in Android Studio?
Kotlin
import androidx.lifecycle.ViewModel class MainActivityViewModel:ViewModel() { private val _seconds = MutableLiveData<Int>() private val _finished = MutableLiveData<Boolean>() // getter method for seconds var fun seconds():LiveData<Int>{ return _seconds } // getter method for finished var fun finished():LiveData<Boolean>{ return _finished } // Counter method that uses CountDownTimer() fun startCounter(){ // you can change the millisInFuture value object : CountDownTimer(5000, 100) { override fun onTick(millisUntilFinished: Long) { val time = millisUntilFinished / 1000 // setting the count value _seconds.value = time.toInt() } override fun onFinish() { // if millisInFuture completed // it set the value true _finished.value = true } }.start() }}
Note: Here we are using MutableLiveData right. but the question is why? because there is already LiveData is available, MutableLiveData extends LiveData class and two functions setValue() and postValue() are publicly available for use.
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file.
Kotlin
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // creating instance of our ViewModel class val viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java) // calling start counter methods which is in our viewmodel class viewModel.startCounter() // observing the second value of our view model class viewModel.seconds().observe(this, Observer { // setting textview value textView.text = it.toString() }) viewModel.finished().observe(this, Observer { if(it){ // if count time finished it set the value textView.text = "Finished" } }) }}
Note: Here inside Observe() “this” is the Life cycle owner as we discussed above to observe the value, we should pass the Lifecycle Owner. Here this means MainActivity which is the observer here.
Output:
No need to update UI every time: LiveData follows the observer pattern. LiveData notifies Observer objects when there is any change occurs.
No memory leaks: Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.
No more manual lifecycle handling: UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.
Proper configuration changes: If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.
gabaa406
Android-Jetpack
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Kotlin Array
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 1053,
"s": 28,
"text": "LiveData is one of the android architecture components. LiveData is an observable data holder class. What is the meaning of observable here the observable means live data can be observed by other components like activity and fragments (Ui Controller). The most important thing about LiveData is it has the knowledge about the Life cycle of its observers like activity or fragment. That means Live data only updates the app components like Activity or Fragments which are in active life cycle state. LiveData notifies the observer(Activity or Fragment) which are in Started or Resumed life cycle state. Inactive observers registered to watch LiveData objects aren’t notified about changes. Here inactive observers mean which are not in the state of Started or Resumed. One can register an observer paired with an object that implements the LifecycleOwner interface which we will see in our example. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED."
},
{
"code": null,
"e": 1710,
"s": 1053,
"text": "This component is an observable data holder class i.e, the contained value can be observed. LiveData is a lifecycle-aware component and thus it performs its functions according to the lifecycle state of other application components. Further, if the observer’s lifecycle state is active i.e., either STARTED or RESUMED, only then LiveData updates the app component. LiveData always checks the observer’s state before making any update to ensure that the observer must be active to receive it. If the observer’s lifecycle state is destroyed, LiveData is capable to remove it, and thus it avoids memory leaks. It makes the task of data synchronization easier."
},
{
"code": null,
"e": 1784,
"s": 1710,
"text": "It is necessary to implement onActive and onInactive methods by LiveData:"
},
{
"code": null,
"e": 1825,
"s": 1784,
"text": "class LocationLiveData(context: Context)"
},
{
"code": null,
"e": 1883,
"s": 1825,
"text": " : LiveData<Location>(), AnkoLogger, LocationListener {"
},
{
"code": null,
"e": 1933,
"s": 1883,
"text": " private val locationManager: LocationManager ="
},
{
"code": null,
"e": 2014,
"s": 1933,
"text": " context.getSystemService(Context.LOCATION_SERVICE) as LocationManager"
},
{
"code": null,
"e": 2043,
"s": 2014,
"text": " override fun onActive() {"
},
{
"code": null,
"e": 2067,
"s": 2043,
"text": " info(“onActive”)"
},
{
"code": null,
"e": 2156,
"s": 2067,
"text": " locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, this)"
},
{
"code": null,
"e": 2161,
"s": 2156,
"text": " }"
},
{
"code": null,
"e": 2192,
"s": 2161,
"text": " override fun onInactive() {"
},
{
"code": null,
"e": 2218,
"s": 2192,
"text": " info(“onInactive”)"
},
{
"code": null,
"e": 2261,
"s": 2218,
"text": " locationManager.removeUpdates(this)"
},
{
"code": null,
"e": 2266,
"s": 2261,
"text": " }"
},
{
"code": null,
"e": 2277,
"s": 2266,
"text": " // ...."
},
{
"code": null,
"e": 2279,
"s": 2277,
"text": "}"
},
{
"code": null,
"e": 2376,
"s": 2279,
"text": "In order to observe a LiveData Component observer(LifecycleOwner, Observer<T>) method is called:"
},
{
"code": null,
"e": 2400,
"s": 2376,
"text": "fun observeLocation() {"
},
{
"code": null,
"e": 2445,
"s": 2400,
"text": " val location = LocationLiveData(this)"
},
{
"code": null,
"e": 2475,
"s": 2445,
"text": " location.observe(this,"
},
{
"code": null,
"e": 2513,
"s": 2475,
"text": " Observer { location ->"
},
{
"code": null,
"e": 2560,
"s": 2513,
"text": " info(“location: $location”)"
},
{
"code": null,
"e": 2578,
"s": 2560,
"text": " })"
},
{
"code": null,
"e": 2583,
"s": 2578,
"text": " }"
},
{
"code": null,
"e": 2585,
"s": 2583,
"text": "}"
},
{
"code": null,
"e": 2747,
"s": 2585,
"text": "In this example we will just create a simple counter app, that just counts 5 seconds, you can do anything using LiveData but for now let’s build this small app. "
},
{
"code": null,
"e": 2804,
"s": 2747,
"text": "Step 1: Add these dependencies in your build.gradle file"
},
{
"code": null,
"e": 2836,
"s": 2804,
"text": "def lifecycle_version = “2.3.0”"
},
{
"code": null,
"e": 2849,
"s": 2836,
"text": "// ViewModel"
},
{
"code": null,
"e": 2928,
"s": 2849,
"text": "implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”"
},
{
"code": null,
"e": 2940,
"s": 2928,
"text": "// LiveData"
},
{
"code": null,
"e": 3018,
"s": 2940,
"text": "implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version”"
},
{
"code": null,
"e": 3095,
"s": 3018,
"text": "implementation “androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version”"
},
{
"code": null,
"e": 3141,
"s": 3095,
"text": "implementation “androidx.core:core-ktx:1.3.2”"
},
{
"code": null,
"e": 3189,
"s": 3141,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3331,
"s": 3189,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 3335,
"s": 3331,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"0\" android:textSize=\"25sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 4156,
"s": 3335,
"text": null
},
{
"code": null,
"e": 4276,
"s": 4156,
"text": " Step 3: Create a Kotlin class file MainActivityViewModel.kt. Our MainActivity class file extends the ViewModel class. "
},
{
"code": null,
"e": 4340,
"s": 4276,
"text": "Refer to this article: How to Create Classes in Android Studio?"
},
{
"code": null,
"e": 4347,
"s": 4340,
"text": "Kotlin"
},
{
"code": "import androidx.lifecycle.ViewModel class MainActivityViewModel:ViewModel() { private val _seconds = MutableLiveData<Int>() private val _finished = MutableLiveData<Boolean>() // getter method for seconds var fun seconds():LiveData<Int>{ return _seconds } // getter method for finished var fun finished():LiveData<Boolean>{ return _finished } // Counter method that uses CountDownTimer() fun startCounter(){ // you can change the millisInFuture value object : CountDownTimer(5000, 100) { override fun onTick(millisUntilFinished: Long) { val time = millisUntilFinished / 1000 // setting the count value _seconds.value = time.toInt() } override fun onFinish() { // if millisInFuture completed // it set the value true _finished.value = true } }.start() }}",
"e": 5336,
"s": 4347,
"text": null
},
{
"code": null,
"e": 5575,
"s": 5339,
"text": "Note: Here we are using MutableLiveData right. but the question is why? because there is already LiveData is available, MutableLiveData extends LiveData class and two functions setValue() and postValue() are publicly available for use."
},
{
"code": null,
"e": 5621,
"s": 5575,
"text": "Step 4: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 5735,
"s": 5621,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. "
},
{
"code": null,
"e": 5742,
"s": 5735,
"text": "Kotlin"
},
{
"code": "class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // creating instance of our ViewModel class val viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java) // calling start counter methods which is in our viewmodel class viewModel.startCounter() // observing the second value of our view model class viewModel.seconds().observe(this, Observer { // setting textview value textView.text = it.toString() }) viewModel.finished().observe(this, Observer { if(it){ // if count time finished it set the value textView.text = \"Finished\" } }) }}",
"e": 6605,
"s": 5742,
"text": null
},
{
"code": null,
"e": 6801,
"s": 6605,
"text": "Note: Here inside Observe() “this” is the Life cycle owner as we discussed above to observe the value, we should pass the Lifecycle Owner. Here this means MainActivity which is the observer here."
},
{
"code": null,
"e": 6810,
"s": 6801,
"text": "Output: "
},
{
"code": null,
"e": 6950,
"s": 6810,
"text": "No need to update UI every time: LiveData follows the observer pattern. LiveData notifies Observer objects when there is any change occurs."
},
{
"code": null,
"e": 7084,
"s": 6950,
"text": "No memory leaks: Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed."
},
{
"code": null,
"e": 7316,
"s": 7084,
"text": "No more manual lifecycle handling: UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing."
},
{
"code": null,
"e": 7490,
"s": 7316,
"text": "Proper configuration changes: If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data."
},
{
"code": null,
"e": 7501,
"s": 7492,
"text": "gabaa406"
},
{
"code": null,
"e": 7517,
"s": 7501,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 7532,
"s": 7517,
"text": "Kotlin Android"
},
{
"code": null,
"e": 7539,
"s": 7532,
"text": "Picked"
},
{
"code": null,
"e": 7547,
"s": 7539,
"text": "Android"
},
{
"code": null,
"e": 7554,
"s": 7547,
"text": "Kotlin"
},
{
"code": null,
"e": 7562,
"s": 7554,
"text": "Android"
},
{
"code": null,
"e": 7660,
"s": 7562,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7729,
"s": 7660,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 7761,
"s": 7729,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 7800,
"s": 7761,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 7849,
"s": 7800,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 7891,
"s": 7849,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 7960,
"s": 7891,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 7979,
"s": 7960,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 7992,
"s": 7979,
"text": "Kotlin Array"
},
{
"code": null,
"e": 8041,
"s": 7992,
"text": "How to Communicate Between Fragments in Android?"
}
] |
Minimum cost to fill given weight in a bag | 03 Jun, 2022
You are given a bag of size W kg and you are provided costs of packets different weights of oranges in array cost[] where cost[i] is basically the cost of ‘i’ kg packet of oranges. Where cost[i] = -1 means that ‘i’ kg packet of orange is unavailableFind the minimum total cost to buy exactly W kg oranges and if it is not possible to buy exactly W kg oranges then print -1. It may be assumed that there is an infinite supply of all available packet types.Note: array starts from index 1.
Examples:
Input : W = 5, cost[] = {20, 10, 4, 50, 100}
Output : 14
We can choose two oranges to minimize cost. First
orange of 2Kg and cost 10. Second orange of 3Kg
and cost 4.
Input : W = 5, cost[] = {1, 10, 4, 50, 100}
Output : 5
We can choose five oranges of weight 1 kg.
Input : W = 5, cost[] = {1, 2, 3, 4, 5}
Output : 5
Costs of 1, 2, 3, 4 and 5 kg packets are 1, 2, 3,
4 and 5 Rs respectively.
We choose packet of 5kg having cost 5 for minimum
cost to get 5Kg oranges.
Input : W = 5, cost[] = {-1, -1, 4, 5, -1}
Output : -1
Packets of size 1, 2 and 5 kg are unavailable
because they have cost -1. Cost of 3 kg packet
is 4 Rs and of 4 kg is 5 Rs. Here we have only
weights 3 and 4 so by using these two we can
not make exactly W kg weight, therefore answer
is -1.
This problem is can be reduced to Unbounded Knapsack. So in the cost array, we first ignore those packets which are not available i.e; cost is -1 and then traverse the cost array and create two array val[] for storing the cost of ‘i’ kg packet of orange and wt[] for storing weight of the corresponding packet. Suppose cost[i] = 50 so the weight of the packet will be i and the cost will be 50. Algorithm :
Create matrix min_cost[n+1][W+1], where n is number of distinct weighted packets of orange and W is the maximum capacity of the bag.
Initialize the 0th row with INF (infinity) and 0th Column with 0.
Now fill the matrixif wt[i-1] > j then min_cost[i][j] = min_cost[i-1][j] ;if wt[i-1] <= j then min_cost[i][j] = min(min_cost[i-1][j], val[i-1] + min_cost[i][j-wt[i-1]]);
if wt[i-1] > j then min_cost[i][j] = min_cost[i-1][j] ;
if wt[i-1] <= j then min_cost[i][j] = min(min_cost[i-1][j], val[i-1] + min_cost[i][j-wt[i-1]]);
If min_cost[n][W]==INF then output will be -1 because this means that we cant not make make weight W by using these weights else output will be min_cost[n][W].
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum cost to get exactly// W Kg with given packets#include<bits/stdc++.h>#define INF 1000000using namespace std; // cost[] initial cost array including unavailable packet// W capacity of bagint MinimumCost(int cost[], int n, int W){ // val[] and wt[] arrays // val[] array to store cost of 'i' kg packet of orange // wt[] array weight of packet of orange vector<int> val, wt; // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available number // of distinct weighted packets int size = 0; for (int i=0; i<n; i++) { if (cost[i]!= -1) { val.push_back(cost[i]); wt.push_back(i+1); size++; } } n = size; int min_cost[n+1][W+1]; // fill 0th row with infinity for (int i=0; i<=W; i++) min_cost[0][i] = INF; // fill 0'th column with 0 for (int i=1; i<=n; i++) min_cost[i][0] = 0; // now check for each weight one by one and fill the // matrix according to the condition for (int i=1; i<=n; i++) { for (int j=1; j<=W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt[i-1] > j) min_cost[i][j] = min_cost[i-1][j]; // here we check we get minimum cost either // by including it or excluding it else min_cost[i][j] = min(min_cost[i-1][j], min_cost[i][j-wt[i-1]] + val[i-1]); } } // exactly weight W can not be made by given weights return (min_cost[n][W]==INF)? -1: min_cost[n][W];} // Driver program to run the test caseint main(){ int cost[] = {1, 2, 3, 4, 5}, W = 5; int n = sizeof(cost)/sizeof(cost[0]); cout << MinimumCost(cost, n, W); return 0;}
// Java Code for Minimum cost to// fill given weight in a bagimport java.util.*; class GFG { // cost[] initial cost array including // unavailable packet W capacity of bag public static int MinimumCost(int cost[], int n, int W) { // val[] and wt[] arrays // val[] array to store cost of 'i' kg // packet of orange wt[] array weight of // packet of orange Vector<Integer> val = new Vector<Integer>(); Vector<Integer> wt = new Vector<Integer>(); // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available // number of distinct weighted packets int size = 0; for (int i = 0; i < n; i++) { if (cost[i] != -1) { val.add(cost[i]); wt.add(i + 1); size++; } } n = size; int min_cost[][] = new int[n+1][W+1]; // fill 0th row with infinity for (int i = 0; i <= W; i++) min_cost[0][i] = Integer.MAX_VALUE; // fill 0'th column with 0 for (int i = 1; i <= n; i++) min_cost[i][0] = 0; // now check for each weight one by one and // fill the matrix according to the condition for (int i = 1; i <= n; i++) { for (int j = 1; j <= W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt.get(i-1) > j) min_cost[i][j] = min_cost[i-1][j]; // here we check we get minimum cost // either by including it or excluding // it else min_cost[i][j] = Math.min(min_cost[i-1][j], min_cost[i][j-wt.get(i-1)] + val.get(i-1)); } } // exactly weight W can not be made by // given weights return (min_cost[n][W] == Integer.MAX_VALUE)? -1: min_cost[n][W]; } /* Driver program to test above function */ public static void main(String[] args) { int cost[] = {1, 2, 3, 4, 5}, W = 5; int n = cost.length; System.out.println(MinimumCost(cost, n, W)); }}// This code is contributed by Arnav Kr. Mandal.
# Python program to find minimum cost to get exactly# W Kg with given packets INF = 1000000 # cost[] initial cost array including unavailable packet# W capacity of bagdef MinimumCost(cost, n, W): # val[] and wt[] arrays # val[] array to store cost of 'i' kg packet of orange # wt[] array weight of packet of orange val = list() wt= list() # traverse the original cost[] array and skip # unavailable packets and make val[] and wt[] # array. size variable tells the available number # of distinct weighted packets. size = 0 for i in range(n): if (cost[i] != -1): val.append(cost[i]) wt.append(i+1) size += 1 n = size min_cost = [[0 for i in range(W+1)] for j in range(n+1)] # fill 0th row with infinity for i in range(W+1): min_cost[0][i] = INF # fill 0th column with 0 for i in range(1, n+1): min_cost[i][0] = 0 # now check for each weight one by one and fill the # matrix according to the condition for i in range(1, n+1): for j in range(1, W+1): # wt[i-1]>j means capacity of bag is # less than weight of item if (wt[i-1] > j): min_cost[i][j] = min_cost[i-1][j] # here we check we get minimum cost either # by including it or excluding it else: min_cost[i][j] = min(min_cost[i-1][j], min_cost[i][j-wt[i-1]] + val[i-1]) # exactly weight W can not be made by given weights if(min_cost[n][W] == INF): return -1 else: return min_cost[n][W] # Driver program to run the test casecost = [1, 2, 3, 4, 5]W = 5n = len(cost) print(MinimumCost(cost, n, W)) # This code is contributed by Soumen Ghosh.
// C# Code for Minimum cost to// fill given weight in a bag using System;using System.Collections.Generic; class GFG { // cost[] initial cost array including // unavailable packet W capacity of bag public static int MinimumCost(int []cost, int n, int W) { // val[] and wt[] arrays // val[] array to store cost of 'i' kg // packet of orange wt[] array weight of // packet of orange List<int> val = new List<int>(); List<int> wt = new List<int>(); // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available // number of distinct weighted packets int size = 0; for (int i = 0; i < n; i++) { if (cost[i] != -1) { val.Add(cost[i]); wt.Add(i + 1); size++; } } n = size; int [,]min_cost = new int[n+1,W+1]; // fill 0th row with infinity for (int i = 0; i <= W; i++) min_cost[0,i] = int.MaxValue; // fill 0'th column with 0 for (int i = 1; i <= n; i++) min_cost[i,0] = 0; // now check for each weight one by one and // fill the matrix according to the condition for (int i = 1; i <= n; i++) { for (int j = 1; j <= W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt[i-1] > j) min_cost[i,j] = min_cost[i-1,j]; // here we check we get minimum cost // either by including it or excluding // it else min_cost[i,j] = Math.Min(min_cost[i-1,j], min_cost[i,j-wt[i-1]] + val[i-1]); } } // exactly weight W can not be made by // given weights return (min_cost[n,W] == int.MaxValue )? -1: min_cost[n,W]; } /* Driver program to test above function */ public static void Main() { int []cost = {1, 2, 3, 4, 5}; int W = 5; int n = cost.Length; Console.WriteLine(MinimumCost(cost, n, W)); }}// This code is contributed by Ryuga
<?php// PHP program to find minimum cost to// get exactly W Kg with given packets$INF = 1000000; // cost[] initial cost array including// unavailable packet W capacity of bagfunction MinimumCost(&$cost, $n, $W){ global $INF; // val[] and wt[] arrays // val[] array to store cost of 'i' // kg packet of orange // wt[] array weight of packet of orange $val = array(); $wt = array(); // traverse the original cost[] array // and skip unavailable packets and // make val[] and wt[] array. size // variable tells the available number // of distinct weighted packets $size = 0; for ($i = 0; $i < $n; $i++) { if ($cost[$i] != -1) { array_push($val, $cost[$i]); array_push($wt, $i + 1); $size++; } } $n = $size; $min_cost = array_fill(0, $n + 1, array_fill(0, $W + 1, NULL)); // fill 0th row with infinity for ($i = 0; $i <= $W; $i++) $min_cost[0][$i] = $INF; // fill 0'th column with 0 for ($i = 1; $i <= $n; $i++) $min_cost[$i][0] = 0; // now check for each weight one by // one and fill the matrix according // to the condition for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $W; $j++) { // wt[i-1]>j means capacity of bag // is less than weight of item if ($wt[$i - 1] > $j) $min_cost[$i][$j] = $min_cost[$i - 1][$j]; // here we check we get minimum // cost either by including it // or excluding it else $min_cost[$i][$j] = min($min_cost[$i - 1][$j], $min_cost[$i][$j - $wt[$i - 1]] + $val[$i - 1]); } } // exactly weight W can not be made // by given weights if ($min_cost[$n][$W] == $INF) return -1; else return $min_cost[$n][$W];} // Driver Code$cost = array(1, 2, 3, 4, 5);$W = 5;$n = sizeof($cost);echo MinimumCost($cost, $n, $W); // This code is contributed by ita_c?>
<script> // Javascript program to find minimum cost to get exactly // W Kg with given packets let INF = 1000000; // cost[] initial cost array including unavailable packet // W capacity of bag function MinimumCost(cost, n, W) { // val[] and wt[] arrays // val[] array to store cost of 'i' kg packet of orange // wt[] array weight of packet of orange let val = [], wt = []; // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available number // of distinct weighted packets let size = 0; for (let i=0; i<n; i++) { if (cost[i]!= -1) { val.push(cost[i]); wt.push(i+1); size++; } } n = size; let min_cost = new Array(n+1); for(let i = 0; i < n + 1; i++) { min_cost[i] = new Array(W + 1); } // fill 0th row with infinity for (let i=0; i<=W; i++) min_cost[0][i] = INF; // fill 0'th column with 0 for (let i=1; i<=n; i++) min_cost[i][0] = 0; // now check for each weight one by one and fill the // matrix according to the condition for (let i=1; i<=n; i++) { for (let j=1; j<=W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt[i-1] > j) min_cost[i][j] = min_cost[i-1][j]; // here we check we get minimum cost either // by including it or excluding it else min_cost[i][j] = Math.min(min_cost[i-1][j], min_cost[i][j-wt[i-1]] + val[i-1]); } } // exactly weight W can not be made by given weights return (min_cost[n][W]==INF)? -1: min_cost[n][W]; } // Driver code let cost = [1, 2, 3, 4, 5], W = 5; let n = cost.length; document.write(MinimumCost(cost, n, W)); // This code is contributed by suresh07.</script>
5
Space Optimized Solution If we take a closer look at this problem, we may notice that this is a variation of Rod Cutting Problem. Instead of doing maximization, here we need to do minimization.
C++
Java
Python3
C#
Javascript
// C++ program to find minimum cost to// get exactly W Kg with given packets#include<bits/stdc++.h>using namespace std; /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int minCost(int cost[], int n){ int dp[n+1]; dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (int i = 1; i<=n; i++) { int min_cost = INT_MAX; for (int j = 0; j < i; j++) if(j < n && cost[j]!=-1) min_cost = min(min_cost, cost[j] + dp[i-j-1]); dp[i] = min_cost; } return dp[n];} /* Driver code */int main(){ int cost[] = {20, 10, 4, 50, 100}; int W = sizeof(cost)/sizeof(cost[0]); cout << minCost(cost, W); return 0;}
// Java program to find minimum cost to// get exactly W Kg with given packetsimport java.util.*;class Main{ /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ public static int minCost(int cost[], int n) { int dp[] = new int[n + 1]; dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (int i = 1; i <= n; i++) { int min_cost = Integer.MAX_VALUE; for (int j = 0; j < i; j++) if(j < cost.length && cost[j]!=-1) { min_cost = Math.min(min_cost, cost[j] + dp[i - j - 1]); } dp[i] = min_cost; } return dp[n]; } public static void main(String[] args) { int cost[] = {10,-1,-1,-1,-1}; int W = cost.length; System.out.print(minCost(cost, W)); }} // This code is contributed by divyeshrabadiya07
# Python3 program to find minimum cost to# get exactly W Kg with given packetsimport sys # Returns the best obtainable price for# a rod of length n and price[] as prices# of different piecesdef minCost(cost, n): dp = [0 for i in range(n + 1)] # Build the table val[] in bottom up # manner and return the last entry # from the table for i in range(1, n + 1): min_cost = sys.maxsize for j in range(i): if j<len(cost) and cost[j]!=-1: min_cost = min(min_cost, cost[j] + dp[i - j - 1]) dp[i] = min_cost return dp[n] # Driver codecost = [ 10,-1,-1,-1,-1 ]W = len(cost) print(minCost(cost, W)) # This code is contributed by rag2127
// C# program to find minimum cost to// get exactly W Kg with given packetsusing System;class GFG { /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ static int minCost(int[] cost, int n) { int[] dp = new int[n + 1]; dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (int i = 1; i <= n; i++) { int min_cost = Int32.MaxValue; for (int j = 0; j < i; j++) if(j < n && cost[j]!=-1) min_cost = Math.Min(min_cost, cost[j] + dp[i - j - 1]); dp[i] = min_cost; } return dp[n]; } // Driver code static void Main() { int[] cost = {20, 10, 4, 50, 100}; int W = cost.Length; Console.Write(minCost(cost, W)); }} // This code is contributed by divyesh072019
<script> // Javascript program to find minimum cost to // get exactly W Kg with given packets /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ function minCost(cost, n) { let dp = new Array(n+1); dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (let i = 1; i<=n; i++) { let min_cost = Number.MAX_VALUE; for (let j = 0; j < i; j++) if(j < n) min_cost = Math.min(min_cost, cost[j] + dp[i-j-1]); dp[i] = min_cost; } return dp[n]; } let cost = [20, 10, 4, 50, 100]; let W = cost.length; document.write(minCost(cost, W)); </script>
14
Top Down Approach: We can also solve the problem using memoization.
C++
Java
Python3
C#
Javascript
// C++ program to find minimum cost to// get exactly W Kg with given packets#include <bits/stdc++.h>using namespace std; int helper(vector<int>& cost, vector<int>& weight, int n, int w, vector<vector<int> >& dp){ // base cases if (w == 0) return 0; if (w < 0 or n <= 0) return INT_MAX; if (dp[n][w] != -1) return dp[n][w]; if (cost[n - 1] < 0) return dp[n][w] = min(INT_MAX, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n][w] = min(cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n][w] = helper(cost, weight, n - 1, w, dp);}int minCost(vector<int>& cost, int W){ int N = cost.size(); // Your code goes here vector<int> weight(N); // create the weight array for (int i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array vector<vector<int> > dp(N + 1, vector<int>(W + 1, -1)); int res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == INT_MAX) ? -1 : res;} /* Driver code */int main(){ vector<int> cost = { 20, 10, 4, 50, 100 }; int W = cost.size(); cout << minCost(cost, W); return 0;}
// Java program to find minimum cost to// get exactly W Kg with given packetsimport java.io.*; class GFG { public static int helper(int cost[], int weight[], int n, int w, int dp[][]) { // base cases if (w == 0) return 0; if (w < 0 || n <= 0) return Integer.MAX_VALUE; if (dp[n][w] != -1) return dp[n][w]; if (cost[n - 1] < 0) return dp[n][w] = Math.min( Integer.MAX_VALUE, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n][w] = Math.min( cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n][w] = helper(cost, weight, n - 1, w, dp); } public static int minCost(int cost[], int W) { int N = cost.length; int weight[] = new int[N]; // create the weight array for (int i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array int dp[][] = new int[N + 1][W + 1]; for (int i = 0; i < N + 1; i++) for (int j = 0; j < W + 1; j++) dp[i][j] = -1; int res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == Integer.MAX_VALUE) ? -1 : res; } // Driver Code public static void main(String[] args) { int cost[] = { 20, 10, 4, 50, 100 }; int W = cost.length; System.out.print(minCost(cost, W)); }} // This code is contributed by Rohit Pradhan
# Python3 program to find minimum cost to# get exactly W Kg with given packetsimport sys def helper(cost, weight, n, w, dp): # base cases if (w == 0): return 0 if (w < 0 or n <= 0): return sys.maxsize if (dp[n][w] != -1): return dp[n][w] if (cost[n - 1] < 0): dp[n][w] = min(sys.maxsize, helper(cost, weight, n - 1, w, dp)) return dp[n][w] if (weight[n - 1] <= w): dp[n][w] = min(cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)) return dp[n][w] dp[n][w] = helper(cost, weight, n - 1, w, dp) return dp[n][w] def minCost(cost, W): N = len(cost) weight = [0 for i in range(N)] # create the weight array for i in range(1,N + 1): weight[i - 1] = i # initialize the dp array dp = [[-1 for i in range(W + 1)]for j in range(N + 1)] res = helper(cost, weight, N, W, dp) # return -1 if result is MAX return -1 if(res == sys.maxsize) else res # Driver codecost = [ 20, 10, 4, 50, 100 ]W = len(cost)print(minCost(cost, W)) # This code is contributed by shinjanpatra
// C# program to find minimum cost to// get exactly W Kg with given packetsusing System; class GFG{ static int helper(int[] cost, int[] weight, int n, int w, int[,] dp) { // base cases if (w == 0) return 0; if (w < 0 || n <= 0) return Int32.MaxValue; if (dp[n,w] != -1) return dp[n,w]; if (cost[n - 1] < 0) return dp[n,w] = Math.Min( Int32.MaxValue, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n,w] = Math.Min( cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n,w] = helper(cost, weight, n - 1, w, dp); } static int minCost(int[] cost, int W) { int N = cost.Length; int[] weight = new int[N]; // create the weight array for (int i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array int[,] dp = new int[N + 1, W + 1]; for (int i = 0; i < N + 1; i++) for (int j = 0; j < W + 1; j++) dp[i,j] = -1; int res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == Int32.MaxValue) ? -1 : res; } // Driver Code static public void Main() { int[] cost = { 20, 10, 4, 50, 100 }; int W = cost.Length; Console.Write(minCost(cost, W)); }} // This code is contributed by kothavvsaakash
<script> // JavaScript program to find minimum cost to// get exactly W Kg with given packetsfunction helper(cost, weight, n, w, dp){ // base cases if (w == 0) return 0; if (w < 0 || n <= 0) return Number.MAX_VALUE; if (dp[n][w] != -1) return dp[n][w]; if (cost[n - 1] < 0) return dp[n][w] = Math.min(Number.MAX_VALUE, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n][w] = Math.min(cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n][w] = helper(cost, weight, n - 1, w, dp);}function minCost(cost,W){ let N = cost.length; // Your code goes here let weight = new Array(N); // create the weight array for (let i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array let dp = new Array(N + 1).fill(-1).map(()=>new Array(W + 1).fill(-1)); let res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == Number.MAX_VALUE) ? -1 : res;} /* Driver code */let cost = [ 20, 10, 4, 50, 100 ];let W = cost.length;document.write(minCost(cost, W),"</br>"); // This code is contributed by shinjanpatra </script>
14
This article is contributed by Shashank Mishra ( Gullu ).This article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ankthon
ukasp
md1844
thekillingjoke
divyeshrabadiya07
divyesh072019
rag2127
emplar
mukesh07
suresh07
ggarushibe18
josal
surinderdawra388
shinjanpatra
rohit768
kothavvsaakash
knapsack
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Find if there is a path between two vertices in an undirected graph
Matrix Chain Multiplication | DP-8
Bellman–Ford Algorithm | DP-23
Sieve of Eratosthenes
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Minimum number of jumps to reach end
Tabulation vs Memoization | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 543,
"s": 54,
"text": "You are given a bag of size W kg and you are provided costs of packets different weights of oranges in array cost[] where cost[i] is basically the cost of ‘i’ kg packet of oranges. Where cost[i] = -1 means that ‘i’ kg packet of orange is unavailableFind the minimum total cost to buy exactly W kg oranges and if it is not possible to buy exactly W kg oranges then print -1. It may be assumed that there is an infinite supply of all available packet types.Note: array starts from index 1. "
},
{
"code": null,
"e": 554,
"s": 543,
"text": "Examples: "
},
{
"code": null,
"e": 1330,
"s": 554,
"text": "Input : W = 5, cost[] = {20, 10, 4, 50, 100}\nOutput : 14\nWe can choose two oranges to minimize cost. First \norange of 2Kg and cost 10. Second orange of 3Kg\nand cost 4. \n\nInput : W = 5, cost[] = {1, 10, 4, 50, 100}\nOutput : 5\nWe can choose five oranges of weight 1 kg.\n\nInput : W = 5, cost[] = {1, 2, 3, 4, 5}\nOutput : 5\nCosts of 1, 2, 3, 4 and 5 kg packets are 1, 2, 3, \n4 and 5 Rs respectively. \nWe choose packet of 5kg having cost 5 for minimum\ncost to get 5Kg oranges.\n\nInput : W = 5, cost[] = {-1, -1, 4, 5, -1}\nOutput : -1\nPackets of size 1, 2 and 5 kg are unavailable\nbecause they have cost -1. Cost of 3 kg packet \nis 4 Rs and of 4 kg is 5 Rs. Here we have only \nweights 3 and 4 so by using these two we can \nnot make exactly W kg weight, therefore answer \nis -1."
},
{
"code": null,
"e": 1737,
"s": 1330,
"text": "This problem is can be reduced to Unbounded Knapsack. So in the cost array, we first ignore those packets which are not available i.e; cost is -1 and then traverse the cost array and create two array val[] for storing the cost of ‘i’ kg packet of orange and wt[] for storing weight of the corresponding packet. Suppose cost[i] = 50 so the weight of the packet will be i and the cost will be 50. Algorithm :"
},
{
"code": null,
"e": 1870,
"s": 1737,
"text": "Create matrix min_cost[n+1][W+1], where n is number of distinct weighted packets of orange and W is the maximum capacity of the bag."
},
{
"code": null,
"e": 1936,
"s": 1870,
"text": "Initialize the 0th row with INF (infinity) and 0th Column with 0."
},
{
"code": null,
"e": 2106,
"s": 1936,
"text": "Now fill the matrixif wt[i-1] > j then min_cost[i][j] = min_cost[i-1][j] ;if wt[i-1] <= j then min_cost[i][j] = min(min_cost[i-1][j], val[i-1] + min_cost[i][j-wt[i-1]]);"
},
{
"code": null,
"e": 2162,
"s": 2106,
"text": "if wt[i-1] > j then min_cost[i][j] = min_cost[i-1][j] ;"
},
{
"code": null,
"e": 2258,
"s": 2162,
"text": "if wt[i-1] <= j then min_cost[i][j] = min(min_cost[i-1][j], val[i-1] + min_cost[i][j-wt[i-1]]);"
},
{
"code": null,
"e": 2418,
"s": 2258,
"text": "If min_cost[n][W]==INF then output will be -1 because this means that we cant not make make weight W by using these weights else output will be min_cost[n][W]."
},
{
"code": null,
"e": 2422,
"s": 2418,
"text": "C++"
},
{
"code": null,
"e": 2427,
"s": 2422,
"text": "Java"
},
{
"code": null,
"e": 2435,
"s": 2427,
"text": "Python3"
},
{
"code": null,
"e": 2438,
"s": 2435,
"text": "C#"
},
{
"code": null,
"e": 2442,
"s": 2438,
"text": "PHP"
},
{
"code": null,
"e": 2453,
"s": 2442,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum cost to get exactly// W Kg with given packets#include<bits/stdc++.h>#define INF 1000000using namespace std; // cost[] initial cost array including unavailable packet// W capacity of bagint MinimumCost(int cost[], int n, int W){ // val[] and wt[] arrays // val[] array to store cost of 'i' kg packet of orange // wt[] array weight of packet of orange vector<int> val, wt; // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available number // of distinct weighted packets int size = 0; for (int i=0; i<n; i++) { if (cost[i]!= -1) { val.push_back(cost[i]); wt.push_back(i+1); size++; } } n = size; int min_cost[n+1][W+1]; // fill 0th row with infinity for (int i=0; i<=W; i++) min_cost[0][i] = INF; // fill 0'th column with 0 for (int i=1; i<=n; i++) min_cost[i][0] = 0; // now check for each weight one by one and fill the // matrix according to the condition for (int i=1; i<=n; i++) { for (int j=1; j<=W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt[i-1] > j) min_cost[i][j] = min_cost[i-1][j]; // here we check we get minimum cost either // by including it or excluding it else min_cost[i][j] = min(min_cost[i-1][j], min_cost[i][j-wt[i-1]] + val[i-1]); } } // exactly weight W can not be made by given weights return (min_cost[n][W]==INF)? -1: min_cost[n][W];} // Driver program to run the test caseint main(){ int cost[] = {1, 2, 3, 4, 5}, W = 5; int n = sizeof(cost)/sizeof(cost[0]); cout << MinimumCost(cost, n, W); return 0;}",
"e": 4328,
"s": 2453,
"text": null
},
{
"code": "// Java Code for Minimum cost to// fill given weight in a bagimport java.util.*; class GFG { // cost[] initial cost array including // unavailable packet W capacity of bag public static int MinimumCost(int cost[], int n, int W) { // val[] and wt[] arrays // val[] array to store cost of 'i' kg // packet of orange wt[] array weight of // packet of orange Vector<Integer> val = new Vector<Integer>(); Vector<Integer> wt = new Vector<Integer>(); // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available // number of distinct weighted packets int size = 0; for (int i = 0; i < n; i++) { if (cost[i] != -1) { val.add(cost[i]); wt.add(i + 1); size++; } } n = size; int min_cost[][] = new int[n+1][W+1]; // fill 0th row with infinity for (int i = 0; i <= W; i++) min_cost[0][i] = Integer.MAX_VALUE; // fill 0'th column with 0 for (int i = 1; i <= n; i++) min_cost[i][0] = 0; // now check for each weight one by one and // fill the matrix according to the condition for (int i = 1; i <= n; i++) { for (int j = 1; j <= W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt.get(i-1) > j) min_cost[i][j] = min_cost[i-1][j]; // here we check we get minimum cost // either by including it or excluding // it else min_cost[i][j] = Math.min(min_cost[i-1][j], min_cost[i][j-wt.get(i-1)] + val.get(i-1)); } } // exactly weight W can not be made by // given weights return (min_cost[n][W] == Integer.MAX_VALUE)? -1: min_cost[n][W]; } /* Driver program to test above function */ public static void main(String[] args) { int cost[] = {1, 2, 3, 4, 5}, W = 5; int n = cost.length; System.out.println(MinimumCost(cost, n, W)); }}// This code is contributed by Arnav Kr. Mandal.",
"e": 6842,
"s": 4328,
"text": null
},
{
"code": "# Python program to find minimum cost to get exactly# W Kg with given packets INF = 1000000 # cost[] initial cost array including unavailable packet# W capacity of bagdef MinimumCost(cost, n, W): # val[] and wt[] arrays # val[] array to store cost of 'i' kg packet of orange # wt[] array weight of packet of orange val = list() wt= list() # traverse the original cost[] array and skip # unavailable packets and make val[] and wt[] # array. size variable tells the available number # of distinct weighted packets. size = 0 for i in range(n): if (cost[i] != -1): val.append(cost[i]) wt.append(i+1) size += 1 n = size min_cost = [[0 for i in range(W+1)] for j in range(n+1)] # fill 0th row with infinity for i in range(W+1): min_cost[0][i] = INF # fill 0th column with 0 for i in range(1, n+1): min_cost[i][0] = 0 # now check for each weight one by one and fill the # matrix according to the condition for i in range(1, n+1): for j in range(1, W+1): # wt[i-1]>j means capacity of bag is # less than weight of item if (wt[i-1] > j): min_cost[i][j] = min_cost[i-1][j] # here we check we get minimum cost either # by including it or excluding it else: min_cost[i][j] = min(min_cost[i-1][j], min_cost[i][j-wt[i-1]] + val[i-1]) # exactly weight W can not be made by given weights if(min_cost[n][W] == INF): return -1 else: return min_cost[n][W] # Driver program to run the test casecost = [1, 2, 3, 4, 5]W = 5n = len(cost) print(MinimumCost(cost, n, W)) # This code is contributed by Soumen Ghosh.",
"e": 8599,
"s": 6842,
"text": null
},
{
"code": "// C# Code for Minimum cost to// fill given weight in a bag using System;using System.Collections.Generic; class GFG { // cost[] initial cost array including // unavailable packet W capacity of bag public static int MinimumCost(int []cost, int n, int W) { // val[] and wt[] arrays // val[] array to store cost of 'i' kg // packet of orange wt[] array weight of // packet of orange List<int> val = new List<int>(); List<int> wt = new List<int>(); // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available // number of distinct weighted packets int size = 0; for (int i = 0; i < n; i++) { if (cost[i] != -1) { val.Add(cost[i]); wt.Add(i + 1); size++; } } n = size; int [,]min_cost = new int[n+1,W+1]; // fill 0th row with infinity for (int i = 0; i <= W; i++) min_cost[0,i] = int.MaxValue; // fill 0'th column with 0 for (int i = 1; i <= n; i++) min_cost[i,0] = 0; // now check for each weight one by one and // fill the matrix according to the condition for (int i = 1; i <= n; i++) { for (int j = 1; j <= W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt[i-1] > j) min_cost[i,j] = min_cost[i-1,j]; // here we check we get minimum cost // either by including it or excluding // it else min_cost[i,j] = Math.Min(min_cost[i-1,j], min_cost[i,j-wt[i-1]] + val[i-1]); } } // exactly weight W can not be made by // given weights return (min_cost[n,W] == int.MaxValue )? -1: min_cost[n,W]; } /* Driver program to test above function */ public static void Main() { int []cost = {1, 2, 3, 4, 5}; int W = 5; int n = cost.Length; Console.WriteLine(MinimumCost(cost, n, W)); }}// This code is contributed by Ryuga",
"e": 10984,
"s": 8599,
"text": null
},
{
"code": "<?php// PHP program to find minimum cost to// get exactly W Kg with given packets$INF = 1000000; // cost[] initial cost array including// unavailable packet W capacity of bagfunction MinimumCost(&$cost, $n, $W){ global $INF; // val[] and wt[] arrays // val[] array to store cost of 'i' // kg packet of orange // wt[] array weight of packet of orange $val = array(); $wt = array(); // traverse the original cost[] array // and skip unavailable packets and // make val[] and wt[] array. size // variable tells the available number // of distinct weighted packets $size = 0; for ($i = 0; $i < $n; $i++) { if ($cost[$i] != -1) { array_push($val, $cost[$i]); array_push($wt, $i + 1); $size++; } } $n = $size; $min_cost = array_fill(0, $n + 1, array_fill(0, $W + 1, NULL)); // fill 0th row with infinity for ($i = 0; $i <= $W; $i++) $min_cost[0][$i] = $INF; // fill 0'th column with 0 for ($i = 1; $i <= $n; $i++) $min_cost[$i][0] = 0; // now check for each weight one by // one and fill the matrix according // to the condition for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $W; $j++) { // wt[i-1]>j means capacity of bag // is less than weight of item if ($wt[$i - 1] > $j) $min_cost[$i][$j] = $min_cost[$i - 1][$j]; // here we check we get minimum // cost either by including it // or excluding it else $min_cost[$i][$j] = min($min_cost[$i - 1][$j], $min_cost[$i][$j - $wt[$i - 1]] + $val[$i - 1]); } } // exactly weight W can not be made // by given weights if ($min_cost[$n][$W] == $INF) return -1; else return $min_cost[$n][$W];} // Driver Code$cost = array(1, 2, 3, 4, 5);$W = 5;$n = sizeof($cost);echo MinimumCost($cost, $n, $W); // This code is contributed by ita_c?>",
"e": 13092,
"s": 10984,
"text": null
},
{
"code": "<script> // Javascript program to find minimum cost to get exactly // W Kg with given packets let INF = 1000000; // cost[] initial cost array including unavailable packet // W capacity of bag function MinimumCost(cost, n, W) { // val[] and wt[] arrays // val[] array to store cost of 'i' kg packet of orange // wt[] array weight of packet of orange let val = [], wt = []; // traverse the original cost[] array and skip // unavailable packets and make val[] and wt[] // array. size variable tells the available number // of distinct weighted packets let size = 0; for (let i=0; i<n; i++) { if (cost[i]!= -1) { val.push(cost[i]); wt.push(i+1); size++; } } n = size; let min_cost = new Array(n+1); for(let i = 0; i < n + 1; i++) { min_cost[i] = new Array(W + 1); } // fill 0th row with infinity for (let i=0; i<=W; i++) min_cost[0][i] = INF; // fill 0'th column with 0 for (let i=1; i<=n; i++) min_cost[i][0] = 0; // now check for each weight one by one and fill the // matrix according to the condition for (let i=1; i<=n; i++) { for (let j=1; j<=W; j++) { // wt[i-1]>j means capacity of bag is // less than weight of item if (wt[i-1] > j) min_cost[i][j] = min_cost[i-1][j]; // here we check we get minimum cost either // by including it or excluding it else min_cost[i][j] = Math.min(min_cost[i-1][j], min_cost[i][j-wt[i-1]] + val[i-1]); } } // exactly weight W can not be made by given weights return (min_cost[n][W]==INF)? -1: min_cost[n][W]; } // Driver code let cost = [1, 2, 3, 4, 5], W = 5; let n = cost.length; document.write(MinimumCost(cost, n, W)); // This code is contributed by suresh07.</script>",
"e": 15260,
"s": 13092,
"text": null
},
{
"code": null,
"e": 15262,
"s": 15260,
"text": "5"
},
{
"code": null,
"e": 15456,
"s": 15262,
"text": "Space Optimized Solution If we take a closer look at this problem, we may notice that this is a variation of Rod Cutting Problem. Instead of doing maximization, here we need to do minimization."
},
{
"code": null,
"e": 15460,
"s": 15456,
"text": "C++"
},
{
"code": null,
"e": 15465,
"s": 15460,
"text": "Java"
},
{
"code": null,
"e": 15473,
"s": 15465,
"text": "Python3"
},
{
"code": null,
"e": 15476,
"s": 15473,
"text": "C#"
},
{
"code": null,
"e": 15487,
"s": 15476,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum cost to// get exactly W Kg with given packets#include<bits/stdc++.h>using namespace std; /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int minCost(int cost[], int n){ int dp[n+1]; dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (int i = 1; i<=n; i++) { int min_cost = INT_MAX; for (int j = 0; j < i; j++) if(j < n && cost[j]!=-1) min_cost = min(min_cost, cost[j] + dp[i-j-1]); dp[i] = min_cost; } return dp[n];} /* Driver code */int main(){ int cost[] = {20, 10, 4, 50, 100}; int W = sizeof(cost)/sizeof(cost[0]); cout << minCost(cost, W); return 0;}",
"e": 16259,
"s": 15487,
"text": null
},
{
"code": "// Java program to find minimum cost to// get exactly W Kg with given packetsimport java.util.*;class Main{ /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ public static int minCost(int cost[], int n) { int dp[] = new int[n + 1]; dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (int i = 1; i <= n; i++) { int min_cost = Integer.MAX_VALUE; for (int j = 0; j < i; j++) if(j < cost.length && cost[j]!=-1) { min_cost = Math.min(min_cost, cost[j] + dp[i - j - 1]); } dp[i] = min_cost; } return dp[n]; } public static void main(String[] args) { int cost[] = {10,-1,-1,-1,-1}; int W = cost.length; System.out.print(minCost(cost, W)); }} // This code is contributed by divyeshrabadiya07",
"e": 17241,
"s": 16259,
"text": null
},
{
"code": "# Python3 program to find minimum cost to# get exactly W Kg with given packetsimport sys # Returns the best obtainable price for# a rod of length n and price[] as prices# of different piecesdef minCost(cost, n): dp = [0 for i in range(n + 1)] # Build the table val[] in bottom up # manner and return the last entry # from the table for i in range(1, n + 1): min_cost = sys.maxsize for j in range(i): if j<len(cost) and cost[j]!=-1: min_cost = min(min_cost, cost[j] + dp[i - j - 1]) dp[i] = min_cost return dp[n] # Driver codecost = [ 10,-1,-1,-1,-1 ]W = len(cost) print(minCost(cost, W)) # This code is contributed by rag2127",
"e": 17993,
"s": 17241,
"text": null
},
{
"code": "// C# program to find minimum cost to// get exactly W Kg with given packetsusing System;class GFG { /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ static int minCost(int[] cost, int n) { int[] dp = new int[n + 1]; dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (int i = 1; i <= n; i++) { int min_cost = Int32.MaxValue; for (int j = 0; j < i; j++) if(j < n && cost[j]!=-1) min_cost = Math.Min(min_cost, cost[j] + dp[i - j - 1]); dp[i] = min_cost; } return dp[n]; } // Driver code static void Main() { int[] cost = {20, 10, 4, 50, 100}; int W = cost.Length; Console.Write(minCost(cost, W)); }} // This code is contributed by divyesh072019",
"e": 18948,
"s": 17993,
"text": null
},
{
"code": "<script> // Javascript program to find minimum cost to // get exactly W Kg with given packets /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ function minCost(cost, n) { let dp = new Array(n+1); dp[0] = 0; // Build the table val[] in bottom up // manner and return the last entry // from the table for (let i = 1; i<=n; i++) { let min_cost = Number.MAX_VALUE; for (let j = 0; j < i; j++) if(j < n) min_cost = Math.min(min_cost, cost[j] + dp[i-j-1]); dp[i] = min_cost; } return dp[n]; } let cost = [20, 10, 4, 50, 100]; let W = cost.length; document.write(minCost(cost, W)); </script>",
"e": 19748,
"s": 18948,
"text": null
},
{
"code": null,
"e": 19751,
"s": 19748,
"text": "14"
},
{
"code": null,
"e": 19819,
"s": 19751,
"text": "Top Down Approach: We can also solve the problem using memoization."
},
{
"code": null,
"e": 19823,
"s": 19819,
"text": "C++"
},
{
"code": null,
"e": 19828,
"s": 19823,
"text": "Java"
},
{
"code": null,
"e": 19836,
"s": 19828,
"text": "Python3"
},
{
"code": null,
"e": 19839,
"s": 19836,
"text": "C#"
},
{
"code": null,
"e": 19850,
"s": 19839,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum cost to// get exactly W Kg with given packets#include <bits/stdc++.h>using namespace std; int helper(vector<int>& cost, vector<int>& weight, int n, int w, vector<vector<int> >& dp){ // base cases if (w == 0) return 0; if (w < 0 or n <= 0) return INT_MAX; if (dp[n][w] != -1) return dp[n][w]; if (cost[n - 1] < 0) return dp[n][w] = min(INT_MAX, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n][w] = min(cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n][w] = helper(cost, weight, n - 1, w, dp);}int minCost(vector<int>& cost, int W){ int N = cost.size(); // Your code goes here vector<int> weight(N); // create the weight array for (int i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array vector<vector<int> > dp(N + 1, vector<int>(W + 1, -1)); int res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == INT_MAX) ? -1 : res;} /* Driver code */int main(){ vector<int> cost = { 20, 10, 4, 50, 100 }; int W = cost.size(); cout << minCost(cost, W); return 0;}",
"e": 21225,
"s": 19850,
"text": null
},
{
"code": "// Java program to find minimum cost to// get exactly W Kg with given packetsimport java.io.*; class GFG { public static int helper(int cost[], int weight[], int n, int w, int dp[][]) { // base cases if (w == 0) return 0; if (w < 0 || n <= 0) return Integer.MAX_VALUE; if (dp[n][w] != -1) return dp[n][w]; if (cost[n - 1] < 0) return dp[n][w] = Math.min( Integer.MAX_VALUE, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n][w] = Math.min( cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n][w] = helper(cost, weight, n - 1, w, dp); } public static int minCost(int cost[], int W) { int N = cost.length; int weight[] = new int[N]; // create the weight array for (int i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array int dp[][] = new int[N + 1][W + 1]; for (int i = 0; i < N + 1; i++) for (int j = 0; j < W + 1; j++) dp[i][j] = -1; int res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == Integer.MAX_VALUE) ? -1 : res; } // Driver Code public static void main(String[] args) { int cost[] = { 20, 10, 4, 50, 100 }; int W = cost.length; System.out.print(minCost(cost, W)); }} // This code is contributed by Rohit Pradhan",
"e": 22954,
"s": 21225,
"text": null
},
{
"code": "# Python3 program to find minimum cost to# get exactly W Kg with given packetsimport sys def helper(cost, weight, n, w, dp): # base cases if (w == 0): return 0 if (w < 0 or n <= 0): return sys.maxsize if (dp[n][w] != -1): return dp[n][w] if (cost[n - 1] < 0): dp[n][w] = min(sys.maxsize, helper(cost, weight, n - 1, w, dp)) return dp[n][w] if (weight[n - 1] <= w): dp[n][w] = min(cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)) return dp[n][w] dp[n][w] = helper(cost, weight, n - 1, w, dp) return dp[n][w] def minCost(cost, W): N = len(cost) weight = [0 for i in range(N)] # create the weight array for i in range(1,N + 1): weight[i - 1] = i # initialize the dp array dp = [[-1 for i in range(W + 1)]for j in range(N + 1)] res = helper(cost, weight, N, W, dp) # return -1 if result is MAX return -1 if(res == sys.maxsize) else res # Driver codecost = [ 20, 10, 4, 50, 100 ]W = len(cost)print(minCost(cost, W)) # This code is contributed by shinjanpatra",
"e": 24084,
"s": 22954,
"text": null
},
{
"code": "// C# program to find minimum cost to// get exactly W Kg with given packetsusing System; class GFG{ static int helper(int[] cost, int[] weight, int n, int w, int[,] dp) { // base cases if (w == 0) return 0; if (w < 0 || n <= 0) return Int32.MaxValue; if (dp[n,w] != -1) return dp[n,w]; if (cost[n - 1] < 0) return dp[n,w] = Math.Min( Int32.MaxValue, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n,w] = Math.Min( cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n,w] = helper(cost, weight, n - 1, w, dp); } static int minCost(int[] cost, int W) { int N = cost.Length; int[] weight = new int[N]; // create the weight array for (int i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array int[,] dp = new int[N + 1, W + 1]; for (int i = 0; i < N + 1; i++) for (int j = 0; j < W + 1; j++) dp[i,j] = -1; int res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == Int32.MaxValue) ? -1 : res; } // Driver Code static public void Main() { int[] cost = { 20, 10, 4, 50, 100 }; int W = cost.Length; Console.Write(minCost(cost, W)); }} // This code is contributed by kothavvsaakash",
"e": 25491,
"s": 24084,
"text": null
},
{
"code": "<script> // JavaScript program to find minimum cost to// get exactly W Kg with given packetsfunction helper(cost, weight, n, w, dp){ // base cases if (w == 0) return 0; if (w < 0 || n <= 0) return Number.MAX_VALUE; if (dp[n][w] != -1) return dp[n][w]; if (cost[n - 1] < 0) return dp[n][w] = Math.min(Number.MAX_VALUE, helper(cost, weight, n - 1, w, dp)); if (weight[n - 1] <= w) { return dp[n][w] = Math.min(cost[n - 1] + helper(cost, weight, n, w - weight[n - 1], dp), helper(cost, weight, n - 1, w, dp)); } return dp[n][w] = helper(cost, weight, n - 1, w, dp);}function minCost(cost,W){ let N = cost.length; // Your code goes here let weight = new Array(N); // create the weight array for (let i = 1; i <= N; i++) { weight[i - 1] = i; } // initialize the dp array let dp = new Array(N + 1).fill(-1).map(()=>new Array(W + 1).fill(-1)); let res = helper(cost, weight, N, W, dp); // return -1 if result is MAX return (res == Number.MAX_VALUE) ? -1 : res;} /* Driver code */let cost = [ 20, 10, 4, 50, 100 ];let W = cost.length;document.write(minCost(cost, W),\"</br>\"); // This code is contributed by shinjanpatra </script>",
"e": 26844,
"s": 25491,
"text": null
},
{
"code": null,
"e": 26847,
"s": 26844,
"text": "14"
},
{
"code": null,
"e": 27078,
"s": 26847,
"text": "This article is contributed by Shashank Mishra ( Gullu ).This article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 27086,
"s": 27078,
"text": "ankthon"
},
{
"code": null,
"e": 27092,
"s": 27086,
"text": "ukasp"
},
{
"code": null,
"e": 27099,
"s": 27092,
"text": "md1844"
},
{
"code": null,
"e": 27114,
"s": 27099,
"text": "thekillingjoke"
},
{
"code": null,
"e": 27132,
"s": 27114,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 27146,
"s": 27132,
"text": "divyesh072019"
},
{
"code": null,
"e": 27154,
"s": 27146,
"text": "rag2127"
},
{
"code": null,
"e": 27161,
"s": 27154,
"text": "emplar"
},
{
"code": null,
"e": 27170,
"s": 27161,
"text": "mukesh07"
},
{
"code": null,
"e": 27179,
"s": 27170,
"text": "suresh07"
},
{
"code": null,
"e": 27192,
"s": 27179,
"text": "ggarushibe18"
},
{
"code": null,
"e": 27198,
"s": 27192,
"text": "josal"
},
{
"code": null,
"e": 27215,
"s": 27198,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27228,
"s": 27215,
"text": "shinjanpatra"
},
{
"code": null,
"e": 27237,
"s": 27228,
"text": "rohit768"
},
{
"code": null,
"e": 27252,
"s": 27237,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 27261,
"s": 27252,
"text": "knapsack"
},
{
"code": null,
"e": 27281,
"s": 27261,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 27301,
"s": 27281,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 27399,
"s": 27301,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27426,
"s": 27399,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 27464,
"s": 27426,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 27497,
"s": 27464,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 27565,
"s": 27497,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 27600,
"s": 27565,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 27631,
"s": 27600,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 27653,
"s": 27631,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 27721,
"s": 27653,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 27758,
"s": 27721,
"text": "Minimum number of jumps to reach end"
}
] |
Function Annotations in Python - GeeksforGeeks | 10 May, 2019
Basic Terminology
PEP: PEP stands for Python Enhancement Proposal. It is a design document that describes new features for Python or its processes or environment. It also provides information to the python community.PEP is a primary mechanism for proposing major new features, for example – Python Web Server Gateway Interface, collecting the inputs of the community on the issues and documenting design decisions that have been implemented in Python.
Function Annotations – PEP 3107 : PEP-3107 introduced the concept and syntax for adding arbitrary metadata annotations to Python. It was introduced in Python3 which was previously done using external libraries in python 2.x
What are Function annotations?
Function annotations are arbitrary python expressions that are associated with various part of functions. These expressions are evaluated at compile time and have no life in python’s runtime environment. Python does not attach any meaning to these annotations. They take life when interpreted by third party libraries, for example, mypy.
Purpose of function annotations:The benefits from function annotations can only be reaped via third party libraries. The type of benefits depends upon the type of the library, for example
Python supports dynamic typing and hence no module is provided for type checking. Annotations like[def foo(a:”int”, b:”float”=5.0) -> ”int”](syntax described in detail in the next section) can be used to collect information about the type of the parameters and the return type of the function to keep track of the type change occurring in the function. ‘mypy’ is one such library.String based annotations can be used by the libraries to provide better help messages at compile time regarding the functionalities of various methods, classes and modules.
Python supports dynamic typing and hence no module is provided for type checking. Annotations like[def foo(a:”int”, b:”float”=5.0) -> ”int”](syntax described in detail in the next section) can be used to collect information about the type of the parameters and the return type of the function to keep track of the type change occurring in the function. ‘mypy’ is one such library.
[def foo(a:”int”, b:”float”=5.0) -> ”int”]
(syntax described in detail in the next section) can be used to collect information about the type of the parameters and the return type of the function to keep track of the type change occurring in the function. ‘mypy’ is one such library.
String based annotations can be used by the libraries to provide better help messages at compile time regarding the functionalities of various methods, classes and modules.
Syntax of function annotations
They are like the optional parameters that follow the parameter name.
Note: The word ‘expression’ mentioned below can be the type of the parameters that should be passed or comment or any arbitrary string that can be made use by external libraries in a meaningful way.Annotations for simple parameters : The argument name is followed by ‘:’ which is then followed by the expression. Annotation syntax is shown below.def foobar(a: expression, b: expression = 5):
Annotations for excess parameters : Excess parameters for e.g. *args and **kwargs, allow arbitrary number of arguments to be passed in a function call. Annotation syntax of such parameters is shown below.def foobar(*args: expression, *kwargs: expression):
Annotations for nested parameters : Nested parameters are useful feature of python 2x where a tuple is passed in a function call and automatic unpacking takes place. This feature is removed in python 3x and manual unpacking should be done. Annotation is done after the variable and not after the tuple as shown below.def foobar((a: expression, b: expression), (c: expression, d: expression)):
Annotations for return type : Annotating return type is slightly different from annotating function arguments. The ‘->’ is followed by expression which is further followed by ‘:’. Annotation syntax of return type is shown below.def foobar(a: expression)->expression:
Annotations for simple parameters : The argument name is followed by ‘:’ which is then followed by the expression. Annotation syntax is shown below.def foobar(a: expression, b: expression = 5):
def foobar(a: expression, b: expression = 5):
Annotations for excess parameters : Excess parameters for e.g. *args and **kwargs, allow arbitrary number of arguments to be passed in a function call. Annotation syntax of such parameters is shown below.def foobar(*args: expression, *kwargs: expression):
def foobar(*args: expression, *kwargs: expression):
Annotations for nested parameters : Nested parameters are useful feature of python 2x where a tuple is passed in a function call and automatic unpacking takes place. This feature is removed in python 3x and manual unpacking should be done. Annotation is done after the variable and not after the tuple as shown below.def foobar((a: expression, b: expression), (c: expression, d: expression)):
def foobar((a: expression, b: expression), (c: expression, d: expression)):
Annotations for return type : Annotating return type is slightly different from annotating function arguments. The ‘->’ is followed by expression which is further followed by ‘:’. Annotation syntax of return type is shown below.def foobar(a: expression)->expression:
def foobar(a: expression)->expression:
Grammar
decorator : ‘@’ name_ [‘(’ [arglist] ‘)’] NEWLINE
decorators : decorator+
funcdef : [decorators] ‘def’ NAME parameters [‘->’] ‘:’ suite
parameters : ‘(’ [typedarglist] ‘)’
typedarglist : (( tfpdef [‘=’ test] ‘, ’)* (‘*’ [tname]
(‘, ’ tname [‘=’ test])* [‘, ’ ‘ **’ tname] | ‘**’ tname)
| tfpdef [‘=’ test (‘, ’ tfpdef [‘=’ test])* [‘, ’]])
tname : NAME [‘:’ test]
tfpdef : tname | ‘(’ tfplist ‘)’
tfplist : tfpdef (‘, ’ tfpdef)* [‘, ’]
Visualizing Grammar : The parse tree is formed from the above grammar to give better visualization of the syntax of the python’s function and function annotations.
Sample Code
The code below will clear the fact that the function annotations are not evaluated at run time. The code prints fibonacci series upto the ‘n’ positions.
# Python program to print Fibonacci seriesdef fib(n:'int', output:'list'=[])-> 'list': if n == 0: return output else: if len(output)< 2: output.append(1) fib(n-1, output) else: last = output[-1] second_last = output[-2] output.append(last + second_last) fib(n-1, output) return outputprint(fib(5))
Output: [1, 1, 2, 3, 5]
Note: Function annotations are only supported in python 3x.
Accessing Function Annotations
1. Using ‘__annotations__’ : The function annotations in the above code can be accessed by a special attribute ‘__annotations__’. It outputs the dictionary having a special key ‘return’ and other keys having name of the annotated arguments. The following code will print the annotations.
# Python program to illustrate Function Annotationsdef fib(n:'int', output:'list'=[])-> 'list': if n == 0: return output else: if len(output)< 2: output.append(1) fib(n-1, output) else: last = output[-1] second_last = output[-2] output.append(last + second_last) fib(n-1, output) return outputprint(fib.__annotations__)
Output: {'return': 'list', 'n': 'int', 'output': 'list'}
2. Using standard module ‘pydoc’ : The ‘pydoc’ is a standard python module that returns the documentation inside a python module(if any). It has a special ‘help()’ method that provides an interactive shell to get help on any keyword, method, class or module. ‘help()’ can be used to access the function annotations. The image below shows the function annotations in the above Fibonacci series code. The module name is ‘fib.py’.
3. Using standard module ‘inspect’: The ‘inspect’ module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. We can use ‘getfullargspec’ method of the module to get complete information about the function which will contain the annotations.
# Python program to illustrate Function Annotationsimport inspectdef fib(n:'int', output:'list'=[])-> 'list': if n == 0: return output else: if len(output)< 2: output.append(1) fib(n-1, output) else: last = output[-1] second_last = output[-2] output.append(last + second_last) fib(n-1, output) return outputprint(inspect.getfullargspec(fib))
Output: FullArgSpec(args=['n', 'output'], varargs=None,
varkw=None, defaults=([], ), kwonlyargs=[],
kwonlydefaults=None, annotations=
{'output': 'list', 'return': 'list', 'n': 'int'})
Application of Function Annotations
Use of ‘mypy’ : ‘mypy’ is an external library that provides static type checking with the help of function annotations.Download mypy for python 2xpip install mypypython 3xpip install git+git://github.com/JukkaL/mypy.gitExample 1:# String slicing function that returns a string from start index to end index.def slice(string:str, start: int, end: int) -> str: return string[start:end] slice([1, 2, 3, 4, 5], 2, 4)Save the above code as example.py and run the following command after installation of mypy. Make sure you are in the directory where you have saved the file.mypy example.pyYou will get the following result.
pip install mypy
python 3x
pip install git+git://github.com/JukkaL/mypy.git
Example 1:
# String slicing function that returns a string from start index to end index.def slice(string:str, start: int, end: int) -> str: return string[start:end] slice([1, 2, 3, 4, 5], 2, 4)
Save the above code as example.py and run the following command after installation of mypy. Make sure you are in the directory where you have saved the file.
mypy example.py
You will get the following result.
Things are little different when the decorators are involved.Example 2(part a): Type checking of the parameters of the wrapped up function ‘gift_func’ and ‘wrapped’def wrapping_paper(func): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))At first, it may seem that passing string as an argument will return an error as the required datatype is an ‘int’ as annotated in ‘gift_func’ and ‘wrapped’. mypy does not establish typechecking in the wrapped up function parameters however typechecking of the decorator and the return type of the wrapped up functions can be checked. Therefore the following result can be expected from the above code.
def wrapping_paper(func): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))
At first, it may seem that passing string as an argument will return an error as the required datatype is an ‘int’ as annotated in ‘gift_func’ and ‘wrapped’. mypy does not establish typechecking in the wrapped up function parameters however typechecking of the decorator and the return type of the wrapped up functions can be checked. Therefore the following result can be expected from the above code.
Example 2(part b): Typechecking of the parameters of the decorator ‘wrapping_paper’.def wrapping_paper(func:str): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))You will now get the following result.
def wrapping_paper(func:str): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))
You will now get the following result.
Example 2(part c): Typechecking of the return type of ‘gift_func’ and ‘wrapped’# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func): def wrapped(gift) -> int: return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname) -> int: return giftname print(gift_func('gtx 5000'))You will get the following result.
# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func): def wrapped(gift) -> int: return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname) -> int: return giftname print(gift_func('gtx 5000'))
You will get the following result.
Example 2(part d) Typechecking of the return type of the wrapper function ‘wrapping_paper’# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func) -> int: def wrapped(gift): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname): return giftname print(gift_func('gtx 5000'))You will get the following result
# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func) -> int: def wrapped(gift): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname): return giftname print(gift_func('gtx 5000'))
You will get the following result
This article is contributed by Anmol Chachra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shubham_singh
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1 | [
{
"code": null,
"e": 24097,
"s": 24069,
"text": "\n10 May, 2019"
},
{
"code": null,
"e": 24115,
"s": 24097,
"text": "Basic Terminology"
},
{
"code": null,
"e": 24549,
"s": 24115,
"text": "PEP: PEP stands for Python Enhancement Proposal. It is a design document that describes new features for Python or its processes or environment. It also provides information to the python community.PEP is a primary mechanism for proposing major new features, for example – Python Web Server Gateway Interface, collecting the inputs of the community on the issues and documenting design decisions that have been implemented in Python."
},
{
"code": null,
"e": 24773,
"s": 24549,
"text": "Function Annotations – PEP 3107 : PEP-3107 introduced the concept and syntax for adding arbitrary metadata annotations to Python. It was introduced in Python3 which was previously done using external libraries in python 2.x"
},
{
"code": null,
"e": 24804,
"s": 24773,
"text": "What are Function annotations?"
},
{
"code": null,
"e": 25142,
"s": 24804,
"text": "Function annotations are arbitrary python expressions that are associated with various part of functions. These expressions are evaluated at compile time and have no life in python’s runtime environment. Python does not attach any meaning to these annotations. They take life when interpreted by third party libraries, for example, mypy."
},
{
"code": null,
"e": 25330,
"s": 25142,
"text": "Purpose of function annotations:The benefits from function annotations can only be reaped via third party libraries. The type of benefits depends upon the type of the library, for example"
},
{
"code": null,
"e": 25884,
"s": 25330,
"text": "Python supports dynamic typing and hence no module is provided for type checking. Annotations like[def foo(a:”int”, b:”float”=5.0) -> ”int”](syntax described in detail in the next section) can be used to collect information about the type of the parameters and the return type of the function to keep track of the type change occurring in the function. ‘mypy’ is one such library.String based annotations can be used by the libraries to provide better help messages at compile time regarding the functionalities of various methods, classes and modules."
},
{
"code": null,
"e": 26266,
"s": 25884,
"text": "Python supports dynamic typing and hence no module is provided for type checking. Annotations like[def foo(a:”int”, b:”float”=5.0) -> ”int”](syntax described in detail in the next section) can be used to collect information about the type of the parameters and the return type of the function to keep track of the type change occurring in the function. ‘mypy’ is one such library."
},
{
"code": null,
"e": 26310,
"s": 26266,
"text": "[def foo(a:”int”, b:”float”=5.0) -> ”int”]"
},
{
"code": null,
"e": 26551,
"s": 26310,
"text": "(syntax described in detail in the next section) can be used to collect information about the type of the parameters and the return type of the function to keep track of the type change occurring in the function. ‘mypy’ is one such library."
},
{
"code": null,
"e": 26724,
"s": 26551,
"text": "String based annotations can be used by the libraries to provide better help messages at compile time regarding the functionalities of various methods, classes and modules."
},
{
"code": null,
"e": 26755,
"s": 26724,
"text": "Syntax of function annotations"
},
{
"code": null,
"e": 26825,
"s": 26755,
"text": "They are like the optional parameters that follow the parameter name."
},
{
"code": null,
"e": 28133,
"s": 26825,
"text": "Note: The word ‘expression’ mentioned below can be the type of the parameters that should be passed or comment or any arbitrary string that can be made use by external libraries in a meaningful way.Annotations for simple parameters : The argument name is followed by ‘:’ which is then followed by the expression. Annotation syntax is shown below.def foobar(a: expression, b: expression = 5):\nAnnotations for excess parameters : Excess parameters for e.g. *args and **kwargs, allow arbitrary number of arguments to be passed in a function call. Annotation syntax of such parameters is shown below.def foobar(*args: expression, *kwargs: expression):\nAnnotations for nested parameters : Nested parameters are useful feature of python 2x where a tuple is passed in a function call and automatic unpacking takes place. This feature is removed in python 3x and manual unpacking should be done. Annotation is done after the variable and not after the tuple as shown below.def foobar((a: expression, b: expression), (c: expression, d: expression)):\nAnnotations for return type : Annotating return type is slightly different from annotating function arguments. The ‘->’ is followed by expression which is further followed by ‘:’. Annotation syntax of return type is shown below.def foobar(a: expression)->expression:"
},
{
"code": null,
"e": 28328,
"s": 28133,
"text": "Annotations for simple parameters : The argument name is followed by ‘:’ which is then followed by the expression. Annotation syntax is shown below.def foobar(a: expression, b: expression = 5):\n"
},
{
"code": null,
"e": 28375,
"s": 28328,
"text": "def foobar(a: expression, b: expression = 5):\n"
},
{
"code": null,
"e": 28632,
"s": 28375,
"text": "Annotations for excess parameters : Excess parameters for e.g. *args and **kwargs, allow arbitrary number of arguments to be passed in a function call. Annotation syntax of such parameters is shown below.def foobar(*args: expression, *kwargs: expression):\n"
},
{
"code": null,
"e": 28685,
"s": 28632,
"text": "def foobar(*args: expression, *kwargs: expression):\n"
},
{
"code": null,
"e": 29079,
"s": 28685,
"text": "Annotations for nested parameters : Nested parameters are useful feature of python 2x where a tuple is passed in a function call and automatic unpacking takes place. This feature is removed in python 3x and manual unpacking should be done. Annotation is done after the variable and not after the tuple as shown below.def foobar((a: expression, b: expression), (c: expression, d: expression)):\n"
},
{
"code": null,
"e": 29156,
"s": 29079,
"text": "def foobar((a: expression, b: expression), (c: expression, d: expression)):\n"
},
{
"code": null,
"e": 29423,
"s": 29156,
"text": "Annotations for return type : Annotating return type is slightly different from annotating function arguments. The ‘->’ is followed by expression which is further followed by ‘:’. Annotation syntax of return type is shown below.def foobar(a: expression)->expression:"
},
{
"code": null,
"e": 29462,
"s": 29423,
"text": "def foobar(a: expression)->expression:"
},
{
"code": null,
"e": 29470,
"s": 29462,
"text": "Grammar"
},
{
"code": null,
"e": 29946,
"s": 29470,
"text": "decorator : ‘@’ name_ [‘(’ [arglist] ‘)’] NEWLINE\ndecorators : decorator+\nfuncdef : [decorators] ‘def’ NAME parameters [‘->’] ‘:’ suite\nparameters : ‘(’ [typedarglist] ‘)’\ntypedarglist : (( tfpdef [‘=’ test] ‘, ’)* (‘*’ [tname]\n(‘, ’ tname [‘=’ test])* [‘, ’ ‘ **’ tname] | ‘**’ tname)\n| tfpdef [‘=’ test (‘, ’ tfpdef [‘=’ test])* [‘, ’]])\ntname : NAME [‘:’ test]\ntfpdef : tname | ‘(’ tfplist ‘)’\ntfplist : tfpdef (‘, ’ tfpdef)* [‘, ’]\n"
},
{
"code": null,
"e": 30110,
"s": 29946,
"text": "Visualizing Grammar : The parse tree is formed from the above grammar to give better visualization of the syntax of the python’s function and function annotations."
},
{
"code": null,
"e": 30122,
"s": 30110,
"text": "Sample Code"
},
{
"code": null,
"e": 30275,
"s": 30122,
"text": "The code below will clear the fact that the function annotations are not evaluated at run time. The code prints fibonacci series upto the ‘n’ positions."
},
{
"code": "# Python program to print Fibonacci seriesdef fib(n:'int', output:'list'=[])-> 'list': if n == 0: return output else: if len(output)< 2: output.append(1) fib(n-1, output) else: last = output[-1] second_last = output[-2] output.append(last + second_last) fib(n-1, output) return outputprint(fib(5))",
"e": 30673,
"s": 30275,
"text": null
},
{
"code": null,
"e": 30697,
"s": 30673,
"text": "Output: [1, 1, 2, 3, 5]"
},
{
"code": null,
"e": 30757,
"s": 30697,
"text": "Note: Function annotations are only supported in python 3x."
},
{
"code": null,
"e": 30788,
"s": 30757,
"text": "Accessing Function Annotations"
},
{
"code": null,
"e": 31076,
"s": 30788,
"text": "1. Using ‘__annotations__’ : The function annotations in the above code can be accessed by a special attribute ‘__annotations__’. It outputs the dictionary having a special key ‘return’ and other keys having name of the annotated arguments. The following code will print the annotations."
},
{
"code": "# Python program to illustrate Function Annotationsdef fib(n:'int', output:'list'=[])-> 'list': if n == 0: return output else: if len(output)< 2: output.append(1) fib(n-1, output) else: last = output[-1] second_last = output[-2] output.append(last + second_last) fib(n-1, output) return outputprint(fib.__annotations__)",
"e": 31496,
"s": 31076,
"text": null
},
{
"code": null,
"e": 31554,
"s": 31496,
"text": "Output: {'return': 'list', 'n': 'int', 'output': 'list'}\n"
},
{
"code": null,
"e": 31982,
"s": 31554,
"text": "2. Using standard module ‘pydoc’ : The ‘pydoc’ is a standard python module that returns the documentation inside a python module(if any). It has a special ‘help()’ method that provides an interactive shell to get help on any keyword, method, class or module. ‘help()’ can be used to access the function annotations. The image below shows the function annotations in the above Fibonacci series code. The module name is ‘fib.py’."
},
{
"code": null,
"e": 32339,
"s": 31982,
"text": "3. Using standard module ‘inspect’: The ‘inspect’ module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. We can use ‘getfullargspec’ method of the module to get complete information about the function which will contain the annotations."
},
{
"code": "# Python program to illustrate Function Annotationsimport inspectdef fib(n:'int', output:'list'=[])-> 'list': if n == 0: return output else: if len(output)< 2: output.append(1) fib(n-1, output) else: last = output[-1] second_last = output[-2] output.append(last + second_last) fib(n-1, output) return outputprint(inspect.getfullargspec(fib))",
"e": 32781,
"s": 32339,
"text": null
},
{
"code": null,
"e": 32966,
"s": 32781,
"text": "Output: FullArgSpec(args=['n', 'output'], varargs=None,\n varkw=None, defaults=([], ), kwonlyargs=[],\nkwonlydefaults=None, annotations=\n{'output': 'list', 'return': 'list', 'n': 'int'})"
},
{
"code": null,
"e": 33002,
"s": 32966,
"text": "Application of Function Annotations"
},
{
"code": null,
"e": 33625,
"s": 33002,
"text": "Use of ‘mypy’ : ‘mypy’ is an external library that provides static type checking with the help of function annotations.Download mypy for python 2xpip install mypypython 3xpip install git+git://github.com/JukkaL/mypy.gitExample 1:# String slicing function that returns a string from start index to end index.def slice(string:str, start: int, end: int) -> str: return string[start:end] slice([1, 2, 3, 4, 5], 2, 4)Save the above code as example.py and run the following command after installation of mypy. Make sure you are in the directory where you have saved the file.mypy example.pyYou will get the following result."
},
{
"code": null,
"e": 33642,
"s": 33625,
"text": "pip install mypy"
},
{
"code": null,
"e": 33652,
"s": 33642,
"text": "python 3x"
},
{
"code": null,
"e": 33701,
"s": 33652,
"text": "pip install git+git://github.com/JukkaL/mypy.git"
},
{
"code": null,
"e": 33712,
"s": 33701,
"text": "Example 1:"
},
{
"code": "# String slicing function that returns a string from start index to end index.def slice(string:str, start: int, end: int) -> str: return string[start:end] slice([1, 2, 3, 4, 5], 2, 4)",
"e": 33900,
"s": 33712,
"text": null
},
{
"code": null,
"e": 34058,
"s": 33900,
"text": "Save the above code as example.py and run the following command after installation of mypy. Make sure you are in the directory where you have saved the file."
},
{
"code": null,
"e": 34074,
"s": 34058,
"text": "mypy example.py"
},
{
"code": null,
"e": 34109,
"s": 34074,
"text": "You will get the following result."
},
{
"code": null,
"e": 34913,
"s": 34109,
"text": "Things are little different when the decorators are involved.Example 2(part a): Type checking of the parameters of the wrapped up function ‘gift_func’ and ‘wrapped’def wrapping_paper(func): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))At first, it may seem that passing string as an argument will return an error as the required datatype is an ‘int’ as annotated in ‘gift_func’ and ‘wrapped’. mypy does not establish typechecking in the wrapped up function parameters however typechecking of the decorator and the return type of the wrapped up functions can be checked. Therefore the following result can be expected from the above code."
},
{
"code": "def wrapping_paper(func): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))",
"e": 35151,
"s": 34913,
"text": null
},
{
"code": null,
"e": 35554,
"s": 35151,
"text": "At first, it may seem that passing string as an argument will return an error as the required datatype is an ‘int’ as annotated in ‘gift_func’ and ‘wrapped’. mypy does not establish typechecking in the wrapped up function parameters however typechecking of the decorator and the return type of the wrapped up functions can be checked. Therefore the following result can be expected from the above code."
},
{
"code": null,
"e": 35922,
"s": 35554,
"text": "Example 2(part b): Typechecking of the parameters of the decorator ‘wrapping_paper’.def wrapping_paper(func:str): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))You will now get the following result."
},
{
"code": "def wrapping_paper(func:str): def wrapped(gift:int): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname:int): return giftname print(gift_func('gtx 5000'))",
"e": 36168,
"s": 35922,
"text": null
},
{
"code": null,
"e": 36207,
"s": 36168,
"text": "You will now get the following result."
},
{
"code": null,
"e": 36634,
"s": 36207,
"text": "Example 2(part c): Typechecking of the return type of ‘gift_func’ and ‘wrapped’# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func): def wrapped(gift) -> int: return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname) -> int: return giftname print(gift_func('gtx 5000'))You will get the following result."
},
{
"code": "# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func): def wrapped(gift) -> int: return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname) -> int: return giftname print(gift_func('gtx 5000'))",
"e": 36948,
"s": 36634,
"text": null
},
{
"code": null,
"e": 36983,
"s": 36948,
"text": "You will get the following result."
},
{
"code": null,
"e": 37413,
"s": 36983,
"text": "Example 2(part d) Typechecking of the return type of the wrapper function ‘wrapping_paper’# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func) -> int: def wrapped(gift): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname): return giftname print(gift_func('gtx 5000'))You will get the following result"
},
{
"code": "# Suppose we want the return type to be intfrom typing import Callabledef wrapping_paper(func) -> int: def wrapped(gift): return 'I got a wrapped up {} for you'.format(str(func(gift))) return wrapped @wrapping_paperdef gift_func(giftname): return giftname print(gift_func('gtx 5000'))",
"e": 37720,
"s": 37413,
"text": null
},
{
"code": null,
"e": 37754,
"s": 37720,
"text": "You will get the following result"
},
{
"code": null,
"e": 38055,
"s": 37754,
"text": "This article is contributed by Anmol Chachra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 38180,
"s": 38055,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 38194,
"s": 38180,
"text": "shubham_singh"
},
{
"code": null,
"e": 38201,
"s": 38194,
"text": "Python"
},
{
"code": null,
"e": 38299,
"s": 38201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38308,
"s": 38299,
"text": "Comments"
},
{
"code": null,
"e": 38321,
"s": 38308,
"text": "Old Comments"
},
{
"code": null,
"e": 38339,
"s": 38321,
"text": "Python Dictionary"
},
{
"code": null,
"e": 38361,
"s": 38339,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 38393,
"s": 38361,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 38435,
"s": 38393,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 38461,
"s": 38435,
"text": "Python String | replace()"
},
{
"code": null,
"e": 38486,
"s": 38461,
"text": "sum() function in Python"
},
{
"code": null,
"e": 38523,
"s": 38486,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 38579,
"s": 38523,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 38608,
"s": 38579,
"text": "*args and **kwargs in Python"
}
] |
SQL Tryit Editor v1.6 | SELECT * FROM Customers
ORDER BY CustomerName DESC;
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": 24,
"s": 0,
"text": "SELECT * FROM Customers"
},
{
"code": null,
"e": 52,
"s": 24,
"text": "ORDER BY CustomerName DESC;"
},
{
"code": null,
"e": 54,
"s": 52,
"text": ""
},
{
"code": null,
"e": 117,
"s": 54,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 177,
"s": 117,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 245,
"s": 177,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 283,
"s": 245,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 368,
"s": 283,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 542,
"s": 368,
"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": 593,
"s": 542,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 661,
"s": 593,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 832,
"s": 661,
"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": 932,
"s": 832,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 992,
"s": 932,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
How do I get the creation date of a MySQL table? | To get the creation date of MySQL table, use the information_schema. The syntax is as follows −
SELECT create_time FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'yourDatabaseName’
AND table_name = 'yourTableName';
Apply the above syntax for your database and the table name. Here I am using the database ‘business’ and table name is ‘student’. The query is as follows −
mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES
-> WHERE table_schema = 'business'
-> AND table_name = 'student';
The following is the output displaying the creation time of a table −
+---------------------+
| CREATE_TIME |
+---------------------+
| 2018-10-01 12:26:57 |
+---------------------+
1 row in set (0.12 sec)
Let us see another example and create a table from scratch.
mysql> create table DateAsStringDemo
-> (
-> YourDateTime datetime
-> );
Query OK, 0 rows affected (0.57 sec)
I have just created a table and my current date time is as follows −
mysql> select now();
The following is the output −
+---------------------+
| now() |
+---------------------+
| 2018-11-26 18:12:29 |
+---------------------+
1 row in set (0.00 sec)
Now you can check the creation time of the above table, which will give the date 2018-11-26.
The query is as follows −
mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES
-> WHERE table_schema = 'test'
-> AND table_name = 'DateAsStringDemo';
The following is the output −
+---------------------+
| CREATE_TIME |
+---------------------+
| 2018-11-26 18:01:44 |
+---------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "To get the creation date of MySQL table, use the information_schema. The syntax is as follows −"
},
{
"code": null,
"e": 1288,
"s": 1158,
"text": "SELECT create_time FROM INFORMATION_SCHEMA.TABLES\n WHERE table_schema = 'yourDatabaseName’\n AND table_name = 'yourTableName';"
},
{
"code": null,
"e": 1444,
"s": 1288,
"text": "Apply the above syntax for your database and the table name. Here I am using the database ‘business’ and table name is ‘student’. The query is as follows −"
},
{
"code": null,
"e": 1573,
"s": 1444,
"text": "mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES\n -> WHERE table_schema = 'business'\n -> AND table_name = 'student';"
},
{
"code": null,
"e": 1643,
"s": 1573,
"text": "The following is the output displaying the creation time of a table −"
},
{
"code": null,
"e": 1787,
"s": 1643,
"text": "+---------------------+\n| CREATE_TIME |\n+---------------------+\n| 2018-10-01 12:26:57 |\n+---------------------+\n1 row in set (0.12 sec)"
},
{
"code": null,
"e": 1847,
"s": 1787,
"text": "Let us see another example and create a table from scratch."
},
{
"code": null,
"e": 1966,
"s": 1847,
"text": "mysql> create table DateAsStringDemo\n -> (\n -> YourDateTime datetime\n -> );\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 2035,
"s": 1966,
"text": "I have just created a table and my current date time is as follows −"
},
{
"code": null,
"e": 2056,
"s": 2035,
"text": "mysql> select now();"
},
{
"code": null,
"e": 2086,
"s": 2056,
"text": "The following is the output −"
},
{
"code": null,
"e": 2230,
"s": 2086,
"text": "+---------------------+\n| now() |\n+---------------------+\n| 2018-11-26 18:12:29 |\n+---------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2323,
"s": 2230,
"text": "Now you can check the creation time of the above table, which will give the date 2018-11-26."
},
{
"code": null,
"e": 2349,
"s": 2323,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2483,
"s": 2349,
"text": "mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES\n -> WHERE table_schema = 'test'\n -> AND table_name = 'DateAsStringDemo';"
},
{
"code": null,
"e": 2513,
"s": 2483,
"text": "The following is the output −"
},
{
"code": null,
"e": 2657,
"s": 2513,
"text": "+---------------------+\n| CREATE_TIME |\n+---------------------+\n| 2018-11-26 18:01:44 |\n+---------------------+\n1 row in set (0.00 sec)"
}
] |
Find all distinct subset (or subsequence) sums of an array - GeeksforGeeks | 19 Apr, 2022
Given a set of integers, find a distinct sum that can be generated from the subsets of the given sets and print them in increasing order. It is given that sum of array elements is small.
Examples:
Input : arr[] = {1, 2, 3}
Output : 0 1 2 3 4 5 6
Distinct subsets of given set are
{}, {1}, {2}, {3}, {1,2}, {2,3},
{1,3} and {1,2,3}. Sums of these
subsets are 0, 1, 2, 3, 3, 5, 4, 6
After removing duplicates, we get
0, 1, 2, 3, 4, 5, 6
Input : arr[] = {2, 3, 4, 5, 6}
Output : 0 2 3 4 5 6 7 8 9 10 11 12
13 14 15 16 17 18 20
Input : arr[] = {20, 30, 50}
Output : 0 20 30 50 70 80 100
The naive solution for this problem is to generate all the subsets, store their sums in a hash set and finally print all keys from the hash set.
C++
Java
Python3
C#
Javascript
// C++ program to print distinct subset sums of// a given array.#include<bits/stdc++.h>using namespace std; // sum denotes the current sum of the subset// currindex denotes the index we have reached in// the given arrayvoid distSumRec(int arr[], int n, int sum, int currindex, unordered_set<int> &s){ if (currindex > n) return; if (currindex == n) { s.insert(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex+1, s); distSumRec(arr, n, sum, currindex+1, s);} // This function mainly calls recursive function// distSumRec() to generate distinct sum subsets.// And finally prints the generated subsets.void printDistSum(int arr[], int n){ unordered_set<int> s; distSumRec(arr, n, 0, 0, s); // Print the result for (auto i=s.begin(); i!=s.end(); i++) cout << *i << " ";} // Driver codeint main(){ int arr[] = {2, 3, 4, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); printDistSum(arr, n); return 0;}
// Java program to print distinct// subset sums of a given array.import java.io.*;import java.util.*; class GFG{ // sum denotes the current sum // of the subset currindex denotes // the index we have reached in // the given array static void distSumRec(int arr[], int n, int sum, int currindex, HashSet<Integer> s) { if (currindex > n) return; if (currindex == n) { s.add(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex + 1, s); distSumRec(arr, n, sum, currindex + 1, s); } // This function mainly calls // recursive function distSumRec() // to generate distinct sum subsets. // And finally prints the generated subsets. static void printDistSum(int arr[], int n) { HashSet<Integer> s = new HashSet<>(); distSumRec(arr, n, 0, 0, s); // Print the result for (int i : s) System.out.print(i + " "); } //Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 5, 6 }; int n = arr.length; printDistSum(arr, n); }} // This code is contributed by Gitanjali.
# Python 3 program to print distinct subset sums of# a given array. # sum denotes the current sum of the subset# currindex denotes the index we have reached in# the given arraydef distSumRec(arr, n, sum, currindex, s): if (currindex > n): return if (currindex == n): s.add(sum) return distSumRec(arr, n, sum + arr[currindex], currindex+1, s) distSumRec(arr, n, sum, currindex+1, s) # This function mainly calls recursive function# distSumRec() to generate distinct sum subsets.# And finally prints the generated subsets.def printDistSum(arr,n): s = set() distSumRec(arr, n, 0, 0, s) # Print the result for i in s: print(i,end = " ") # Driver codeif __name__ == '__main__': arr = [2, 3, 4, 5, 6] n = len(arr) printDistSum(arr, n) # This code is contributed by# Surendra_Gangwar
// C# program to print distinct// subset sums of a given array.using System;using System.Collections.Generic; class GFG{ // sum denotes the current sum // of the subset currindex denotes // the index we have reached in // the given array static void distSumRec(int []arr, int n, int sum, int currindex, HashSet<int> s) { if (currindex > n) return; if (currindex == n) { s.Add(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex + 1, s); distSumRec(arr, n, sum, currindex + 1, s); } // This function mainly calls // recursive function distSumRec() // to generate distinct sum subsets. // And finally prints the generated subsets. static void printDistSum(int []arr, int n) { HashSet<int> s = new HashSet<int>(); distSumRec(arr, n, 0, 0, s); // Print the result foreach (int i in s) Console.Write(i + " "); } // Driver code public static void Main() { int []arr = { 2, 3, 4, 5, 6 }; int n = arr.Length; printDistSum(arr, n); }} /* This code contributed by PrinciRaj1992 */
<script>// Javascript program to print distinct// subset sums of a given array. // sum denotes the current sum // of the subset currindex denotes // the index we have reached in // the given array function distSumRec(arr,n,sum,currindex,s) { if (currindex > n) return; if (currindex == n) { s.add(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex + 1, s); distSumRec(arr, n, sum, currindex + 1, s); } // This function mainly calls // recursive function distSumRec() // to generate distinct sum subsets. // And finally prints the generated subsets. function printDistSum(arr,n) { let s=new Set(); distSumRec(arr, n, 0, 0, s); let s1=[...s] s1.sort(function(a,b){return a-b;}) // Print the result for (let [key, value] of s1.entries()) document.write(value + " "); } //Driver code let arr=[2, 3, 4, 5, 6 ]; let n = arr.length; printDistSum(arr, n); // This code is contributed by unknown2108</script>
Output:
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
The time complexity of the above naive recursive approach is O(2n).
The time complexity of the above problem can be improved using Dynamic Programming, especially when the sum of given elements is small. We can make a dp table with rows containing the size of the array and the size of the column will be the sum of all the elements in the array.
C++
Java
Python3
C#
Javascript
// C++ program to print distinct subset sums of// a given array.#include<bits/stdc++.h>using namespace std; // Uses Dynamic Programming to find distinct// subset sumsvoid printDistSum(int arr[], int n){ int sum = 0; for (int i=0; i<n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] has // a subset with sum equal to j. bool dp[n+1][sum+1]; memset(dp, 0, sizeof(dp)); // There is always a subset with 0 sum for (int i=0; i<=n; i++) dp[i][0] = true; // Fill dp[][] in bottom up manner for (int i=1; i<=n; i++) { dp[i][arr[i-1]] = true; for (int j=1; j<=sum; j++) { // Sums that were achievable // without current array element if (dp[i-1][j] == true) { dp[i][j] = true; dp[i][j + arr[i-1]] = true; } } } // Print last row elements for (int j=0; j<=sum; j++) if (dp[n][j]==true) cout << j << " ";} // Driver codeint main(){ int arr[] = {2, 3, 4, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); printDistSum(arr, n); return 0;}
// Java program to print distinct// subset sums of a given array.import java.io.*;import java.util.*; class GFG { // Uses Dynamic Programming to // find distinct subset sums static void printDistSum(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] // has a subset with sum equal to j. boolean[][] dp = new boolean[n + 1][sum + 1]; // There is always a subset with 0 sum for (int i = 0; i <= n; i++) dp[i][0] = true; // Fill dp[][] in bottom up manner for (int i = 1; i <= n; i++) { dp[i][arr[i - 1]] = true; for (int j = 1; j <= sum; j++) { // Sums that were achievable // without current array element if (dp[i - 1][j] == true) { dp[i][j] = true; dp[i][j + arr[i - 1]] = true; } } } // Print last row elements for (int j = 0; j <= sum; j++) if (dp[n][j] == true) System.out.print(j + " "); } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 5, 6 }; int n = arr.length; printDistSum(arr, n); }} // This code is contributed by Gitanjali.
# Python3 program to print distinct subset# Sums of a given array. # Uses Dynamic Programming to find# distinct subset Sumsdef printDistSum(arr, n): Sum = sum(arr) # dp[i][j] would be true if arr[0..i-1] # has a subset with Sum equal to j. dp = [[False for i in range(Sum + 1)] for i in range(n + 1)] # There is always a subset with 0 Sum for i in range(n + 1): dp[i][0] = True # Fill dp[][] in bottom up manner for i in range(1, n + 1): dp[i][arr[i - 1]] = True for j in range(1, Sum + 1): # Sums that were achievable # without current array element if (dp[i - 1][j] == True): dp[i][j] = True dp[i][j + arr[i - 1]] = True # Print last row elements for j in range(Sum + 1): if (dp[n][j] == True): print(j, end = " ") # Driver codearr = [2, 3, 4, 5, 6]n = len(arr)printDistSum(arr, n) # This code is contributed# by mohit kumar
// C# program to print distinct// subset sums of a given array.using System; class GFG { // Uses Dynamic Programming to // find distinct subset sums static void printDistSum(int []arr, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] // has a subset with sum equal to j. bool [,]dp = new bool[n + 1,sum + 1]; // There is always a subset with 0 sum for (int i = 0; i <= n; i++) dp[i,0] = true; // Fill dp[][] in bottom up manner for (int i = 1; i <= n; i++) { dp[i,arr[i - 1]] = true; for (int j = 1; j <= sum; j++) { // Sums that were achievable // without current array element if (dp[i - 1,j] == true) { dp[i,j] = true; dp[i,j + arr[i - 1]] = true; } } } // Print last row elements for (int j = 0; j <= sum; j++) if (dp[n,j] == true) Console.Write(j + " "); } // Driver code public static void Main() { int []arr = { 2, 3, 4, 5, 6 }; int n = arr.Length; printDistSum(arr, n); }} // This code is contributed by nitin mittal.
<script> // Javascript program to print distinct// subset sums of a given array. // Uses Dynamic Programming to find// distinct subset sumsfunction printDistSum(arr, n){ var sum = 0; for(var i = 0; i < n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] has // a subset with sum equal to j. var dp = Array.from( Array(n + 1), () => Array(sum + 1).fill(0)); // There is always a subset with 0 sum for(var i = 0; i <= n; i++) dp[i][0] = true; // Fill dp[][] in bottom up manner for(var i = 1; i <= n; i++) { dp[i][arr[i - 1]] = true; for(var j = 1; j <= sum; j++) { // Sums that were achievable // without current array element if (dp[i - 1][j] == true) { dp[i][j] = true; dp[i][j + arr[i - 1]] = true; } } } // Print last row elements for(var j = 0; j <= sum; j++) if (dp[n][j] == true) document.write(j + " ");} // Driver codevar arr = [ 2, 3, 4, 5, 6 ];var n = arr.length; printDistSum(arr, n); // This code is contributed by importantly </script>
Output:
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
Time complexity of the above approach is O(n*sum) where n is the size of the array and sum is the sum of all the integers in the array.
Optimized Bit-set Approach
dp = dp | dp << a[i]
Above Code snippet does the same as naive solution, where dp is a bit mask (we’ll use bit-set). Lets see how:
dp → all the sums which were produced before element a[i]dp << a[i] → shifting all the sums by a[i], i.e. adding a[i] to all the sums.For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.This can be denoted by 010100000 which is equivalent to (000010100) << 3dp | (dp << a[i]) → 000010100 | 010100000 = 010110100 This is union of above two sums representing which sums are possible, namely 2, 4, 5 and 7.
dp → all the sums which were produced before element a[i]
dp << a[i] → shifting all the sums by a[i], i.e. adding a[i] to all the sums.For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.This can be denoted by 010100000 which is equivalent to (000010100) << 3
For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.This can be denoted by 010100000 which is equivalent to (000010100) << 3
For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).
Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.
This can be denoted by 010100000 which is equivalent to (000010100) << 3
dp | (dp << a[i]) → 000010100 | 010100000 = 010110100 This is union of above two sums representing which sums are possible, namely 2, 4, 5 and 7.
bitset optimized knapsack
C++
// C++ Program to Demonstrate Bitset Optimised Knapsack// Solution #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Input Vector vector<int> a = { 2, 3, 4, 5, 6 }; // we have to make a constant size for bit-set // and to be safe keep it significantly high int n = a.size(); const int mx = 40; // bitset of size mx, dp[i] is 1 if sum i is possible // and 0 otherwise bitset<mx> dp; // sum 0 is always possible dp[0] = 1; // dp transitions as explained in article for (int i = 0; i < n; ++i) { dp |= dp << a[i]; } // print all the 1s in bit-set, this will be the // all the unique sums possible for (int i = 0; i <= mx; i++) { if (dp[i] == 1) cout << i << " "; }} // code is contributed by sarvjot singh
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
Time Complexity also seems to be O(N * S). Because if we would have used a array instead of bitset the shifting would have taken linear time O(S). However the shift (and almost all) operation on bitset takes O(S / W) time. Where W is the word size of the system, Usually its 32 bit or 64 bit. Thus the final time complexity becomes O(N * S / W)
Some Important Points:
The size of bitset must be a constant, this sometimes is a drawback as we might waste some space.Bitset can be thought of a array where every element takes care of W elements. For example 010110100 is equivalent to {2, 6, 4} in a hypothetical system with word size W = 3.Bitset optimized knapsack solution reduced the time complexity by a factor of W which sometimes is just enough to get AC.
The size of bitset must be a constant, this sometimes is a drawback as we might waste some space.
Bitset can be thought of a array where every element takes care of W elements. For example 010110100 is equivalent to {2, 6, 4} in a hypothetical system with word size W = 3.
Bitset optimized knapsack solution reduced the time complexity by a factor of W which sometimes is just enough to get AC.
This article is contributed by Karan Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
princiraj1992
mohit kumar 29
SURENDRA_GANGWAR
unknown2108
importantly
surinderdawra388
sarvjot
subsequence
subset
Dynamic Programming
Dynamic Programming
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Sieve of Eratosthenes
Overlapping Subproblems Property in Dynamic Programming | DP-1
Edit Distance | DP-5
Minimum number of jumps to reach end | [
{
"code": null,
"e": 24601,
"s": 24573,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 24788,
"s": 24601,
"text": "Given a set of integers, find a distinct sum that can be generated from the subsets of the given sets and print them in increasing order. It is given that sum of array elements is small."
},
{
"code": null,
"e": 24800,
"s": 24788,
"text": "Examples: "
},
{
"code": null,
"e": 25203,
"s": 24800,
"text": "Input : arr[] = {1, 2, 3}\nOutput : 0 1 2 3 4 5 6\nDistinct subsets of given set are\n{}, {1}, {2}, {3}, {1,2}, {2,3}, \n{1,3} and {1,2,3}. Sums of these\nsubsets are 0, 1, 2, 3, 3, 5, 4, 6\nAfter removing duplicates, we get\n0, 1, 2, 3, 4, 5, 6 \n\nInput : arr[] = {2, 3, 4, 5, 6}\nOutput : 0 2 3 4 5 6 7 8 9 10 11 12 \n 13 14 15 16 17 18 20\n\nInput : arr[] = {20, 30, 50}\nOutput : 0 20 30 50 70 80 100"
},
{
"code": null,
"e": 25350,
"s": 25203,
"text": "The naive solution for this problem is to generate all the subsets, store their sums in a hash set and finally print all keys from the hash set. "
},
{
"code": null,
"e": 25354,
"s": 25350,
"text": "C++"
},
{
"code": null,
"e": 25359,
"s": 25354,
"text": "Java"
},
{
"code": null,
"e": 25367,
"s": 25359,
"text": "Python3"
},
{
"code": null,
"e": 25370,
"s": 25367,
"text": "C#"
},
{
"code": null,
"e": 25381,
"s": 25370,
"text": "Javascript"
},
{
"code": "// C++ program to print distinct subset sums of// a given array.#include<bits/stdc++.h>using namespace std; // sum denotes the current sum of the subset// currindex denotes the index we have reached in// the given arrayvoid distSumRec(int arr[], int n, int sum, int currindex, unordered_set<int> &s){ if (currindex > n) return; if (currindex == n) { s.insert(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex+1, s); distSumRec(arr, n, sum, currindex+1, s);} // This function mainly calls recursive function// distSumRec() to generate distinct sum subsets.// And finally prints the generated subsets.void printDistSum(int arr[], int n){ unordered_set<int> s; distSumRec(arr, n, 0, 0, s); // Print the result for (auto i=s.begin(); i!=s.end(); i++) cout << *i << \" \";} // Driver codeint main(){ int arr[] = {2, 3, 4, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); printDistSum(arr, n); return 0;}",
"e": 26404,
"s": 25381,
"text": null
},
{
"code": "// Java program to print distinct// subset sums of a given array.import java.io.*;import java.util.*; class GFG{ // sum denotes the current sum // of the subset currindex denotes // the index we have reached in // the given array static void distSumRec(int arr[], int n, int sum, int currindex, HashSet<Integer> s) { if (currindex > n) return; if (currindex == n) { s.add(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex + 1, s); distSumRec(arr, n, sum, currindex + 1, s); } // This function mainly calls // recursive function distSumRec() // to generate distinct sum subsets. // And finally prints the generated subsets. static void printDistSum(int arr[], int n) { HashSet<Integer> s = new HashSet<>(); distSumRec(arr, n, 0, 0, s); // Print the result for (int i : s) System.out.print(i + \" \"); } //Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 5, 6 }; int n = arr.length; printDistSum(arr, n); }} // This code is contributed by Gitanjali.",
"e": 27629,
"s": 26404,
"text": null
},
{
"code": "# Python 3 program to print distinct subset sums of# a given array. # sum denotes the current sum of the subset# currindex denotes the index we have reached in# the given arraydef distSumRec(arr, n, sum, currindex, s): if (currindex > n): return if (currindex == n): s.add(sum) return distSumRec(arr, n, sum + arr[currindex], currindex+1, s) distSumRec(arr, n, sum, currindex+1, s) # This function mainly calls recursive function# distSumRec() to generate distinct sum subsets.# And finally prints the generated subsets.def printDistSum(arr,n): s = set() distSumRec(arr, n, 0, 0, s) # Print the result for i in s: print(i,end = \" \") # Driver codeif __name__ == '__main__': arr = [2, 3, 4, 5, 6] n = len(arr) printDistSum(arr, n) # This code is contributed by# Surendra_Gangwar",
"e": 28470,
"s": 27629,
"text": null
},
{
"code": "// C# program to print distinct// subset sums of a given array.using System;using System.Collections.Generic; class GFG{ // sum denotes the current sum // of the subset currindex denotes // the index we have reached in // the given array static void distSumRec(int []arr, int n, int sum, int currindex, HashSet<int> s) { if (currindex > n) return; if (currindex == n) { s.Add(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex + 1, s); distSumRec(arr, n, sum, currindex + 1, s); } // This function mainly calls // recursive function distSumRec() // to generate distinct sum subsets. // And finally prints the generated subsets. static void printDistSum(int []arr, int n) { HashSet<int> s = new HashSet<int>(); distSumRec(arr, n, 0, 0, s); // Print the result foreach (int i in s) Console.Write(i + \" \"); } // Driver code public static void Main() { int []arr = { 2, 3, 4, 5, 6 }; int n = arr.Length; printDistSum(arr, n); }} /* This code contributed by PrinciRaj1992 */",
"e": 29696,
"s": 28470,
"text": null
},
{
"code": "<script>// Javascript program to print distinct// subset sums of a given array. // sum denotes the current sum // of the subset currindex denotes // the index we have reached in // the given array function distSumRec(arr,n,sum,currindex,s) { if (currindex > n) return; if (currindex == n) { s.add(sum); return; } distSumRec(arr, n, sum + arr[currindex], currindex + 1, s); distSumRec(arr, n, sum, currindex + 1, s); } // This function mainly calls // recursive function distSumRec() // to generate distinct sum subsets. // And finally prints the generated subsets. function printDistSum(arr,n) { let s=new Set(); distSumRec(arr, n, 0, 0, s); let s1=[...s] s1.sort(function(a,b){return a-b;}) // Print the result for (let [key, value] of s1.entries()) document.write(value + \" \"); } //Driver code let arr=[2, 3, 4, 5, 6 ]; let n = arr.length; printDistSum(arr, n); // This code is contributed by unknown2108</script>",
"e": 30847,
"s": 29696,
"text": null
},
{
"code": null,
"e": 30857,
"s": 30847,
"text": "Output: "
},
{
"code": null,
"e": 30905,
"s": 30857,
"text": "0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20"
},
{
"code": null,
"e": 30973,
"s": 30905,
"text": "The time complexity of the above naive recursive approach is O(2n)."
},
{
"code": null,
"e": 31254,
"s": 30973,
"text": "The time complexity of the above problem can be improved using Dynamic Programming, especially when the sum of given elements is small. We can make a dp table with rows containing the size of the array and the size of the column will be the sum of all the elements in the array. "
},
{
"code": null,
"e": 31258,
"s": 31254,
"text": "C++"
},
{
"code": null,
"e": 31263,
"s": 31258,
"text": "Java"
},
{
"code": null,
"e": 31271,
"s": 31263,
"text": "Python3"
},
{
"code": null,
"e": 31274,
"s": 31271,
"text": "C#"
},
{
"code": null,
"e": 31285,
"s": 31274,
"text": "Javascript"
},
{
"code": "// C++ program to print distinct subset sums of// a given array.#include<bits/stdc++.h>using namespace std; // Uses Dynamic Programming to find distinct// subset sumsvoid printDistSum(int arr[], int n){ int sum = 0; for (int i=0; i<n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] has // a subset with sum equal to j. bool dp[n+1][sum+1]; memset(dp, 0, sizeof(dp)); // There is always a subset with 0 sum for (int i=0; i<=n; i++) dp[i][0] = true; // Fill dp[][] in bottom up manner for (int i=1; i<=n; i++) { dp[i][arr[i-1]] = true; for (int j=1; j<=sum; j++) { // Sums that were achievable // without current array element if (dp[i-1][j] == true) { dp[i][j] = true; dp[i][j + arr[i-1]] = true; } } } // Print last row elements for (int j=0; j<=sum; j++) if (dp[n][j]==true) cout << j << \" \";} // Driver codeint main(){ int arr[] = {2, 3, 4, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); printDistSum(arr, n); return 0;}",
"e": 32422,
"s": 31285,
"text": null
},
{
"code": "// Java program to print distinct// subset sums of a given array.import java.io.*;import java.util.*; class GFG { // Uses Dynamic Programming to // find distinct subset sums static void printDistSum(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] // has a subset with sum equal to j. boolean[][] dp = new boolean[n + 1][sum + 1]; // There is always a subset with 0 sum for (int i = 0; i <= n; i++) dp[i][0] = true; // Fill dp[][] in bottom up manner for (int i = 1; i <= n; i++) { dp[i][arr[i - 1]] = true; for (int j = 1; j <= sum; j++) { // Sums that were achievable // without current array element if (dp[i - 1][j] == true) { dp[i][j] = true; dp[i][j + arr[i - 1]] = true; } } } // Print last row elements for (int j = 0; j <= sum; j++) if (dp[n][j] == true) System.out.print(j + \" \"); } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 5, 6 }; int n = arr.length; printDistSum(arr, n); }} // This code is contributed by Gitanjali.",
"e": 33811,
"s": 32422,
"text": null
},
{
"code": "# Python3 program to print distinct subset# Sums of a given array. # Uses Dynamic Programming to find# distinct subset Sumsdef printDistSum(arr, n): Sum = sum(arr) # dp[i][j] would be true if arr[0..i-1] # has a subset with Sum equal to j. dp = [[False for i in range(Sum + 1)] for i in range(n + 1)] # There is always a subset with 0 Sum for i in range(n + 1): dp[i][0] = True # Fill dp[][] in bottom up manner for i in range(1, n + 1): dp[i][arr[i - 1]] = True for j in range(1, Sum + 1): # Sums that were achievable # without current array element if (dp[i - 1][j] == True): dp[i][j] = True dp[i][j + arr[i - 1]] = True # Print last row elements for j in range(Sum + 1): if (dp[n][j] == True): print(j, end = \" \") # Driver codearr = [2, 3, 4, 5, 6]n = len(arr)printDistSum(arr, n) # This code is contributed# by mohit kumar",
"e": 34839,
"s": 33811,
"text": null
},
{
"code": "// C# program to print distinct// subset sums of a given array.using System; class GFG { // Uses Dynamic Programming to // find distinct subset sums static void printDistSum(int []arr, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] // has a subset with sum equal to j. bool [,]dp = new bool[n + 1,sum + 1]; // There is always a subset with 0 sum for (int i = 0; i <= n; i++) dp[i,0] = true; // Fill dp[][] in bottom up manner for (int i = 1; i <= n; i++) { dp[i,arr[i - 1]] = true; for (int j = 1; j <= sum; j++) { // Sums that were achievable // without current array element if (dp[i - 1,j] == true) { dp[i,j] = true; dp[i,j + arr[i - 1]] = true; } } } // Print last row elements for (int j = 0; j <= sum; j++) if (dp[n,j] == true) Console.Write(j + \" \"); } // Driver code public static void Main() { int []arr = { 2, 3, 4, 5, 6 }; int n = arr.Length; printDistSum(arr, n); }} // This code is contributed by nitin mittal.",
"e": 36180,
"s": 34839,
"text": null
},
{
"code": "<script> // Javascript program to print distinct// subset sums of a given array. // Uses Dynamic Programming to find// distinct subset sumsfunction printDistSum(arr, n){ var sum = 0; for(var i = 0; i < n; i++) sum += arr[i]; // dp[i][j] would be true if arr[0..i-1] has // a subset with sum equal to j. var dp = Array.from( Array(n + 1), () => Array(sum + 1).fill(0)); // There is always a subset with 0 sum for(var i = 0; i <= n; i++) dp[i][0] = true; // Fill dp[][] in bottom up manner for(var i = 1; i <= n; i++) { dp[i][arr[i - 1]] = true; for(var j = 1; j <= sum; j++) { // Sums that were achievable // without current array element if (dp[i - 1][j] == true) { dp[i][j] = true; dp[i][j + arr[i - 1]] = true; } } } // Print last row elements for(var j = 0; j <= sum; j++) if (dp[n][j] == true) document.write(j + \" \");} // Driver codevar arr = [ 2, 3, 4, 5, 6 ];var n = arr.length; printDistSum(arr, n); // This code is contributed by importantly </script>",
"e": 37349,
"s": 36180,
"text": null
},
{
"code": null,
"e": 37359,
"s": 37349,
"text": "Output: "
},
{
"code": null,
"e": 37407,
"s": 37359,
"text": "0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20"
},
{
"code": null,
"e": 37543,
"s": 37407,
"text": "Time complexity of the above approach is O(n*sum) where n is the size of the array and sum is the sum of all the integers in the array."
},
{
"code": null,
"e": 37570,
"s": 37543,
"text": "Optimized Bit-set Approach"
},
{
"code": null,
"e": 37591,
"s": 37570,
"text": "dp = dp | dp << a[i]"
},
{
"code": null,
"e": 37701,
"s": 37591,
"text": "Above Code snippet does the same as naive solution, where dp is a bit mask (we’ll use bit-set). Lets see how:"
},
{
"code": null,
"e": 38260,
"s": 37701,
"text": "dp → all the sums which were produced before element a[i]dp << a[i] → shifting all the sums by a[i], i.e. adding a[i] to all the sums.For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.This can be denoted by 010100000 which is equivalent to (000010100) << 3dp | (dp << a[i]) → 000010100 | 010100000 = 010110100 This is union of above two sums representing which sums are possible, namely 2, 4, 5 and 7."
},
{
"code": null,
"e": 38318,
"s": 38260,
"text": "dp → all the sums which were produced before element a[i]"
},
{
"code": null,
"e": 38675,
"s": 38318,
"text": "dp << a[i] → shifting all the sums by a[i], i.e. adding a[i] to all the sums.For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.This can be denoted by 010100000 which is equivalent to (000010100) << 3"
},
{
"code": null,
"e": 38955,
"s": 38675,
"text": "For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.This can be denoted by 010100000 which is equivalent to (000010100) << 3"
},
{
"code": null,
"e": 39072,
"s": 38955,
"text": "For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right)."
},
{
"code": null,
"e": 39164,
"s": 39072,
"text": "Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively."
},
{
"code": null,
"e": 39237,
"s": 39164,
"text": "This can be denoted by 010100000 which is equivalent to (000010100) << 3"
},
{
"code": null,
"e": 39383,
"s": 39237,
"text": "dp | (dp << a[i]) → 000010100 | 010100000 = 010110100 This is union of above two sums representing which sums are possible, namely 2, 4, 5 and 7."
},
{
"code": null,
"e": 39409,
"s": 39383,
"text": "bitset optimized knapsack"
},
{
"code": null,
"e": 39413,
"s": 39409,
"text": "C++"
},
{
"code": "// C++ Program to Demonstrate Bitset Optimised Knapsack// Solution #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Input Vector vector<int> a = { 2, 3, 4, 5, 6 }; // we have to make a constant size for bit-set // and to be safe keep it significantly high int n = a.size(); const int mx = 40; // bitset of size mx, dp[i] is 1 if sum i is possible // and 0 otherwise bitset<mx> dp; // sum 0 is always possible dp[0] = 1; // dp transitions as explained in article for (int i = 0; i < n; ++i) { dp |= dp << a[i]; } // print all the 1s in bit-set, this will be the // all the unique sums possible for (int i = 0; i <= mx; i++) { if (dp[i] == 1) cout << i << \" \"; }} // code is contributed by sarvjot singh",
"e": 40224,
"s": 39413,
"text": null
},
{
"code": null,
"e": 40273,
"s": 40224,
"text": "0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 "
},
{
"code": null,
"e": 40618,
"s": 40273,
"text": "Time Complexity also seems to be O(N * S). Because if we would have used a array instead of bitset the shifting would have taken linear time O(S). However the shift (and almost all) operation on bitset takes O(S / W) time. Where W is the word size of the system, Usually its 32 bit or 64 bit. Thus the final time complexity becomes O(N * S / W)"
},
{
"code": null,
"e": 40641,
"s": 40618,
"text": "Some Important Points:"
},
{
"code": null,
"e": 41034,
"s": 40641,
"text": "The size of bitset must be a constant, this sometimes is a drawback as we might waste some space.Bitset can be thought of a array where every element takes care of W elements. For example 010110100 is equivalent to {2, 6, 4} in a hypothetical system with word size W = 3.Bitset optimized knapsack solution reduced the time complexity by a factor of W which sometimes is just enough to get AC."
},
{
"code": null,
"e": 41132,
"s": 41034,
"text": "The size of bitset must be a constant, this sometimes is a drawback as we might waste some space."
},
{
"code": null,
"e": 41307,
"s": 41132,
"text": "Bitset can be thought of a array where every element takes care of W elements. For example 010110100 is equivalent to {2, 6, 4} in a hypothetical system with word size W = 3."
},
{
"code": null,
"e": 41429,
"s": 41307,
"text": "Bitset optimized knapsack solution reduced the time complexity by a factor of W which sometimes is just enough to get AC."
},
{
"code": null,
"e": 41848,
"s": 41429,
"text": "This article is contributed by Karan Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 41861,
"s": 41848,
"text": "nitin mittal"
},
{
"code": null,
"e": 41875,
"s": 41861,
"text": "princiraj1992"
},
{
"code": null,
"e": 41890,
"s": 41875,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 41907,
"s": 41890,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 41919,
"s": 41907,
"text": "unknown2108"
},
{
"code": null,
"e": 41931,
"s": 41919,
"text": "importantly"
},
{
"code": null,
"e": 41948,
"s": 41931,
"text": "surinderdawra388"
},
{
"code": null,
"e": 41956,
"s": 41948,
"text": "sarvjot"
},
{
"code": null,
"e": 41968,
"s": 41956,
"text": "subsequence"
},
{
"code": null,
"e": 41975,
"s": 41968,
"text": "subset"
},
{
"code": null,
"e": 41995,
"s": 41975,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42015,
"s": 41995,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42022,
"s": 42015,
"text": "subset"
},
{
"code": null,
"e": 42120,
"s": 42022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42129,
"s": 42120,
"text": "Comments"
},
{
"code": null,
"e": 42142,
"s": 42129,
"text": "Old Comments"
},
{
"code": null,
"e": 42173,
"s": 42142,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 42206,
"s": 42173,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 42225,
"s": 42206,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 42260,
"s": 42225,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 42298,
"s": 42260,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 42366,
"s": 42298,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 42388,
"s": 42366,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 42451,
"s": 42388,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 42472,
"s": 42451,
"text": "Edit Distance | DP-5"
}
] |
Unary operators in C/C++ | Here we will see what are the unary operators in C / C++. Unary operator is operators that act upon a single operand to produce a new value. The unary operators are as follows.
These operators have right-to-left associativity. Unary expressions generally involve syntax that precedes a postfix or primary expression
Let's look at an example of the -(minus) and casting() unary operators.
Live Demo
#include<iostream>
using namespace std;
int main() {
int x;
float y = 1.23;
x = (int) y;
x = -x;
cout << x;
return 0;
}
-1 | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Here we will see what are the unary operators in C / C++. Unary operator is operators that act upon a single operand to produce a new value. The unary operators are as follows."
},
{
"code": null,
"e": 1378,
"s": 1239,
"text": "These operators have right-to-left associativity. Unary expressions generally involve syntax that precedes a postfix or primary expression"
},
{
"code": null,
"e": 1450,
"s": 1378,
"text": "Let's look at an example of the -(minus) and casting() unary operators."
},
{
"code": null,
"e": 1461,
"s": 1450,
"text": " Live Demo"
},
{
"code": null,
"e": 1599,
"s": 1461,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int x;\n float y = 1.23;\n x = (int) y;\n x = -x;\n cout << x;\n return 0;\n}"
},
{
"code": null,
"e": 1602,
"s": 1599,
"text": "-1"
}
] |
Perl - Coding Standard | Each programmer will, of course, have his or her own preferences in regards to formatting, but there are some general guidelines that will make your programs easier to read, understand, and maintain.
The most important thing is to run your programs under the -w flag at all times. You may turn it off explicitly for particular portions of code via the no warnings pragma or the $^W variable if you must. You should also always run under use strict or know the reason why not. The use sigtrap and even use diagnostics pragmas may also prove useful.
Regarding aesthetics of code lay out, about the only thing Larry cares strongly about is that the closing curly bracket of a multi-line BLOCK should line up with the keyword that started the construct. Beyond that, he has other preferences that aren't so strong −
4-column indent.
Opening curly on same line as keyword, if possible, otherwise line up.
Space before the opening curly of a multi-line BLOCK.
One-line BLOCK may be put on one line, including curlies.
No space before the semicolon.
Semicolon omitted in "short" one-line BLOCK.
Space around most operators.
Space around a "complex" subscript (inside brackets).
Blank lines between chunks that do different things.
Uncuddled elses.
No space between function name and its opening parenthesis.
Space after each comma.
Long lines broken after an operator (except and and or).
Space after last parenthesis matching on current line.
Line up corresponding items vertically.
Omit redundant punctuation as long as clarity doesn't suffer.
Here are some other more substantive style issues to think about: Just because you CAN do something a particular way doesn't mean that you SHOULD do it that way. Perl is designed to give you several ways to do anything, so consider picking the most readable one. For instance −
open(FOO,$foo) || die "Can't open $foo: $!";
Is better than −
die "Can't open $foo: $!" unless open(FOO,$foo);
Because the second way hides the main point of the statement in a modifier. On the other hand,
print "Starting analysis\n" if $verbose;
Is better than −
$verbose && print "Starting analysis\n";
Because the main point isn't whether the user typed -v or not.
Don't go through silly contortions to exit a loop at the top or the bottom, when Perl provides the last operator so you can exit in the middle. Just "outdent" it a little to make it more visible −
LINE:
for (;;) {
statements;
last LINE if $foo;
next LINE if /^#/;
statements;
}
Let's see few more important points −
Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the previous example.
Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the previous example.
Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead.
Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead.
For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed.
For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed.
Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem.
Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem.
While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS.
While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS.
Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for "pragma" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes.
Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for "pragma" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes.
If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or backslashes.
If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or backslashes.
Always check the return codes of system calls. Good error messages should go to STDERR, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple but sufficient example −
Always check the return codes of system calls. Good error messages should go to STDERR, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple but sufficient example −
opendir(D, $dir) or die "can't opendir $dir: $!";
Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and use warnings (or -w) in effect. Consider giving away your code. Consider changing your whole world view. Consider... oh, never mind.
Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and use warnings (or -w) in effect. Consider giving away your code. Consider changing your whole world view. Consider... oh, never mind.
Be consistent.
Be consistent.
Be nice.
Be nice.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2420,
"s": 2220,
"text": "Each programmer will, of course, have his or her own preferences in regards to formatting, but there are some general guidelines that will make your programs easier to read, understand, and maintain."
},
{
"code": null,
"e": 2768,
"s": 2420,
"text": "The most important thing is to run your programs under the -w flag at all times. You may turn it off explicitly for particular portions of code via the no warnings pragma or the $^W variable if you must. You should also always run under use strict or know the reason why not. The use sigtrap and even use diagnostics pragmas may also prove useful."
},
{
"code": null,
"e": 3032,
"s": 2768,
"text": "Regarding aesthetics of code lay out, about the only thing Larry cares strongly about is that the closing curly bracket of a multi-line BLOCK should line up with the keyword that started the construct. Beyond that, he has other preferences that aren't so strong −"
},
{
"code": null,
"e": 3049,
"s": 3032,
"text": "4-column indent."
},
{
"code": null,
"e": 3120,
"s": 3049,
"text": "Opening curly on same line as keyword, if possible, otherwise line up."
},
{
"code": null,
"e": 3174,
"s": 3120,
"text": "Space before the opening curly of a multi-line BLOCK."
},
{
"code": null,
"e": 3232,
"s": 3174,
"text": "One-line BLOCK may be put on one line, including curlies."
},
{
"code": null,
"e": 3263,
"s": 3232,
"text": "No space before the semicolon."
},
{
"code": null,
"e": 3308,
"s": 3263,
"text": "Semicolon omitted in \"short\" one-line BLOCK."
},
{
"code": null,
"e": 3337,
"s": 3308,
"text": "Space around most operators."
},
{
"code": null,
"e": 3391,
"s": 3337,
"text": "Space around a \"complex\" subscript (inside brackets)."
},
{
"code": null,
"e": 3444,
"s": 3391,
"text": "Blank lines between chunks that do different things."
},
{
"code": null,
"e": 3461,
"s": 3444,
"text": "Uncuddled elses."
},
{
"code": null,
"e": 3521,
"s": 3461,
"text": "No space between function name and its opening parenthesis."
},
{
"code": null,
"e": 3545,
"s": 3521,
"text": "Space after each comma."
},
{
"code": null,
"e": 3602,
"s": 3545,
"text": "Long lines broken after an operator (except and and or)."
},
{
"code": null,
"e": 3657,
"s": 3602,
"text": "Space after last parenthesis matching on current line."
},
{
"code": null,
"e": 3697,
"s": 3657,
"text": "Line up corresponding items vertically."
},
{
"code": null,
"e": 3759,
"s": 3697,
"text": "Omit redundant punctuation as long as clarity doesn't suffer."
},
{
"code": null,
"e": 4037,
"s": 3759,
"text": "Here are some other more substantive style issues to think about: Just because you CAN do something a particular way doesn't mean that you SHOULD do it that way. Perl is designed to give you several ways to do anything, so consider picking the most readable one. For instance −"
},
{
"code": null,
"e": 4082,
"s": 4037,
"text": "open(FOO,$foo) || die \"Can't open $foo: $!\";"
},
{
"code": null,
"e": 4099,
"s": 4082,
"text": "Is better than −"
},
{
"code": null,
"e": 4148,
"s": 4099,
"text": "die \"Can't open $foo: $!\" unless open(FOO,$foo);"
},
{
"code": null,
"e": 4243,
"s": 4148,
"text": "Because the second way hides the main point of the statement in a modifier. On the other hand,"
},
{
"code": null,
"e": 4284,
"s": 4243,
"text": "print \"Starting analysis\\n\" if $verbose;"
},
{
"code": null,
"e": 4301,
"s": 4284,
"text": "Is better than −"
},
{
"code": null,
"e": 4342,
"s": 4301,
"text": "$verbose && print \"Starting analysis\\n\";"
},
{
"code": null,
"e": 4405,
"s": 4342,
"text": "Because the main point isn't whether the user typed -v or not."
},
{
"code": null,
"e": 4602,
"s": 4405,
"text": "Don't go through silly contortions to exit a loop at the top or the bottom, when Perl provides the last operator so you can exit in the middle. Just \"outdent\" it a little to make it more visible −"
},
{
"code": null,
"e": 4695,
"s": 4602,
"text": "LINE:\nfor (;;) {\n statements;\n last LINE if $foo;\n next LINE if /^#/;\n statements;\n}"
},
{
"code": null,
"e": 4733,
"s": 4695,
"text": "Let's see few more important points −"
},
{
"code": null,
"e": 4876,
"s": 4733,
"text": "Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the previous example."
},
{
"code": null,
"e": 5019,
"s": 4876,
"text": "Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the previous example."
},
{
"code": null,
"e": 5256,
"s": 5019,
"text": "Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead."
},
{
"code": null,
"e": 5493,
"s": 5256,
"text": "Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead."
},
{
"code": null,
"e": 5890,
"s": 5493,
"text": "For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed."
},
{
"code": null,
"e": 6287,
"s": 5890,
"text": "For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed."
},
{
"code": null,
"e": 6381,
"s": 6287,
"text": "Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem."
},
{
"code": null,
"e": 6475,
"s": 6381,
"text": "Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem."
},
{
"code": null,
"e": 6782,
"s": 6475,
"text": "While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS."
},
{
"code": null,
"e": 7089,
"s": 6782,
"text": "While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS."
},
{
"code": null,
"e": 7466,
"s": 7089,
"text": "Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for \"pragma\" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes."
},
{
"code": null,
"e": 7843,
"s": 7466,
"text": "Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for \"pragma\" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes."
},
{
"code": null,
"e": 8060,
"s": 7843,
"text": "If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or backslashes."
},
{
"code": null,
"e": 8277,
"s": 8060,
"text": "If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or backslashes."
},
{
"code": null,
"e": 8588,
"s": 8277,
"text": "Always check the return codes of system calls. Good error messages should go to STDERR, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple but sufficient example − "
},
{
"code": null,
"e": 8899,
"s": 8588,
"text": "Always check the return codes of system calls. Good error messages should go to STDERR, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple but sufficient example − "
},
{
"code": null,
"e": 8949,
"s": 8899,
"text": "opendir(D, $dir) or die \"can't opendir $dir: $!\";"
},
{
"code": null,
"e": 9327,
"s": 8949,
"text": "Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and use warnings (or -w) in effect. Consider giving away your code. Consider changing your whole world view. Consider... oh, never mind."
},
{
"code": null,
"e": 9705,
"s": 9327,
"text": "Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and use warnings (or -w) in effect. Consider giving away your code. Consider changing your whole world view. Consider... oh, never mind."
},
{
"code": null,
"e": 9720,
"s": 9705,
"text": "Be consistent."
},
{
"code": null,
"e": 9735,
"s": 9720,
"text": "Be consistent."
},
{
"code": null,
"e": 9744,
"s": 9735,
"text": "Be nice."
},
{
"code": null,
"e": 9753,
"s": 9744,
"text": "Be nice."
},
{
"code": null,
"e": 9788,
"s": 9753,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9802,
"s": 9788,
"text": " Devi Killada"
},
{
"code": null,
"e": 9837,
"s": 9802,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9857,
"s": 9837,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 9890,
"s": 9857,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9906,
"s": 9890,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 9939,
"s": 9906,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9956,
"s": 9939,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 9989,
"s": 9956,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 10012,
"s": 9989,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 10047,
"s": 10012,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 10070,
"s": 10047,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 10077,
"s": 10070,
"text": " Print"
},
{
"code": null,
"e": 10088,
"s": 10077,
"text": " Add Notes"
}
] |
Explain the basic structure of a program in Java? | A typical structure of a Java program contains the following elements
Package declaration
Import statements
Comments
Class definition
Class variables, Local variables
Methods/Behaviors
A class in Java can be placed in different directories/packages based on the module they are used. For all the classes that belong to a single parent source directory, a path from source directory is considered as package declaration.
There can be classes written in other folders/packages of our working java project and also there are many classes written by individuals, companies, etc which can be useful in our program. To use them in a class, we need to import the class that we intend to use. Many classes can be imported in a single program and hence multiple import statements can be written.
The comments in Java can be used to provide information about the variable, method, class or any other statement. It can also be used to hide the program code for a specific time.
A name should be given to a class in a java file. This name is used while creating an object of a class, in other classes/programs.
The Variables are storing the values of parameters that are required during the execution of the program. Variables declared with modifiers have different scopes, which define the life of a variable.
Execution of a Java application starts from the main method. In other words, its an entry point for the class or program that starts in Java Run-time.
A set of instructions which form a purposeful functionality that can be required to run multiple times during the execution of a program. To not repeat the same set of instructions when the same functionality is required, the instructions are enclosed in a method. A method’s behavior can be exploited by passing variable values to a method.
Live Demo
package abc; // A package declaration
import java.util.*; // declaration of an import statement
// This is a sample program to understnd basic structure of Java (Comment Section)
public class JavaProgramStructureTest { // class name
int repeat = 4; // global variable
public static void main(String args[]) { // main method
JavaProgramStructureTest test = new JavaProgramStructureTest();
test.printMessage("Welcome to Tutorials Point");
}
public void printMessage(String msg) { // method
Date date = new Date(); // variable local to method
for(int index = 0; index < repeat; index++) { // Here index - variable local to for loop
System.out.println(msg + "From" + date.toGMTString());
}
}
}
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT
Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "A typical structure of a Java program contains the following elements"
},
{
"code": null,
"e": 1152,
"s": 1132,
"text": "Package declaration"
},
{
"code": null,
"e": 1170,
"s": 1152,
"text": "Import statements"
},
{
"code": null,
"e": 1179,
"s": 1170,
"text": "Comments"
},
{
"code": null,
"e": 1196,
"s": 1179,
"text": "Class definition"
},
{
"code": null,
"e": 1229,
"s": 1196,
"text": "Class variables, Local variables"
},
{
"code": null,
"e": 1247,
"s": 1229,
"text": "Methods/Behaviors"
},
{
"code": null,
"e": 1482,
"s": 1247,
"text": "A class in Java can be placed in different directories/packages based on the module they are used. For all the classes that belong to a single parent source directory, a path from source directory is considered as package declaration."
},
{
"code": null,
"e": 1849,
"s": 1482,
"text": "There can be classes written in other folders/packages of our working java project and also there are many classes written by individuals, companies, etc which can be useful in our program. To use them in a class, we need to import the class that we intend to use. Many classes can be imported in a single program and hence multiple import statements can be written."
},
{
"code": null,
"e": 2029,
"s": 1849,
"text": "The comments in Java can be used to provide information about the variable, method, class or any other statement. It can also be used to hide the program code for a specific time."
},
{
"code": null,
"e": 2161,
"s": 2029,
"text": "A name should be given to a class in a java file. This name is used while creating an object of a class, in other classes/programs."
},
{
"code": null,
"e": 2361,
"s": 2161,
"text": "The Variables are storing the values of parameters that are required during the execution of the program. Variables declared with modifiers have different scopes, which define the life of a variable."
},
{
"code": null,
"e": 2512,
"s": 2361,
"text": "Execution of a Java application starts from the main method. In other words, its an entry point for the class or program that starts in Java Run-time."
},
{
"code": null,
"e": 2854,
"s": 2512,
"text": "A set of instructions which form a purposeful functionality that can be required to run multiple times during the execution of a program. To not repeat the same set of instructions when the same functionality is required, the instructions are enclosed in a method. A method’s behavior can be exploited by passing variable values to a method."
},
{
"code": null,
"e": 2864,
"s": 2854,
"text": "Live Demo"
},
{
"code": null,
"e": 3623,
"s": 2864,
"text": "package abc; // A package declaration\nimport java.util.*; // declaration of an import statement\n // This is a sample program to understnd basic structure of Java (Comment Section)\n public class JavaProgramStructureTest { // class name\n int repeat = 4; // global variable\n public static void main(String args[]) { // main method\n JavaProgramStructureTest test = new JavaProgramStructureTest();\n test.printMessage(\"Welcome to Tutorials Point\");\n }\n public void printMessage(String msg) { // method\n Date date = new Date(); // variable local to method\n for(int index = 0; index < repeat; index++) { // Here index - variable local to for loop\n System.out.println(msg + \"From\" + date.toGMTString());\n }\n }\n}"
},
{
"code": null,
"e": 3847,
"s": 3623,
"text": "Welcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT\nWelcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT\nWelcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT\nWelcome to Tutorials Point from 2 Jul 2019 08:35:15 GMT"
}
] |
Preview an image before it is uploaded in JavaScript | For security reasons browsers do not allow accessing the path of the image file selected via an input, i.e.JavaScript in browsers has no access to the File System. Therefore, our task is to preview the image file selected via the input before we send it to any server or anywhere else.
WE can use the createObjectURL() function of the URL class to create a url of the image selected by the input and then provide that url to the src attribute of an img tag.
The code for this will be −
<img id="preview"/>
<input type="file" accept="image/*" onchange="previewImage(event)">
<script>
const previewImage = e => {
const preview = document.getElementById('preview');
preview.src = URL.createObjectURL(e.target.files[0]);
preview.onload = () => URL.revokeObjectURL(preview.src);
};
</script>
This method will parse the file taken in by the <input /> and then it will create a string containing a base64 representation of the image.
The code for this will be −
Live Demo
<img id="preview"/>
<input type="file" accept="image/*" onchange="previewImage(event)">
<script>
const previewImage = e => {
const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = () => {
const preview = document.getElementById('preview');
preview.src = reader.result;
};
};
</script>
The output for both the methods will look like − | [
{
"code": null,
"e": 1348,
"s": 1062,
"text": "For security reasons browsers do not allow accessing the path of the image file selected via an input, i.e.JavaScript in browsers has no access to the File System. Therefore, our task is to preview the image file selected via the input before we send it to any server or anywhere else."
},
{
"code": null,
"e": 1520,
"s": 1348,
"text": "WE can use the createObjectURL() function of the URL class to create a url of the image selected by the input and then provide that url to the src attribute of an img tag."
},
{
"code": null,
"e": 1548,
"s": 1520,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1873,
"s": 1548,
"text": "<img id=\"preview\"/>\n<input type=\"file\" accept=\"image/*\" onchange=\"previewImage(event)\">\n<script>\n const previewImage = e => {\n const preview = document.getElementById('preview');\n preview.src = URL.createObjectURL(e.target.files[0]);\n preview.onload = () => URL.revokeObjectURL(preview.src);\n };\n</script>"
},
{
"code": null,
"e": 2013,
"s": 1873,
"text": "This method will parse the file taken in by the <input /> and then it will create a string containing a base64 representation of the image."
},
{
"code": null,
"e": 2041,
"s": 2013,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2052,
"s": 2041,
"text": " Live Demo"
},
{
"code": null,
"e": 2420,
"s": 2052,
"text": "<img id=\"preview\"/>\n<input type=\"file\" accept=\"image/*\" onchange=\"previewImage(event)\">\n<script>\n const previewImage = e => {\n const reader = new FileReader();\n reader.readAsDataURL(e.target.files[0]);\n reader.onload = () => {\n const preview = document.getElementById('preview');\n preview.src = reader.result;\n };\n };\n</script>"
},
{
"code": null,
"e": 2469,
"s": 2420,
"text": "The output for both the methods will look like −"
}
] |
Creating A Time Series Plot With Seaborn And Pandas - GeeksforGeeks | 11 Dec, 2020
In this article, we will learn how to create A Time Series Plot With Seaborn And Pandas. Let’s discuss some concepts :
Pandas is an open-source library that’s built on top of NumPy library. It’s a Python package that gives various data structures and operations for manipulating numerical data and statistics. It’s mainly popular for importing and analyzing data much easier. Pandas is fast and it’s high-performance & productive for users.
Seaborn is a tremendous visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to form statistical plots more attractive. It’s built on the highest of matplotlib library and also closely integrated to the info structures from pandas.
A timeplot (sometimes called a statistic graph) displays values against the clock. They’re almost like x-y graphs, but while an x-y graph can plot a spread of “x” variables (for example, height, weight, age), timeplots can only display time on the x-axis. Unlike the pie charts and bar charts, these plots don’t have categories. Timeplots are good for showing how data changes over time. For instance, this sort of chart would work well if you were sampling data randomly times.
Import packagesImport / Load / Create data.Plot the time series plot over data using lineplot (as tsplot was replaced with lineplot since Sep 2020).
Import packages
Import / Load / Create data.
Plot the time series plot over data using lineplot (as tsplot was replaced with lineplot since Sep 2020).
Here, we create a rough data for understanding the time series plot with the help of some examples. Let’s create the data :
Python3
# importing packagesimport pandas as pd # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]}) # view datasetdisplay(df)
Output:
Example 1: Simple time series plot with single column using lineplot
Python3
# importing packagesimport seaborn as snsimport pandas as pd # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]}) # create the time series plotsns.lineplot(x = "Date", y = "Col_1", data = df) plt.xticks(rotation = 25)
Output :
Example 2: (Simple time series plot with multiple columns using line plot)
Python3
# importing packagesimport seaborn as snsimport pandas as pd # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]}) # create the time series plotsns.lineplot(x = "Date", y = "Col_1", data = df)sns.lineplot(x = "Date", y = "Col_2", data = df)plt.ylabel("Col_1 and Col_2")plt.xticks(rotation = 25)
Output :
Example 3: Multiple time series plot with multiple columns
Python3
# importing packagesimport seaborn as snsimport pandas as pdimport matplotlib.pyplot as plt # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]})# create the time series subplotsfig,ax = plt.subplots( 2, 2, figsize = ( 10, 8)) sns.lineplot( x = "Date", y = "Col_1", color = 'r', data = df, ax = ax[0][0]) ax[0][0].tick_params(labelrotation = 25)sns.lineplot( x = "Date", y = "Col_2", color = 'g', data = df, ax = ax[0][1]) ax[0][1].tick_params(labelrotation = 25)sns.lineplot(x = "Date", y = "Col_3", color = 'b', data = df, ax = ax[1][0]) ax[1][0].tick_params(labelrotation = 25) sns.lineplot(x = "Date", y = "Col_4", color = 'y', data = df, ax = ax[1][1]) ax[1][1].tick_params(labelrotation = 25)fig.tight_layout(pad = 1.2)
Output :
Python-pandas
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 26762,
"s": 26734,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 26881,
"s": 26762,
"text": "In this article, we will learn how to create A Time Series Plot With Seaborn And Pandas. Let’s discuss some concepts :"
},
{
"code": null,
"e": 27203,
"s": 26881,
"text": "Pandas is an open-source library that’s built on top of NumPy library. It’s a Python package that gives various data structures and operations for manipulating numerical data and statistics. It’s mainly popular for importing and analyzing data much easier. Pandas is fast and it’s high-performance & productive for users."
},
{
"code": null,
"e": 27505,
"s": 27203,
"text": "Seaborn is a tremendous visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to form statistical plots more attractive. It’s built on the highest of matplotlib library and also closely integrated to the info structures from pandas."
},
{
"code": null,
"e": 27984,
"s": 27505,
"text": "A timeplot (sometimes called a statistic graph) displays values against the clock. They’re almost like x-y graphs, but while an x-y graph can plot a spread of “x” variables (for example, height, weight, age), timeplots can only display time on the x-axis. Unlike the pie charts and bar charts, these plots don’t have categories. Timeplots are good for showing how data changes over time. For instance, this sort of chart would work well if you were sampling data randomly times."
},
{
"code": null,
"e": 28133,
"s": 27984,
"text": "Import packagesImport / Load / Create data.Plot the time series plot over data using lineplot (as tsplot was replaced with lineplot since Sep 2020)."
},
{
"code": null,
"e": 28149,
"s": 28133,
"text": "Import packages"
},
{
"code": null,
"e": 28178,
"s": 28149,
"text": "Import / Load / Create data."
},
{
"code": null,
"e": 28284,
"s": 28178,
"text": "Plot the time series plot over data using lineplot (as tsplot was replaced with lineplot since Sep 2020)."
},
{
"code": null,
"e": 28408,
"s": 28284,
"text": "Here, we create a rough data for understanding the time series plot with the help of some examples. Let’s create the data :"
},
{
"code": null,
"e": 28416,
"s": 28408,
"text": "Python3"
},
{
"code": "# importing packagesimport pandas as pd # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]}) # view datasetdisplay(df)",
"e": 29218,
"s": 28416,
"text": null
},
{
"code": null,
"e": 29226,
"s": 29218,
"text": "Output:"
},
{
"code": null,
"e": 29295,
"s": 29226,
"text": "Example 1: Simple time series plot with single column using lineplot"
},
{
"code": null,
"e": 29303,
"s": 29295,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport pandas as pd # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]}) # create the time series plotsns.lineplot(x = \"Date\", y = \"Col_1\", data = df) plt.xticks(rotation = 25)",
"e": 30197,
"s": 29303,
"text": null
},
{
"code": null,
"e": 30206,
"s": 30197,
"text": "Output :"
},
{
"code": null,
"e": 30282,
"s": 30206,
"text": "Example 2: (Simple time series plot with multiple columns using line plot)"
},
{
"code": null,
"e": 30290,
"s": 30282,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport pandas as pd # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]}) # create the time series plotsns.lineplot(x = \"Date\", y = \"Col_1\", data = df)sns.lineplot(x = \"Date\", y = \"Col_2\", data = df)plt.ylabel(\"Col_1 and Col_2\")plt.xticks(rotation = 25)",
"e": 31247,
"s": 30290,
"text": null
},
{
"code": null,
"e": 31256,
"s": 31247,
"text": "Output :"
},
{
"code": null,
"e": 31315,
"s": 31256,
"text": "Example 3: Multiple time series plot with multiple columns"
},
{
"code": null,
"e": 31323,
"s": 31315,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport pandas as pdimport matplotlib.pyplot as plt # creating datadf = pd.DataFrame({'Date': ['2019-10-01', '2019-11-01', '2019-12-01','2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'], 'Col_1': [34, 43, 14, 15, 15, 14, 31, 25, 62], 'Col_2': [52, 66, 78, 15, 15, 5, 25, 25, 86], 'Col_3': [13, 73, 82, 58, 52, 87, 26, 5, 56], 'Col_4': [44, 75, 26, 15, 15, 14, 54, 25, 24]})# create the time series subplotsfig,ax = plt.subplots( 2, 2, figsize = ( 10, 8)) sns.lineplot( x = \"Date\", y = \"Col_1\", color = 'r', data = df, ax = ax[0][0]) ax[0][0].tick_params(labelrotation = 25)sns.lineplot( x = \"Date\", y = \"Col_2\", color = 'g', data = df, ax = ax[0][1]) ax[0][1].tick_params(labelrotation = 25)sns.lineplot(x = \"Date\", y = \"Col_3\", color = 'b', data = df, ax = ax[1][0]) ax[1][0].tick_params(labelrotation = 25) sns.lineplot(x = \"Date\", y = \"Col_4\", color = 'y', data = df, ax = ax[1][1]) ax[1][1].tick_params(labelrotation = 25)fig.tight_layout(pad = 1.2)",
"e": 32841,
"s": 31323,
"text": null
},
{
"code": null,
"e": 32850,
"s": 32841,
"text": "Output :"
},
{
"code": null,
"e": 32864,
"s": 32850,
"text": "Python-pandas"
},
{
"code": null,
"e": 32879,
"s": 32864,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 32886,
"s": 32879,
"text": "Python"
},
{
"code": null,
"e": 32984,
"s": 32886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33012,
"s": 32984,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 33062,
"s": 33012,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 33084,
"s": 33062,
"text": "Python map() function"
},
{
"code": null,
"e": 33128,
"s": 33084,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 33146,
"s": 33128,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33169,
"s": 33146,
"text": "Taking input in Python"
},
{
"code": null,
"e": 33204,
"s": 33169,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33226,
"s": 33204,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 33258,
"s": 33226,
"text": "How to Install PIP on Windows ?"
}
] |
How do I connect to a Wi-Fi network on Android programmatically using Kotlin? | This example demonstrates how to connect to a Wi-Fi network on Android programmatically using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<Switch
android:id="@+id/switchWifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/switchWifi"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:text="WiFi OFF"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold|italic" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.net.wifi.WifiManager
import android.os.Bundle
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
private lateinit var wifiButton: Switch
lateinit var textView: TextView
lateinit var wifiManager: WifiManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
wifiButton = findViewById(R.id.switchWifi)
wifiButton.setOnCheckedChangeListener { _, isChecked -> // TODO Auto-generated method stub if (isChecked) {
textView.text = "WIFI ON"
enableWiFi()
}
else {
textView.text = "WIFI OFF"
disableWiFi()
}
}
}
private fun disableWiFi() {
wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager wifiManager.isWifiEnabled = false
Toast.makeText(this, "Wifi Disabled", Toast.LENGTH_SHORT).show()
}
private fun enableWiFi() {
wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager wifiManager.isWifiEnabled = true
Toast.makeText(this, "Wifi Enabled", Toast.LENGTH_SHORT).show()
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Click here to download the project code. | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "This example demonstrates how to connect to a Wi-Fi network on Android programmatically using Kotlin."
},
{
"code": null,
"e": 1293,
"s": 1164,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1358,
"s": 1293,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2660,
"s": 1358,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/activity_main\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\"MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Switch\n android:id=\"@+id/switchWifi\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@+id/switchWifi\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginBottom=\"30dp\"\n android:text=\"WiFi OFF\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n</RelativeLayout>\n"
},
{
"code": null,
"e": 2715,
"s": 2660,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4152,
"s": 2715,
"text": "import android.content.Context\nimport android.net.wifi.WifiManager\nimport android.os.Bundle\nimport android.widget.Switch\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\n@Suppress(\"DEPRECATION\")\nclass MainActivity : AppCompatActivity() {\n private lateinit var wifiButton: Switch\n lateinit var textView: TextView\n lateinit var wifiManager: WifiManager\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n wifiButton = findViewById(R.id.switchWifi)\n wifiButton.setOnCheckedChangeListener { _, isChecked -> // TODO Auto-generated method stub if (isChecked) {\n textView.text = \"WIFI ON\"\n enableWiFi()\n }\n else {\n textView.text = \"WIFI OFF\"\n disableWiFi()\n }\n }\n }\n private fun disableWiFi() {\n wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager wifiManager.isWifiEnabled = false\n Toast.makeText(this, \"Wifi Disabled\", Toast.LENGTH_SHORT).show()\n }\n private fun enableWiFi() {\n wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager wifiManager.isWifiEnabled = true\n Toast.makeText(this, \"Wifi Enabled\", Toast.LENGTH_SHORT).show()\n }\n}"
},
{
"code": null,
"e": 4207,
"s": 4152,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5022,
"s": 4207,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" />\n<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5372,
"s": 5022,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 5413,
"s": 5372,
"text": "Click here to download the project code."
}
] |
Check if two arrays are equal or not - GeeksforGeeks | 12 Apr, 2022
Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain the same set of elements, arrangements (or permutation) of elements may be different though.
Note: If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal.
Examples :
Input : arr1[] = {1, 2, 5, 4, 0};
arr2[] = {2, 4, 5, 0, 1};
Output : Yes
Input : arr1[] = {1, 2, 5, 4, 0, 2, 1};
arr2[] = {2, 4, 5, 0, 1, 1, 2};
Output : Yes
Input : arr1[] = {1, 7, 1};
arr2[] = {7, 7, 1};
Output : No
A simple solution is to sort both arrays and then linearly compare elements.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find given two array// are equal or not#include <bits/stdc++.h>using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.bool areEqual(int arr1[], int arr2[], int n, int m){ // If lengths of array are not equal means // array are not equal if (n != m) return false; // Sort both arrays sort(arr1, arr1 + n); sort(arr2, arr2 + m); // Linearly compare elements for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true;} // Driver Codeint main(){ int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); if (areEqual(arr1, arr2, n, m)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to find given two array// are equal or notimport java.io.*;import java.util.*; class GFG { // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. public static boolean areEqual(int arr1[], int arr2[]) { int n = arr1.length; int m = arr2.length; // If lengths of array are not equal means // array are not equal if (n != m) return false; // Sort both arrays Arrays.sort(arr1); Arrays.sort(arr2); // Linearly compare elements for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver code public static void main(String[] args) { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) System.out.println("Yes"); else System.out.println("No"); }}
# Python3 program to find given# two array are equal or not # Returns true if arr1[0..n-1] and# arr2[0..m-1] contain same elements. def areEqual(arr1, arr2, n, m): # If lengths of array are not # equal means array are not equal if (n != m): return False # Sort both arrays arr1.sort() arr2.sort() # Linearly compare elements for i in range(0, n): if (arr1[i] != arr2[i]): return False # If all elements were same. return True # Driver Codearr1 = [3, 5, 2, 5, 2]arr2 = [2, 3, 5, 5, 2]n = len(arr1)m = len(arr2) if (areEqual(arr1, arr2, n, m)): print("Yes")else: print("No") # This code is contributed# by Shivi_Aggarwal.
// C# program to find given two array// are equal or notusing System; class GFG { // Returns true if arr1[0..n-1] and // arr2[0..m-1] contain same elements. public static bool areEqual(int[] arr1, int[] arr2) { int n = arr1.Length; int m = arr2.Length; // If lengths of array are not // equal means array are not equal if (n != m) return false; // Sort both arrays Array.Sort(arr1); Array.Sort(arr2); // Linearly compare elements for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver code public static void Main() { int[] arr1 = { 3, 5, 2, 5, 2 }; int[] arr2 = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by anuj_67.
<?php// PHP program to find given// two array are equal or not // Returns true if arr1[0..n-1]// and arr2[0..m-1] contain same elements.function areEqual( $arr1, $arr2, $n, $m){ // If lengths of array // are not equal means // array are not equal if ($n != $m) return false; // Sort both arrays sort($arr1); sort($arr2); // Linearly compare elements for ( $i = 0; $i < $n; $i++) if ($arr1[$i] != $arr2[$i]) return false; // If all elements were same. return true;} // Driver Code$arr1 = array( 3, 5, 2, 5, 2);$arr2 = array( 2, 3, 5, 5, 2);$n = count($arr1);$m = count($arr2); if (areEqual($arr1, $arr2, $n, $m)) echo "Yes";else echo "No"; // This code is contributed by anuj_67.?>
<script> // JavaScript program for the above approach // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. function areEqual(arr1, arr2) { let n = arr1.length; let m = arr2.length; // If lengths of array are not equal means // array are not equal if (n != m) return false; // Sort both arrays arr1.sort(); arr2.sort(); // Linearly compare elements for (let i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver Code let arr1 = [ 3, 5, 2, 5, 2 ]; let arr2 = [ 2, 3, 5, 5, 2 ]; if (areEqual(arr1, arr2)) document.write("Yes"); else document.write("No"); // This code is contributed by chinmoy1997pal.</script>
Yes
Time Complexity: O(n log n) Auxiliary Space: O(1)
An Efficient Solution to this approach is to use hashing. We store all elements of arr1[] and their counts in a hash table. Then we traverse arr2[] and check if the count of every element in arr2[] matches with the count in arr1[].
Below is the implementation of the above idea. We use unordered_map to store counts.
C++
Java
Python3
C#
Javascript
// C++ program to find given two array// are equal or not using hashing technique#include <bits/stdc++.h>using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.bool areEqual(int arr1[], int arr2[], int n, int m){ // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr1[i]]++; // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (mp.find(arr2[i]) == mp.end()) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (mp[arr2[i]] == 0) return false; mp[arr2[i]]--; } return true;} // Driver Codeint main(){ int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); if (areEqual(arr1, arr2, n, m)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to find given two array// are equal or not using hashing techniqueimport java.util.*;import java.io.*; class GFG { // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. public static boolean areEqual(int arr1[], int arr2[]) { int n = arr1.length; int m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int count = 0; for (int i = 0; i < n; i++) { if (map.get(arr1[i]) == null) map.put(arr1[i], 1); else { count = map.get(arr1[i]); count++; map.put(arr1[i], count); } } // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (!map.containsKey(arr2[i])) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (map.get(arr2[i]) == 0) return false; count = map.get(arr2[i]); --count; map.put(arr2[i], count); } return true; } // Driver code public static void main(String[] args) { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) System.out.println("Yes"); else System.out.println("No"); }}
# Python3 program to find if given# two arrays are equal or not# using dictionaryfrom collections import defaultdict # Returns true if arr1[0..n-1] and# arr2[0..m-1] contain same elements. def areEqual(arr1, arr2, n, m): # If lengths of array are not # equal means array are not equal if (n != m): return False # Create a defaultdict count to # store counts count = defaultdict(int) # Store the elements of arr1 # and their counts in the dictionary for i in arr1: count[i] += 1 # Traverse through arr2 and compare # the elements and its count with # the elements of arr1 for i in arr2: # Return false if the element # is not in arr2 or if any element # appears more no. of times than in arr1 if (count[i] == 0): return False # If element is found, decrement # its value in the dictionary else: count[i] -= 1 # Return true if both arr1 and # arr2 are equal return True # Driver Codearr1 = [3, 5, 2, 5, 2]arr2 = [2, 3, 5, 5, 2] n = len(arr1)m = len(arr2) if areEqual(arr1, arr2, n, m): print("Yes")else: print("No") # This code is contributed by Karthik_Aravind
// C# program to find given two array// are equal or not using hashing techniqueusing System;using System.Collections.Generic; class GFG { // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. public static bool areEqual(int[] arr1, int[] arr2) { int n = arr1.Length; int m = arr2.Length; // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map Dictionary<int, int> map = new Dictionary<int, int>(); int count = 0; for (int i = 0; i < n; i++) { if (!map.ContainsKey(arr1[i])) map.Add(arr1[i], 1); else { count = map[arr1[i]]; count++; map.Remove(arr1[i]); map.Add(arr1[i], count); } } // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (!map.ContainsKey(arr2[i])) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (map[arr2[i]] == 0) return false; count = map[arr2[i]]; --count; if (!map.ContainsKey(arr2[i])) map.Add(arr2[i], count); } return true; } // Driver code public static void Main(String[] args) { int[] arr1 = { 3, 5, 2, 5, 2 }; int[] arr2 = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program to find given two array// are equal or not using hashing technique // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. function areEqual(arr1, arr2) { let n = arr1.length; let m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map let map = new Map(); let count = 0; for (let i = 0; i < n; i++) { if (map.get(arr1[i]) == null) map.set(arr1[i], 1); else { count = map.get(arr1[i]); count++; map.set(arr1[i], count); } } // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (let i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (!map.has(arr2[i])) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (map.get(arr2[i]) == 0) return false; count = map.get(arr2[i]); --count; map.set(arr2[i], count); } return true; } // Driver code let arr1 = [ 3, 5, 2, 5, 2 ]; let arr2 = [ 2, 3, 5, 5, 2 ]; if (areEqual(arr1, arr2)) document.write("Yes"); else document.write("No"); </script>
Yes
Time Complexity: O(n) Auxiliary Space: O(n)
An Alternate Solution without comparing each element of the arrays and without using unordered_map (by using XOR). This approach will work only if each element exist only once in an array. For example : array a : { 3 , 3 } and array b : { 5 , 5 }, xor_of_array_a(say b1) = 0 and xor_of_array_b = 0 (say b2) and b1^b2 = 0, but array a and array b are not equal.
C++14
Java
Python3
Javascript
// C++ program to find given two array// are equal or not#include <bits/stdc++.h>using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.bool areEqual(int arr1[], int arr2[], int n, int m){ // If lengths of array are not equal means // array are not equal if (n != m) return false; // to store xor of both arrays int b1 = arr1[0]; int b2 = arr2[0]; // find xor of each elements in array for (int i = 1; i < n; i++) { b1 ^= arr1[i]; } for (int i = 1; i < m; i++) { b2 ^= arr2[i]; } int all_xor = b1 ^ b2; // if xor is zero means they are equal (5^5=0) if (all_xor == 0) return true; // If all elements were not same, then xor will not be // zero return false;} // Driver Codeint main(){ int arr1[] = { 3, 6, 7, 5, 2 }; int arr2[] = { 2, 3, 5, 6, 7 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); // Function call if (areEqual(arr1, arr2, n, m)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to find given two array// are equal or notimport java.io.*;import java.util.*; class GFG{ // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.public static boolean areEqual(int arr1[], int arr2[]){ // Length of the two array int n = arr1.length; int m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // To store xor of both arrays int b1 = arr1[0]; int b2 = arr2[0]; // Find xor of each elements in array for(int i = 1; i < n; i++) { b1 ^= arr1[i]; } for(int i = 1; i < m; i++) { b2 ^= arr2[i]; } int all_xor = b1 ^ b2; // If xor is zero means they are // equal (5^5=0) if (all_xor == 0) return true; // If all elements were not same, // then xor will not be zero return false;} // Driver codepublic static void main(String[] args){ int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; // Function call if (areEqual(arr1, arr2)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by sayantanbose2001
# Python3 program to find given# two array are equal or not # Returns true if arr1[0..n-1] and# arr2[0..m-1] contain same elements. def areEqual(arr1, arr2, n, m): # If lengths of array are not # equal means array are not equal if (n != m): return False b1 = arr1[0] b2 = arr2[0] # find xor of all elements for i in range(1, n - 1): b1 ^= arr1[i] for i in range(1, m - 1): b2 ^= arr2[i] all_xor = b1 ^ b2 # If all elements were same then xor will be zero if(all_xor == 0): return True return False # Driver Codearr1 = [3, 5, 2, 5, 2]arr2 = [2, 3, 5, 5, 2]n = len(arr1)m = len(arr2) # Function callif (areEqual(arr1, arr2, n, m)): print("Yes")else: print("No")
<script>// Java Script program to find given two array// are equal or not // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.function areEqual(arr1,arr2){ // Length of the two array let n = arr1.length; let m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // To store xor of both arrays let b1 = arr1[0]; let b2 = arr2[0]; // Find xor of each elements in array for(let i = 1; i < n; i++) { b1 ^= arr1[i]; } for(let i = 1; i < m; i++) { b2 ^= arr2[i]; } let all_xor = b1 ^ b2; // If xor is zero means they are // equal (5^5=0) if (all_xor == 0) return true; // If all elements were not same, // then xor will not be zero return false;} // Driver code let arr1 = [ 3, 5, 2, 5, 2 ]; let arr2 = [ 2, 3, 5, 5, 2 ]; // Function call if (areEqual(arr1, arr2)) document.write("Yes"); else document.write("No"); //contributed by sravan kumar Gottumukkala</script>
Yes
Time Complexity: O(n) Auxiliary Space: O(1)
This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Improved By: vt_m, Shivi_Aggarwal, imrohan, princiraj1992, karthikaravindt88, anupriyanishad
vt_m
Shivi_Aggarwal
imrohan
princiraj1992
karthikaravindt88
anupriyanishad
sayantanbose2001
vaiibhav
chinmoy1997pal
sravankumar8128
avijitmondal1998
anikaseth98
devadarsh7
Goldman Sachs
Arrays
Hash
Sorting
Goldman Sachs
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining) | [
{
"code": null,
"e": 24478,
"s": 24450,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 24721,
"s": 24478,
"text": "Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain the same set of elements, arrangements (or permutation) of elements may be different though."
},
{
"code": null,
"e": 24837,
"s": 24721,
"text": "Note: If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal. "
},
{
"code": null,
"e": 24849,
"s": 24837,
"text": "Examples : "
},
{
"code": null,
"e": 25100,
"s": 24849,
"text": "Input : arr1[] = {1, 2, 5, 4, 0};\n arr2[] = {2, 4, 5, 0, 1}; \nOutput : Yes\n\nInput : arr1[] = {1, 2, 5, 4, 0, 2, 1};\n arr2[] = {2, 4, 5, 0, 1, 1, 2}; \nOutput : Yes\n \nInput : arr1[] = {1, 7, 1};\n arr2[] = {7, 7, 1};\nOutput : No"
},
{
"code": null,
"e": 25178,
"s": 25100,
"text": "A simple solution is to sort both arrays and then linearly compare elements. "
},
{
"code": null,
"e": 25182,
"s": 25178,
"text": "C++"
},
{
"code": null,
"e": 25187,
"s": 25182,
"text": "Java"
},
{
"code": null,
"e": 25195,
"s": 25187,
"text": "Python3"
},
{
"code": null,
"e": 25198,
"s": 25195,
"text": "C#"
},
{
"code": null,
"e": 25202,
"s": 25198,
"text": "PHP"
},
{
"code": null,
"e": 25213,
"s": 25202,
"text": "Javascript"
},
{
"code": "// C++ program to find given two array// are equal or not#include <bits/stdc++.h>using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.bool areEqual(int arr1[], int arr2[], int n, int m){ // If lengths of array are not equal means // array are not equal if (n != m) return false; // Sort both arrays sort(arr1, arr1 + n); sort(arr2, arr2 + m); // Linearly compare elements for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true;} // Driver Codeint main(){ int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); if (areEqual(arr1, arr2, n, m)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26069,
"s": 25213,
"text": null
},
{
"code": "// Java program to find given two array// are equal or notimport java.io.*;import java.util.*; class GFG { // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. public static boolean areEqual(int arr1[], int arr2[]) { int n = arr1.length; int m = arr2.length; // If lengths of array are not equal means // array are not equal if (n != m) return false; // Sort both arrays Arrays.sort(arr1); Arrays.sort(arr2); // Linearly compare elements for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver code public static void main(String[] args) { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 27051,
"s": 26069,
"text": null
},
{
"code": "# Python3 program to find given# two array are equal or not # Returns true if arr1[0..n-1] and# arr2[0..m-1] contain same elements. def areEqual(arr1, arr2, n, m): # If lengths of array are not # equal means array are not equal if (n != m): return False # Sort both arrays arr1.sort() arr2.sort() # Linearly compare elements for i in range(0, n): if (arr1[i] != arr2[i]): return False # If all elements were same. return True # Driver Codearr1 = [3, 5, 2, 5, 2]arr2 = [2, 3, 5, 5, 2]n = len(arr1)m = len(arr2) if (areEqual(arr1, arr2, n, m)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Shivi_Aggarwal.",
"e": 27738,
"s": 27051,
"text": null
},
{
"code": "// C# program to find given two array// are equal or notusing System; class GFG { // Returns true if arr1[0..n-1] and // arr2[0..m-1] contain same elements. public static bool areEqual(int[] arr1, int[] arr2) { int n = arr1.Length; int m = arr2.Length; // If lengths of array are not // equal means array are not equal if (n != m) return false; // Sort both arrays Array.Sort(arr1); Array.Sort(arr2); // Linearly compare elements for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver code public static void Main() { int[] arr1 = { 3, 5, 2, 5, 2 }; int[] arr2 = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by anuj_67.",
"e": 28716,
"s": 27738,
"text": null
},
{
"code": "<?php// PHP program to find given// two array are equal or not // Returns true if arr1[0..n-1]// and arr2[0..m-1] contain same elements.function areEqual( $arr1, $arr2, $n, $m){ // If lengths of array // are not equal means // array are not equal if ($n != $m) return false; // Sort both arrays sort($arr1); sort($arr2); // Linearly compare elements for ( $i = 0; $i < $n; $i++) if ($arr1[$i] != $arr2[$i]) return false; // If all elements were same. return true;} // Driver Code$arr1 = array( 3, 5, 2, 5, 2);$arr2 = array( 2, 3, 5, 5, 2);$n = count($arr1);$m = count($arr2); if (areEqual($arr1, $arr2, $n, $m)) echo \"Yes\";else echo \"No\"; // This code is contributed by anuj_67.?>",
"e": 29464,
"s": 28716,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. function areEqual(arr1, arr2) { let n = arr1.length; let m = arr2.length; // If lengths of array are not equal means // array are not equal if (n != m) return false; // Sort both arrays arr1.sort(); arr2.sort(); // Linearly compare elements for (let i = 0; i < n; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver Code let arr1 = [ 3, 5, 2, 5, 2 ]; let arr2 = [ 2, 3, 5, 5, 2 ]; if (areEqual(arr1, arr2)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by chinmoy1997pal.</script>",
"e": 30320,
"s": 29464,
"text": null
},
{
"code": null,
"e": 30324,
"s": 30320,
"text": "Yes"
},
{
"code": null,
"e": 30374,
"s": 30324,
"text": "Time Complexity: O(n log n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30606,
"s": 30374,
"text": "An Efficient Solution to this approach is to use hashing. We store all elements of arr1[] and their counts in a hash table. Then we traverse arr2[] and check if the count of every element in arr2[] matches with the count in arr1[]."
},
{
"code": null,
"e": 30692,
"s": 30606,
"text": "Below is the implementation of the above idea. We use unordered_map to store counts. "
},
{
"code": null,
"e": 30696,
"s": 30692,
"text": "C++"
},
{
"code": null,
"e": 30701,
"s": 30696,
"text": "Java"
},
{
"code": null,
"e": 30709,
"s": 30701,
"text": "Python3"
},
{
"code": null,
"e": 30712,
"s": 30709,
"text": "C#"
},
{
"code": null,
"e": 30723,
"s": 30712,
"text": "Javascript"
},
{
"code": "// C++ program to find given two array// are equal or not using hashing technique#include <bits/stdc++.h>using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.bool areEqual(int arr1[], int arr2[], int n, int m){ // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr1[i]]++; // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (mp.find(arr2[i]) == mp.end()) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (mp[arr2[i]] == 0) return false; mp[arr2[i]]--; } return true;} // Driver Codeint main(){ int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); if (areEqual(arr1, arr2, n, m)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 31957,
"s": 30723,
"text": null
},
{
"code": "// Java program to find given two array// are equal or not using hashing techniqueimport java.util.*;import java.io.*; class GFG { // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. public static boolean areEqual(int arr1[], int arr2[]) { int n = arr1.length; int m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int count = 0; for (int i = 0; i < n; i++) { if (map.get(arr1[i]) == null) map.put(arr1[i], 1); else { count = map.get(arr1[i]); count++; map.put(arr1[i], count); } } // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (!map.containsKey(arr2[i])) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (map.get(arr2[i]) == 0) return false; count = map.get(arr2[i]); --count; map.put(arr2[i], count); } return true; } // Driver code public static void main(String[] args) { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 33696,
"s": 31957,
"text": null
},
{
"code": "# Python3 program to find if given# two arrays are equal or not# using dictionaryfrom collections import defaultdict # Returns true if arr1[0..n-1] and# arr2[0..m-1] contain same elements. def areEqual(arr1, arr2, n, m): # If lengths of array are not # equal means array are not equal if (n != m): return False # Create a defaultdict count to # store counts count = defaultdict(int) # Store the elements of arr1 # and their counts in the dictionary for i in arr1: count[i] += 1 # Traverse through arr2 and compare # the elements and its count with # the elements of arr1 for i in arr2: # Return false if the element # is not in arr2 or if any element # appears more no. of times than in arr1 if (count[i] == 0): return False # If element is found, decrement # its value in the dictionary else: count[i] -= 1 # Return true if both arr1 and # arr2 are equal return True # Driver Codearr1 = [3, 5, 2, 5, 2]arr2 = [2, 3, 5, 5, 2] n = len(arr1)m = len(arr2) if areEqual(arr1, arr2, n, m): print(\"Yes\")else: print(\"No\") # This code is contributed by Karthik_Aravind",
"e": 34904,
"s": 33696,
"text": null
},
{
"code": "// C# program to find given two array// are equal or not using hashing techniqueusing System;using System.Collections.Generic; class GFG { // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. public static bool areEqual(int[] arr1, int[] arr2) { int n = arr1.Length; int m = arr2.Length; // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map Dictionary<int, int> map = new Dictionary<int, int>(); int count = 0; for (int i = 0; i < n; i++) { if (!map.ContainsKey(arr1[i])) map.Add(arr1[i], 1); else { count = map[arr1[i]]; count++; map.Remove(arr1[i]); map.Add(arr1[i], count); } } // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (!map.ContainsKey(arr2[i])) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (map[arr2[i]] == 0) return false; count = map[arr2[i]]; --count; if (!map.ContainsKey(arr2[i])) map.Add(arr2[i], count); } return true; } // Driver code public static void Main(String[] args) { int[] arr1 = { 3, 5, 2, 5, 2 }; int[] arr2 = { 2, 3, 5, 5, 2 }; if (areEqual(arr1, arr2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} /* This code contributed by PrinciRaj1992 */",
"e": 36756,
"s": 34904,
"text": null
},
{
"code": "<script> // Javascript program to find given two array// are equal or not using hashing technique // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. function areEqual(arr1, arr2) { let n = arr1.length; let m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // Store arr1[] elements and their counts in // hash map let map = new Map(); let count = 0; for (let i = 0; i < n; i++) { if (map.get(arr1[i]) == null) map.set(arr1[i], 1); else { count = map.get(arr1[i]); count++; map.set(arr1[i], count); } } // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (let i = 0; i < n; i++) { // If there is an element in arr2[], but // not in arr1[] if (!map.has(arr2[i])) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (map.get(arr2[i]) == 0) return false; count = map.get(arr2[i]); --count; map.set(arr2[i], count); } return true; } // Driver code let arr1 = [ 3, 5, 2, 5, 2 ]; let arr2 = [ 2, 3, 5, 5, 2 ]; if (areEqual(arr1, arr2)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 38348,
"s": 36756,
"text": null
},
{
"code": null,
"e": 38352,
"s": 38348,
"text": "Yes"
},
{
"code": null,
"e": 38396,
"s": 38352,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 38761,
"s": 38396,
"text": "An Alternate Solution without comparing each element of the arrays and without using unordered_map (by using XOR). This approach will work only if each element exist only once in an array. For example : array a : { 3 , 3 } and array b : { 5 , 5 }, xor_of_array_a(say b1) = 0 and xor_of_array_b = 0 (say b2) and b1^b2 = 0, but array a and array b are not equal."
},
{
"code": null,
"e": 38767,
"s": 38761,
"text": "C++14"
},
{
"code": null,
"e": 38772,
"s": 38767,
"text": "Java"
},
{
"code": null,
"e": 38780,
"s": 38772,
"text": "Python3"
},
{
"code": null,
"e": 38791,
"s": 38780,
"text": "Javascript"
},
{
"code": "// C++ program to find given two array// are equal or not#include <bits/stdc++.h>using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.bool areEqual(int arr1[], int arr2[], int n, int m){ // If lengths of array are not equal means // array are not equal if (n != m) return false; // to store xor of both arrays int b1 = arr1[0]; int b2 = arr2[0]; // find xor of each elements in array for (int i = 1; i < n; i++) { b1 ^= arr1[i]; } for (int i = 1; i < m; i++) { b2 ^= arr2[i]; } int all_xor = b1 ^ b2; // if xor is zero means they are equal (5^5=0) if (all_xor == 0) return true; // If all elements were not same, then xor will not be // zero return false;} // Driver Codeint main(){ int arr1[] = { 3, 6, 7, 5, 2 }; int arr2[] = { 2, 3, 5, 6, 7 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); // Function call if (areEqual(arr1, arr2, n, m)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 39884,
"s": 38791,
"text": null
},
{
"code": "// Java program to find given two array// are equal or notimport java.io.*;import java.util.*; class GFG{ // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.public static boolean areEqual(int arr1[], int arr2[]){ // Length of the two array int n = arr1.length; int m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // To store xor of both arrays int b1 = arr1[0]; int b2 = arr2[0]; // Find xor of each elements in array for(int i = 1; i < n; i++) { b1 ^= arr1[i]; } for(int i = 1; i < m; i++) { b2 ^= arr2[i]; } int all_xor = b1 ^ b2; // If xor is zero means they are // equal (5^5=0) if (all_xor == 0) return true; // If all elements were not same, // then xor will not be zero return false;} // Driver codepublic static void main(String[] args){ int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; // Function call if (areEqual(arr1, arr2)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by sayantanbose2001",
"e": 41100,
"s": 39884,
"text": null
},
{
"code": "# Python3 program to find given# two array are equal or not # Returns true if arr1[0..n-1] and# arr2[0..m-1] contain same elements. def areEqual(arr1, arr2, n, m): # If lengths of array are not # equal means array are not equal if (n != m): return False b1 = arr1[0] b2 = arr2[0] # find xor of all elements for i in range(1, n - 1): b1 ^= arr1[i] for i in range(1, m - 1): b2 ^= arr2[i] all_xor = b1 ^ b2 # If all elements were same then xor will be zero if(all_xor == 0): return True return False # Driver Codearr1 = [3, 5, 2, 5, 2]arr2 = [2, 3, 5, 5, 2]n = len(arr1)m = len(arr2) # Function callif (areEqual(arr1, arr2, n, m)): print(\"Yes\")else: print(\"No\")",
"e": 41845,
"s": 41100,
"text": null
},
{
"code": "<script>// Java Script program to find given two array// are equal or not // Returns true if arr1[0..n-1] and arr2[0..m-1]// contain same elements.function areEqual(arr1,arr2){ // Length of the two array let n = arr1.length; let m = arr2.length; // If lengths of arrays are not equal if (n != m) return false; // To store xor of both arrays let b1 = arr1[0]; let b2 = arr2[0]; // Find xor of each elements in array for(let i = 1; i < n; i++) { b1 ^= arr1[i]; } for(let i = 1; i < m; i++) { b2 ^= arr2[i]; } let all_xor = b1 ^ b2; // If xor is zero means they are // equal (5^5=0) if (all_xor == 0) return true; // If all elements were not same, // then xor will not be zero return false;} // Driver code let arr1 = [ 3, 5, 2, 5, 2 ]; let arr2 = [ 2, 3, 5, 5, 2 ]; // Function call if (areEqual(arr1, arr2)) document.write(\"Yes\"); else document.write(\"No\"); //contributed by sravan kumar Gottumukkala</script>",
"e": 42926,
"s": 41845,
"text": null
},
{
"code": null,
"e": 42930,
"s": 42926,
"text": "Yes"
},
{
"code": null,
"e": 42974,
"s": 42930,
"text": "Time Complexity: O(n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 43393,
"s": 42974,
"text": "This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 43486,
"s": 43393,
"text": "Improved By: vt_m, Shivi_Aggarwal, imrohan, princiraj1992, karthikaravindt88, anupriyanishad"
},
{
"code": null,
"e": 43491,
"s": 43486,
"text": "vt_m"
},
{
"code": null,
"e": 43506,
"s": 43491,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 43514,
"s": 43506,
"text": "imrohan"
},
{
"code": null,
"e": 43528,
"s": 43514,
"text": "princiraj1992"
},
{
"code": null,
"e": 43546,
"s": 43528,
"text": "karthikaravindt88"
},
{
"code": null,
"e": 43561,
"s": 43546,
"text": "anupriyanishad"
},
{
"code": null,
"e": 43578,
"s": 43561,
"text": "sayantanbose2001"
},
{
"code": null,
"e": 43587,
"s": 43578,
"text": "vaiibhav"
},
{
"code": null,
"e": 43602,
"s": 43587,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 43618,
"s": 43602,
"text": "sravankumar8128"
},
{
"code": null,
"e": 43635,
"s": 43618,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 43647,
"s": 43635,
"text": "anikaseth98"
},
{
"code": null,
"e": 43658,
"s": 43647,
"text": "devadarsh7"
},
{
"code": null,
"e": 43672,
"s": 43658,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 43679,
"s": 43672,
"text": "Arrays"
},
{
"code": null,
"e": 43684,
"s": 43679,
"text": "Hash"
},
{
"code": null,
"e": 43692,
"s": 43684,
"text": "Sorting"
},
{
"code": null,
"e": 43706,
"s": 43692,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 43713,
"s": 43706,
"text": "Arrays"
},
{
"code": null,
"e": 43718,
"s": 43713,
"text": "Hash"
},
{
"code": null,
"e": 43726,
"s": 43718,
"text": "Sorting"
},
{
"code": null,
"e": 43824,
"s": 43726,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43872,
"s": 43824,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 43916,
"s": 43872,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 43948,
"s": 43916,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 43971,
"s": 43948,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 43985,
"s": 43971,
"text": "Linear Search"
},
{
"code": null,
"e": 44070,
"s": 43985,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 44101,
"s": 44070,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 44135,
"s": 44101,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 44162,
"s": 44135,
"text": "Count pairs with given sum"
}
] |
Gson - Serializing Inner Classes | In this chapter, we will explain serialization/deserialization of classes having inner classes.
Student student = new Student();
student.setRollNo(1);
Student.Name name = student.new Name();
name.firstName = "Mahesh";
name.lastName = "Kumar";
student.setName(name);
//serialize inner class object
String nameString = gson.toJson(name);
System.out.println(nameString);
//deserialize inner class object
name = gson.fromJson(nameString,Student.Name.class);
System.out.println(name.getClass());
Let's see an example of serialization/de-serialization of class with an inner class in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
File − GsonTester.java
import com.google.gson.Gson;
public class GsonTester {
public static void main(String args[]) {
Student student = new Student();
student.setRollNo(1);
Student.Name name = student.new Name();
name.firstName = "Mahesh";
name.lastName = "Kumar";
student.setName(name);
Gson gson = new Gson();
String jsonString = gson.toJson(student);
System.out.println(jsonString);
student = gson.fromJson(jsonString, Student.class);
System.out.println("Roll No: "+ student.getRollNo());
System.out.println("First Name: "+ student.getName().firstName);
System.out.println("Last Name: "+ student.getName().lastName);
String nameString = gson.toJson(name);
System.out.println(nameString);
name = gson.fromJson(nameString,Student.Name.class);
System.out.println(name.getClass());
System.out.println("First Name: "+ name.firstName);
System.out.println("Last Name: "+ name.lastName);
}
}
class Student {
private int rollNo;
private Name name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
class Name {
public String firstName;
public String lastName;
}
}
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java
Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester
Verify the output.
{"rollNo":1,"name":{"firstName":"Mahesh","lastName":"Kumar"}}
Roll No: 1
First Name: Mahesh
Last Name: Kumar
{"firstName":"Mahesh","lastName":"Kumar"}
class Student$Name
First Name: Mahesh
Last Name: Kumar
Student student = new Student();
student.setRollNo(1);
Student.Name name = new Student.Name();
name.firstName = "Mahesh";
name.lastName = "Kumar";
student.setName(name);
//serialize static inner class object
String nameString = gson.toJson(name);
System.out.println(nameString);
//deserialize static inner class object
name = gson.fromJson(nameString,Student.Name.class);
System.out.println(name.getClass());
Let's see an example of serialization/de-serialization of class with a static inner class in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
File − GsonTester.java
import com.google.gson.Gson;
public class GsonTester {
public static void main(String args[]) {
Student student = new Student();
student.setRollNo(1);
Student.Name name = new Student.Name();
name.firstName = "Mahesh";
name.lastName = "Kumar";
student.setName(name);
Gson gson = new Gson();
String jsonString = gson.toJson(student);
System.out.println(jsonString);
student = gson.fromJson(jsonString, Student.class);
System.out.println("Roll No: "+ student.getRollNo());
System.out.println("First Name: "+ student.getName().firstName);
System.out.println("Last Name: "+ student.getName().lastName);
String nameString = gson.toJson(name);
System.out.println(nameString);
name = gson.fromJson(nameString,Student.Name.class);
System.out.println(name.getClass());
System.out.println("First Name: "+ name.firstName);
System.out.println("Last Name: "+ name.lastName);
}
}
class Student {
private int rollNo;
private Name name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
static class Name {
public String firstName;
public String lastName;
}
}
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java
Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester
Verify the output.
{"rollNo":1,"name":{"firstName":"Mahesh","lastName":"Kumar"}}
Roll No: 1
First Name: Mahesh
Last Name: Kumar
{"firstName":"Mahesh","lastName":"Kumar"}
class Student$Name
First Name: Mahesh
Last Name: Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2028,
"s": 1932,
"text": "In this chapter, we will explain serialization/deserialization of classes having inner classes."
},
{
"code": null,
"e": 2440,
"s": 2028,
"text": "Student student = new Student(); \nstudent.setRollNo(1); \nStudent.Name name = student.new Name(); \nname.firstName = \"Mahesh\"; \nname.lastName = \"Kumar\"; \n\nstudent.setName(name); \n//serialize inner class object \nString nameString = gson.toJson(name); \nSystem.out.println(nameString); \n\n//deserialize inner class object \nname = gson.fromJson(nameString,Student.Name.class); \nSystem.out.println(name.getClass()); \n"
},
{
"code": null,
"e": 2600,
"s": 2440,
"text": "Let's see an example of serialization/de-serialization of class with an inner class in action. Create a Java class file named GsonTester in C:\\>GSON_WORKSPACE."
},
{
"code": null,
"e": 2623,
"s": 2600,
"text": "File − GsonTester.java"
},
{
"code": null,
"e": 4112,
"s": 2623,
"text": "import com.google.gson.Gson; \n\npublic class GsonTester { \n public static void main(String args[]) { \n \n Student student = new Student(); \n student.setRollNo(1); \n Student.Name name = student.new Name(); \n \n name.firstName = \"Mahesh\"; \n name.lastName = \"Kumar\"; \n student.setName(name); \n Gson gson = new Gson(); \n \n String jsonString = gson.toJson(student); \n System.out.println(jsonString); \n student = gson.fromJson(jsonString, Student.class); \n \n System.out.println(\"Roll No: \"+ student.getRollNo()); \n System.out.println(\"First Name: \"+ student.getName().firstName); \n System.out.println(\"Last Name: \"+ student.getName().lastName); \n \n String nameString = gson.toJson(name); \n System.out.println(nameString); \n \n name = gson.fromJson(nameString,Student.Name.class); \n System.out.println(name.getClass()); \n System.out.println(\"First Name: \"+ name.firstName); \n System.out.println(\"Last Name: \"+ name.lastName); \n } \n} \n\nclass Student { \n private int rollNo; \n private Name name; \n \n public int getRollNo() { \n return rollNo; \n }\n \n public void setRollNo(int rollNo) { \n this.rollNo = rollNo; \n } \n \n public Name getName() { \n return name; \n } \n \n public void setName(Name name) { \n this.name = name; \n }\n \n class Name { \n public String firstName; \n public String lastName; \n } \n} "
},
{
"code": null,
"e": 4166,
"s": 4112,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 4207,
"s": 4166,
"text": "C:\\GSON_WORKSPACE>javac GsonTester.java\n"
},
{
"code": null,
"e": 4250,
"s": 4207,
"text": "Now run the GsonTester to see the result −"
},
{
"code": null,
"e": 4285,
"s": 4250,
"text": "C:\\GSON_WORKSPACE>java GsonTester\n"
},
{
"code": null,
"e": 4304,
"s": 4285,
"text": "Verify the output."
},
{
"code": null,
"e": 4519,
"s": 4304,
"text": "{\"rollNo\":1,\"name\":{\"firstName\":\"Mahesh\",\"lastName\":\"Kumar\"}} \nRoll No: 1 \nFirst Name: Mahesh \nLast Name: Kumar \n\n{\"firstName\":\"Mahesh\",\"lastName\":\"Kumar\"} \nclass Student$Name \nFirst Name: Mahesh \nLast Name: Kumar\n"
},
{
"code": null,
"e": 4945,
"s": 4519,
"text": "Student student = new Student(); \nstudent.setRollNo(1); \nStudent.Name name = new Student.Name(); \n\nname.firstName = \"Mahesh\"; \nname.lastName = \"Kumar\"; \nstudent.setName(name); \n\n//serialize static inner class object \nString nameString = gson.toJson(name); \nSystem.out.println(nameString); \n\n//deserialize static inner class object \nname = gson.fromJson(nameString,Student.Name.class); \nSystem.out.println(name.getClass()); "
},
{
"code": null,
"e": 5111,
"s": 4945,
"text": "Let's see an example of serialization/de-serialization of class with a static inner class in action. Create a Java class file named GsonTester in C:\\>GSON_WORKSPACE."
},
{
"code": null,
"e": 5134,
"s": 5111,
"text": "File − GsonTester.java"
},
{
"code": null,
"e": 6628,
"s": 5134,
"text": "import com.google.gson.Gson; \n\npublic class GsonTester { \n public static void main(String args[]) { \n \n Student student = new Student(); \n student.setRollNo(1); \n Student.Name name = new Student.Name(); \n \n name.firstName = \"Mahesh\"; \n name.lastName = \"Kumar\"; \n student.setName(name); \n \n Gson gson = new Gson(); \n String jsonString = gson.toJson(student); \n System.out.println(jsonString); \n student = gson.fromJson(jsonString, Student.class); \n \n System.out.println(\"Roll No: \"+ student.getRollNo()); \n System.out.println(\"First Name: \"+ student.getName().firstName); \n System.out.println(\"Last Name: \"+ student.getName().lastName); \n String nameString = gson.toJson(name); \n System.out.println(nameString); \n \n name = gson.fromJson(nameString,Student.Name.class); \n System.out.println(name.getClass()); \n System.out.println(\"First Name: \"+ name.firstName); \n System.out.println(\"Last Name: \"+ name.lastName); \n } \n} \n\nclass Student { \n private int rollNo; \n private Name name; \n \n public int getRollNo() { \n return rollNo; \n } \n \n public void setRollNo(int rollNo) { \n this.rollNo = rollNo; \n } \n \n public Name getName() { \n return name; \n } \n \n public void setName(Name name) { \n this.name = name; \n } \n \n static class Name { \n public String firstName; \n public String lastName; \n } \n} "
},
{
"code": null,
"e": 6682,
"s": 6628,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 6724,
"s": 6682,
"text": "C:\\GSON_WORKSPACE>javac GsonTester.java \n"
},
{
"code": null,
"e": 6767,
"s": 6724,
"text": "Now run the GsonTester to see the result −"
},
{
"code": null,
"e": 6803,
"s": 6767,
"text": "C:\\GSON_WORKSPACE>java GsonTester \n"
},
{
"code": null,
"e": 6822,
"s": 6803,
"text": "Verify the output."
},
{
"code": null,
"e": 7038,
"s": 6822,
"text": "{\"rollNo\":1,\"name\":{\"firstName\":\"Mahesh\",\"lastName\":\"Kumar\"}} \nRoll No: 1 \nFirst Name: Mahesh \nLast Name: Kumar \n\n{\"firstName\":\"Mahesh\",\"lastName\":\"Kumar\"} \nclass Student$Name \nFirst Name: Mahesh \nLast Name: Kumar \n"
},
{
"code": null,
"e": 7045,
"s": 7038,
"text": " Print"
},
{
"code": null,
"e": 7056,
"s": 7045,
"text": " Add Notes"
}
] |
Java Examples - Calculating Fibonacci Series | How to use method for calculating Fibonacci series?
This example shows the way of using method for calculating Fibonacci Series upto numbers.
public class MainClass {
public static long fibonacci(long number) {
if ((number == 0) || (number == 1)) return number;
else return fibonacci(number - 1) + fibonacci(number - 2);
}
public static void main(String[] args) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
}
}
The above code sample will produce the following result.
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55
The following is an another example of Fibonacci series
public class ExampleFibonacci {
public static void main(String a[]) {
int count = 15;
int[] feb = new int[count];
feb[0] = 0;
feb[1] = 1;
for(int i = 2; i < count; i++) {
feb[i] = feb[i-1] + feb[i-2];
}
for(int i = 0; i < count; i++) {
System.out.print(feb[i] + " ");
}
}
}
The above code sample will produce the following result.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2121,
"s": 2068,
"text": "How to use method for calculating Fibonacci series?"
},
{
"code": null,
"e": 2212,
"s": 2121,
"text": "This example shows the way of using method for calculating Fibonacci Series upto numbers."
},
{
"code": null,
"e": 2610,
"s": 2212,
"text": "public class MainClass {\n public static long fibonacci(long number) {\n if ((number == 0) || (number == 1)) return number;\n else return fibonacci(number - 1) + fibonacci(number - 2);\n }\n public static void main(String[] args) {\n for (int counter = 0; counter <= 10; counter++){\n System.out.printf(\"Fibonacci of %d is: %d\\n\", counter, fibonacci(counter));\n }\n }\n}"
},
{
"code": null,
"e": 2667,
"s": 2610,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2904,
"s": 2667,
"text": "Fibonacci of 0 is: 0\nFibonacci of 1 is: 1\nFibonacci of 2 is: 1\nFibonacci of 3 is: 2\nFibonacci of 4 is: 3\nFibonacci of 5 is: 5\nFibonacci of 6 is: 8\nFibonacci of 7 is: 13\nFibonacci of 8 is: 21\nFibonacci of 9 is: 34\nFibonacci of 10 is: 55\n"
},
{
"code": null,
"e": 2960,
"s": 2904,
"text": "The following is an another example of Fibonacci series"
},
{
"code": null,
"e": 3314,
"s": 2960,
"text": "public class ExampleFibonacci {\n public static void main(String a[]) {\n int count = 15;\n int[] feb = new int[count];\n feb[0] = 0;\n feb[1] = 1;\n \n for(int i = 2; i < count; i++) {\n feb[i] = feb[i-1] + feb[i-2];\n } \n for(int i = 0; i < count; i++) {\n System.out.print(feb[i] + \" \");\n }\n }\n}"
},
{
"code": null,
"e": 3371,
"s": 3314,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3414,
"s": 3371,
"text": "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 \n"
},
{
"code": null,
"e": 3421,
"s": 3414,
"text": " Print"
},
{
"code": null,
"e": 3432,
"s": 3421,
"text": " Add Notes"
}
] |
BigInteger class in Java
| The java.math.BigInteger class provides operations analogs to all of Java's primitive integer operators and for all relevant methods from java.lang.Math.
It also provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations. All operations behave as if BigIntegers were represented in twos-complement notation.
The semantics of arithmetic operations and bitwise logical operations are similar to those of Java's integer arithmetic operators and Java's bitwise integer operators respectively. The semantics of shift operations extend those of Java's shift operators to allow for negative shift distances.
Comparison operations perform signed integer comparisons. Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. Bit operations operate on a single bit of the twos-complement representation of their operand.
All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter.
Following is the declaration for java.math.BigInteger class −
public class BigInteger
extends Number
implements Comparable<BigInteger>
Following are the fields for java.math.BigInteger class −
static BigInteger ONE − The BigInteger constant one.
static BigInteger ONE − The BigInteger constant one.
static BigInteger TEN − The BigInteger constant ten.
static BigInteger TEN − The BigInteger constant ten.
static BigInteger ZERO − The BigInteger constant zero.
static BigInteger ZERO − The BigInteger constant zero.
Live Demo
import java.math.BigInteger;
public class Tester {
public static void main(String[] args) {
// create 3 BigInteger objects
BigInteger bi1, bi2;
// assign values to bi1, bi2
bi1 = new BigInteger("123");
bi2 = new BigInteger("-50");
System.out.println("Absolute value of "
+ bi2 + " is " + bi2.abs());
System.out.println("Result of addition of "
+ bi1 + ", "+ bi2 + " is " +bi1.add(bi2));
System.out.println("Result of and opearation of "
+ bi1 + ", "+ bi2 + " is " +bi1.and(bi2));
System.out.println("Result of bitCount opearation of "
+ bi1 + " is " +bi1.bitCount());
System.out.println("Result of compareTo opearation of "
+ bi1 + ", "+ bi2 + " is " +bi1.compareTo(bi2));
}
}
Absolute value of -50 is 50
Result of addition of 123, -50 is 73
Result of and opearation of 123, -50 is 74
Result of bitCount opearation of 123 is 6
Result of compareTo opearation of 123, -50 is 1 | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "The java.math.BigInteger class provides operations analogs to all of Java's primitive integer operators and for all relevant methods from java.lang.Math."
},
{
"code": null,
"e": 1468,
"s": 1216,
"text": "It also provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations. All operations behave as if BigIntegers were represented in twos-complement notation."
},
{
"code": null,
"e": 1761,
"s": 1468,
"text": "The semantics of arithmetic operations and bitwise logical operations are similar to those of Java's integer arithmetic operators and Java's bitwise integer operators respectively. The semantics of shift operations extend those of Java's shift operators to allow for negative shift distances."
},
{
"code": null,
"e": 2039,
"s": 1761,
"text": "Comparison operations perform signed integer comparisons. Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. Bit operations operate on a single bit of the twos-complement representation of their operand."
},
{
"code": null,
"e": 2170,
"s": 2039,
"text": "All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter."
},
{
"code": null,
"e": 2232,
"s": 2170,
"text": "Following is the declaration for java.math.BigInteger class −"
},
{
"code": null,
"e": 2324,
"s": 2232,
"text": "public class BigInteger \n extends Number \n implements Comparable<BigInteger>"
},
{
"code": null,
"e": 2382,
"s": 2324,
"text": "Following are the fields for java.math.BigInteger class −"
},
{
"code": null,
"e": 2435,
"s": 2382,
"text": "static BigInteger ONE − The BigInteger constant one."
},
{
"code": null,
"e": 2488,
"s": 2435,
"text": "static BigInteger ONE − The BigInteger constant one."
},
{
"code": null,
"e": 2541,
"s": 2488,
"text": "static BigInteger TEN − The BigInteger constant ten."
},
{
"code": null,
"e": 2594,
"s": 2541,
"text": "static BigInteger TEN − The BigInteger constant ten."
},
{
"code": null,
"e": 2649,
"s": 2594,
"text": "static BigInteger ZERO − The BigInteger constant zero."
},
{
"code": null,
"e": 2704,
"s": 2649,
"text": "static BigInteger ZERO − The BigInteger constant zero."
},
{
"code": null,
"e": 2714,
"s": 2704,
"text": "Live Demo"
},
{
"code": null,
"e": 3526,
"s": 2714,
"text": "import java.math.BigInteger;\n\npublic class Tester {\n public static void main(String[] args) {\n // create 3 BigInteger objects\n BigInteger bi1, bi2;\n \n // assign values to bi1, bi2\n bi1 = new BigInteger(\"123\");\n bi2 = new BigInteger(\"-50\");\n\n System.out.println(\"Absolute value of \" \n + bi2 + \" is \" + bi2.abs());\n System.out.println(\"Result of addition of \" \n + bi1 + \", \"+ bi2 + \" is \" +bi1.add(bi2));\n System.out.println(\"Result of and opearation of \"\n + bi1 + \", \"+ bi2 + \" is \" +bi1.and(bi2));\n System.out.println(\"Result of bitCount opearation of \"\n + bi1 + \" is \" +bi1.bitCount());\n System.out.println(\"Result of compareTo opearation of \"\n + bi1 + \", \"+ bi2 + \" is \" +bi1.compareTo(bi2));\n }\n}"
},
{
"code": null,
"e": 3724,
"s": 3526,
"text": "Absolute value of -50 is 50\nResult of addition of 123, -50 is 73\nResult of and opearation of 123, -50 is 74\nResult of bitCount opearation of 123 is 6\nResult of compareTo opearation of 123, -50 is 1"
}
] |
C# | Array.FindAll() Method - GeeksforGeeks | 06 Oct, 2021
This method is used to retrieve all the elements that match the conditions defined by the specified predicate.Syntax:
public static T[] FindAll (T[] array, Predicate match);
Here, T is the type of element of the array.Parameters:
array: It is the one-dimensional, zero-based array to search.match: It is the predicate that defines the conditions of the element to search for.
Return Value: This method return an array containing all elements that matches the conditions defined by the specified predicate if it is found. Otherwise, it returns an empty array.Exception: This method throws ArgumentNullException if the array is null or match is null.Below programs illustrate the use of Array.FindAll(T[], Predicate) Method:Example 1:
CSharp
// C# program to demonstrate// FindAll() methodusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing new the String String[] myArr = {"Sun", "Mon", "Tue", "Sat"}; // Display the values of the myArr. Console.WriteLine("Initial Array:"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(myArr); // getting a element a with required // condition using method Find() String[] value = Array.FindAll(myArr, element => element.StartsWith("S", StringComparison.Ordinal)); // Display the value // of the found element. Console.WriteLine("Elements are: "); // printing the Array of String PrintIndexAndValues(value); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine("{0}", myArr[i]); } Console.WriteLine();}}
Initial Array:
Sun
Mon
Tue
Sat
Elements are:
Sun
Sat
Example 2:
CSharp
// C# program to demonstrate// FindAll() method// For ArgumentNullExceptionusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing // new the String String[] myArr = null; // getting a element a with // required condition using // method Find() Console.WriteLine("Trying to get the element from a null array"); Console.WriteLine(); String[] value = Array.FindAll(myArr, element => element.StartsWith("S", StringComparison.Ordinal)); // Display the value of the found element. Console.WriteLine("Elements are: "); // printing the Array of String PrintIndexAndValues(value); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine("{0}", myArr[i]); } Console.WriteLine();}}
Trying to get the element from a null array
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.array.findall?view=netframework-4.7.2
simranarora5sos
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Replace() Method
C# | Class and Object
C# | Constructors
Introduction to .NET Framework
C# | Data Types
C# | Encapsulation
Common Language Runtime (CLR) in C# | [
{
"code": null,
"e": 25875,
"s": 25847,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 25995,
"s": 25875,
"text": "This method is used to retrieve all the elements that match the conditions defined by the specified predicate.Syntax: "
},
{
"code": null,
"e": 26051,
"s": 25995,
"text": "public static T[] FindAll (T[] array, Predicate match);"
},
{
"code": null,
"e": 26109,
"s": 26051,
"text": "Here, T is the type of element of the array.Parameters: "
},
{
"code": null,
"e": 26257,
"s": 26109,
"text": "array: It is the one-dimensional, zero-based array to search.match: It is the predicate that defines the conditions of the element to search for. "
},
{
"code": null,
"e": 26615,
"s": 26257,
"text": "Return Value: This method return an array containing all elements that matches the conditions defined by the specified predicate if it is found. Otherwise, it returns an empty array.Exception: This method throws ArgumentNullException if the array is null or match is null.Below programs illustrate the use of Array.FindAll(T[], Predicate) Method:Example 1: "
},
{
"code": null,
"e": 26622,
"s": 26615,
"text": "CSharp"
},
{
"code": "// C# program to demonstrate// FindAll() methodusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing new the String String[] myArr = {\"Sun\", \"Mon\", \"Tue\", \"Sat\"}; // Display the values of the myArr. Console.WriteLine(\"Initial Array:\"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(myArr); // getting a element a with required // condition using method Find() String[] value = Array.FindAll(myArr, element => element.StartsWith(\"S\", StringComparison.Ordinal)); // Display the value // of the found element. Console.WriteLine(\"Elements are: \"); // printing the Array of String PrintIndexAndValues(value); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine(\"{0}\", myArr[i]); } Console.WriteLine();}}",
"e": 27852,
"s": 26622,
"text": null
},
{
"code": null,
"e": 27907,
"s": 27852,
"text": "Initial Array:\nSun\nMon\nTue\nSat\n\nElements are: \nSun\nSat"
},
{
"code": null,
"e": 27921,
"s": 27909,
"text": "Example 2: "
},
{
"code": null,
"e": 27928,
"s": 27921,
"text": "CSharp"
},
{
"code": "// C# program to demonstrate// FindAll() method// For ArgumentNullExceptionusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing // new the String String[] myArr = null; // getting a element a with // required condition using // method Find() Console.WriteLine(\"Trying to get the element from a null array\"); Console.WriteLine(); String[] value = Array.FindAll(myArr, element => element.StartsWith(\"S\", StringComparison.Ordinal)); // Display the value of the found element. Console.WriteLine(\"Elements are: \"); // printing the Array of String PrintIndexAndValues(value); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine(\"{0}\", myArr[i]); } Console.WriteLine();}}",
"e": 29086,
"s": 27928,
"text": null
},
{
"code": null,
"e": 29178,
"s": 29086,
"text": "Trying to get the element from a null array\n\nException Thrown: System.ArgumentNullException"
},
{
"code": null,
"e": 29193,
"s": 29180,
"text": "Reference: "
},
{
"code": null,
"e": 29282,
"s": 29193,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.array.findall?view=netframework-4.7.2"
},
{
"code": null,
"e": 29300,
"s": 29284,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29314,
"s": 29300,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 29328,
"s": 29314,
"text": "CSharp-method"
},
{
"code": null,
"e": 29331,
"s": 29328,
"text": "C#"
},
{
"code": null,
"e": 29429,
"s": 29331,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29444,
"s": 29429,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29466,
"s": 29444,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29489,
"s": 29466,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29511,
"s": 29489,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 29533,
"s": 29511,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 29551,
"s": 29533,
"text": "C# | Constructors"
},
{
"code": null,
"e": 29582,
"s": 29551,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 29598,
"s": 29582,
"text": "C# | Data Types"
},
{
"code": null,
"e": 29617,
"s": 29598,
"text": "C# | Encapsulation"
}
] |
Cordova - Battery Status | This Cordova plugin is used for monitoring device's battery status. The plugin will monitor every change that happens to device's battery.
To install this plugin, we need to open the command prompt window and run the following code.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-pluginbattery-status
When you open the index.js file, you will find the onDeviceReady function. This is where the event listener should be added.
window.addEventListener("batterystatus", onBatteryStatus, false);
We will create the onBatteryStatus callback function at the bottom of the index.js file.
function onBatteryStatus(info) {
alert("BATTERY STATUS: Level: " + info.level + " isPlugged: " + info.isPlugged);
}
When we run the app, an alert will be triggered. At the moment, the battery is 100% charged.
When the status is changed, a new alert will be displayed. The battery status shows that the battery is now charged 99%.
If we plug in the device to the charger, the new alert will show that the isPlugged value is changed to true.
This plugin offers two additional events besides the batterystatus event. These events can be used in the same way as the batterystatus event.
batterylow
The event is triggered when the battery charge percentage reaches low value. This value varies with different devices.
batterycritical
The event is triggered when the battery charge percentage reaches critical value. This value varies with different devices.
45 Lectures
2 hours
Skillbakerystudios
16 Lectures
1 hours
Nilay Mehta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2319,
"s": 2180,
"text": "This Cordova plugin is used for monitoring device's battery status. The plugin will monitor every change that happens to device's battery."
},
{
"code": null,
"e": 2413,
"s": 2319,
"text": "To install this plugin, we need to open the command prompt window and run the following code."
},
{
"code": null,
"e": 2504,
"s": 2413,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-pluginbattery-status \n"
},
{
"code": null,
"e": 2629,
"s": 2504,
"text": "When you open the index.js file, you will find the onDeviceReady function. This is where the event listener should be added."
},
{
"code": null,
"e": 2697,
"s": 2629,
"text": "window.addEventListener(\"batterystatus\", onBatteryStatus, false); \n"
},
{
"code": null,
"e": 2786,
"s": 2697,
"text": "We will create the onBatteryStatus callback function at the bottom of the index.js file."
},
{
"code": null,
"e": 2908,
"s": 2786,
"text": "function onBatteryStatus(info) { \n alert(\"BATTERY STATUS: Level: \" + info.level + \" isPlugged: \" + info.isPlugged); \n}"
},
{
"code": null,
"e": 3001,
"s": 2908,
"text": "When we run the app, an alert will be triggered. At the moment, the battery is 100% charged."
},
{
"code": null,
"e": 3122,
"s": 3001,
"text": "When the status is changed, a new alert will be displayed. The battery status shows that the battery is now charged 99%."
},
{
"code": null,
"e": 3232,
"s": 3122,
"text": "If we plug in the device to the charger, the new alert will show that the isPlugged value is changed to true."
},
{
"code": null,
"e": 3375,
"s": 3232,
"text": "This plugin offers two additional events besides the batterystatus event. These events can be used in the same way as the batterystatus event."
},
{
"code": null,
"e": 3386,
"s": 3375,
"text": "batterylow"
},
{
"code": null,
"e": 3505,
"s": 3386,
"text": "The event is triggered when the battery charge percentage reaches low value. This value varies with different devices."
},
{
"code": null,
"e": 3521,
"s": 3505,
"text": "batterycritical"
},
{
"code": null,
"e": 3645,
"s": 3521,
"text": "The event is triggered when the battery charge percentage reaches critical value. This value varies with different devices."
},
{
"code": null,
"e": 3678,
"s": 3645,
"text": "\n 45 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3698,
"s": 3678,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3731,
"s": 3698,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3744,
"s": 3731,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 3751,
"s": 3744,
"text": " Print"
},
{
"code": null,
"e": 3762,
"s": 3751,
"text": " Add Notes"
}
] |
How to return multiple values from function in PHP? - GeeksforGeeks | 10 Feb, 2022
PHP doesn’t support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed. However, there are ways to work around this limitation. The multiple values can be returned from a function by using an array.Example 1: This example shows how to return multiple values from a function in PHP. First, create an empty array end push the element to the array and then return the array.
php
<?php // Function to return the array// of factors of nfunction factors( $n ) { // Declare an empty array $fact = array(); // Loop to find the for ( $i = 1; $i < $n; $i++) { // Check if i is the factor of // n then push it into array if( $n % $i == 0 ) array_push( $fact, $i ); } // Return the array return $fact;} // Declare a variable and initialize it$num = 24; // Function call$nFactors = factors($num); // Display the resultecho 'Factors of ' . $num . ' are: <br>'; foreach( $nFactors as $x ) { echo $x . "<br>";} ?>
Factors of 24 are:
1
2
3
4
6
8
12
Example 2: This example uses list function to store the swapped value of variable. It is used to assign array values to multiple variables at the same time. The multiple values returned in array from the function can be assigned to corresponding variables using list().
php
<?php // Function to swap two numbersfunction swap( $x, $y ) { return array( $y, $x );} // Declare variable and initialize it$a = 10;$b = 20; echo 'Before swapping the elements <br>'; // Display the value of a and becho 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>'; // Function call to swap the value of a and blist($a, $b) = swap($a, $b); echo 'After swapping the elements <br>'; // Display the value of a and becho 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>'; ?>
Before swapping the elements
a = 10
b = 20
After swapping the elements
a = 20
b = 10
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
shubham_singh
sagar0719kumar
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
How to get parameters from a URL string in PHP?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
How to get parameters from a URL string in PHP? | [
{
"code": null,
"e": 25885,
"s": 25857,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 26415,
"s": 25885,
"text": "PHP doesn’t support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed. However, there are ways to work around this limitation. The multiple values can be returned from a function by using an array.Example 1: This example shows how to return multiple values from a function in PHP. First, create an empty array end push the element to the array and then return the array. "
},
{
"code": null,
"e": 26419,
"s": 26415,
"text": "php"
},
{
"code": "<?php // Function to return the array// of factors of nfunction factors( $n ) { // Declare an empty array $fact = array(); // Loop to find the for ( $i = 1; $i < $n; $i++) { // Check if i is the factor of // n then push it into array if( $n % $i == 0 ) array_push( $fact, $i ); } // Return the array return $fact;} // Declare a variable and initialize it$num = 24; // Function call$nFactors = factors($num); // Display the resultecho 'Factors of ' . $num . ' are: <br>'; foreach( $nFactors as $x ) { echo $x . \"<br>\";} ?>",
"e": 27017,
"s": 26419,
"text": null
},
{
"code": null,
"e": 27052,
"s": 27017,
"text": "Factors of 24 are: \n1\n2\n3\n4\n6\n8\n12"
},
{
"code": null,
"e": 27325,
"s": 27054,
"text": "Example 2: This example uses list function to store the swapped value of variable. It is used to assign array values to multiple variables at the same time. The multiple values returned in array from the function can be assigned to corresponding variables using list(). "
},
{
"code": null,
"e": 27329,
"s": 27325,
"text": "php"
},
{
"code": "<?php // Function to swap two numbersfunction swap( $x, $y ) { return array( $y, $x );} // Declare variable and initialize it$a = 10;$b = 20; echo 'Before swapping the elements <br>'; // Display the value of a and becho 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>'; // Function call to swap the value of a and blist($a, $b) = swap($a, $b); echo 'After swapping the elements <br>'; // Display the value of a and becho 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>'; ?>",
"e": 27796,
"s": 27329,
"text": null
},
{
"code": null,
"e": 27883,
"s": 27796,
"text": "Before swapping the elements \na = 10\nb = 20\nAfter swapping the elements \na = 20\nb = 10"
},
{
"code": null,
"e": 28054,
"s": 27885,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 28068,
"s": 28054,
"text": "shubham_singh"
},
{
"code": null,
"e": 28083,
"s": 28068,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 28090,
"s": 28083,
"text": "Picked"
},
{
"code": null,
"e": 28094,
"s": 28090,
"text": "PHP"
},
{
"code": null,
"e": 28107,
"s": 28094,
"text": "PHP Programs"
},
{
"code": null,
"e": 28124,
"s": 28107,
"text": "Web Technologies"
},
{
"code": null,
"e": 28151,
"s": 28124,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28155,
"s": 28151,
"text": "PHP"
},
{
"code": null,
"e": 28253,
"s": 28155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28293,
"s": 28253,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28338,
"s": 28293,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 28390,
"s": 28338,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 28432,
"s": 28390,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 28480,
"s": 28432,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 28520,
"s": 28480,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28572,
"s": 28520,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 28624,
"s": 28572,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 28666,
"s": 28624,
"text": "How to pass JavaScript variables to PHP ?"
}
] |
How to fire jQuery events with setTimeout? | The jQuery setTimeout() method is used to set an interval for events to fire.
Here, we will set an interval of 3 seconds for an alert box to load using jQuery events:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
setTimeout("alert('Hello World!');", 3000);
});
});
</script>
</head>
<body>
<button id="button1">Click</button>
<p>Click the above button and wait for 3 seconds. An alert box will generate after 3 seconds.</p>
<p></p>
</body>
</html> | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "The jQuery setTimeout() method is used to set an interval for events to fire."
},
{
"code": null,
"e": 1229,
"s": 1140,
"text": "Here, we will set an interval of 3 seconds for an alert box to load using jQuery events:"
},
{
"code": null,
"e": 1239,
"s": 1229,
"text": "Live Demo"
},
{
"code": null,
"e": 1681,
"s": 1239,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"#button1\").click(function(){\n setTimeout(\"alert('Hello World!');\", 3000);\n });\n});\n</script>\n</head>\n<body>\n\n<button id=\"button1\">Click</button>\n<p>Click the above button and wait for 3 seconds. An alert box will generate after 3 seconds.</p>\n\n<p></p>\n</body>\n</html>"
}
] |
Priority Queues with C# | A priority queue is held information with a priority value. It is an extension of queue.
The item with the highest property is removed first when you try to eliminate an item from a priority queue.
Let us see how to set priority queue −
public class MyPriorityQueue <T> where T : IComparable <T> {
}
Now let us add an item. In the below example the items get stored in info, which is a generic list.
public class MyPriorityQueue <T> where T : IComparable <T> {
private List <T> info;
public MyPriorityQueue() {
this.info = new List <T>();
}
} | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "A priority queue is held information with a priority value. It is an extension of queue."
},
{
"code": null,
"e": 1260,
"s": 1151,
"text": "The item with the highest property is removed first when you try to eliminate an item from a priority queue."
},
{
"code": null,
"e": 1299,
"s": 1260,
"text": "Let us see how to set priority queue −"
},
{
"code": null,
"e": 1363,
"s": 1299,
"text": "public class MyPriorityQueue <T> where T : IComparable <T> {\n\n}"
},
{
"code": null,
"e": 1463,
"s": 1363,
"text": "Now let us add an item. In the below example the items get stored in info, which is a generic list."
},
{
"code": null,
"e": 1622,
"s": 1463,
"text": "public class MyPriorityQueue <T> where T : IComparable <T> {\n private List <T> info;\n\n public MyPriorityQueue() {\n this.info = new List <T>();\n }\n}"
}
] |
How to get protocol, domain and port from URL using JavaScript ? - GeeksforGeeks | 30 May, 2019
The protocol, domain, and port of the current page can be found by two methods:
Method 1: Using location.protocol, location.hostname, location.port methods: The location interface has various methods that can be used to return the required properties.
The location.protocol property is used to return the protocol scheme of the URL along with the final colon(:).
The location.hostname is used to return the domain name of the URL.
The location.port property is used to return the port of the URL. It returns nothing if the port is not described explicitly in the URL.
Syntax:
protocol = location.protocol;
domain = location.hostname;
port = location.port;
Example:
<!DOCTYPE html><html> <head> <title> Get protocol, domain, and port from URL </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Get protocol, domain, and port from URL </b> <p> Protocol is: <span class="protocol"></span> </p> <p> Domain is: <span class="domain"></span> </p> <p> Port is: <span class="port"></span> </p> <button onclick="getDetails()"> Get protocol, domain, port </button> <script type="text/javascript"> function getDetails() { protocol = location.protocol; domain = location.hostname; port = location.port; document.querySelector('.protocol').textContent = protocol; document.querySelector('.domain').textContent = domain; document.querySelector('.port').textContent = port; } </script></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
Method 2: Using the URL interface: The URL interface is used to represent object URL. It can be used for getting the port, domain, and protocol as it has inbuilt methods to get these values.
The url.protocol property is used to return the protocol scheme of the URL along with the final colon(:).
The url.hostname is used to return the domain of the URL.
The url.port property is used to return the port of the URL. It returns ” if the port is not described explicitly.
Note: This API is not supported in Internet Explorer 11.
Syntax:
current_url = window.location.href;
url_object = new URL(current_url);
protocol = url_object.protocol;
domain = url_object.hostname;
port = url_object.port;
Example:
<!DOCTYPE html><html> <head> <title> Get protocol, domain, and port from URL </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Get protocol, domain, and port from URL </b> <p>Protocol is: <span class="protocol"></span></p> <p>Domain is: <span class="domain"></span></p> <p>Port is: <span class="port"></span></p> <button onclick="getDetails()"> Get protocol, domain, port </button> <script type="text/javascript"> function getDetails() { current_url = window.location.href; url_object = new URL(current_url); protocol = url_object.protocol; domain = url_object.hostname; port = url_object.port; document.querySelector('.protocol').textContent = protocol; document.querySelector('.domain').textContent = domain; document.querySelector('.port').textContent = port; } </script></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26383,
"s": 26355,
"text": "\n30 May, 2019"
},
{
"code": null,
"e": 26463,
"s": 26383,
"text": "The protocol, domain, and port of the current page can be found by two methods:"
},
{
"code": null,
"e": 26635,
"s": 26463,
"text": "Method 1: Using location.protocol, location.hostname, location.port methods: The location interface has various methods that can be used to return the required properties."
},
{
"code": null,
"e": 26746,
"s": 26635,
"text": "The location.protocol property is used to return the protocol scheme of the URL along with the final colon(:)."
},
{
"code": null,
"e": 26814,
"s": 26746,
"text": "The location.hostname is used to return the domain name of the URL."
},
{
"code": null,
"e": 26951,
"s": 26814,
"text": "The location.port property is used to return the port of the URL. It returns nothing if the port is not described explicitly in the URL."
},
{
"code": null,
"e": 26959,
"s": 26951,
"text": "Syntax:"
},
{
"code": null,
"e": 27039,
"s": 26959,
"text": "protocol = location.protocol;\ndomain = location.hostname;\nport = location.port;"
},
{
"code": null,
"e": 27048,
"s": 27039,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Get protocol, domain, and port from URL </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Get protocol, domain, and port from URL </b> <p> Protocol is: <span class=\"protocol\"></span> </p> <p> Domain is: <span class=\"domain\"></span> </p> <p> Port is: <span class=\"port\"></span> </p> <button onclick=\"getDetails()\"> Get protocol, domain, port </button> <script type=\"text/javascript\"> function getDetails() { protocol = location.protocol; domain = location.hostname; port = location.port; document.querySelector('.protocol').textContent = protocol; document.querySelector('.domain').textContent = domain; document.querySelector('.port').textContent = port; } </script></body> </html> ",
"e": 28109,
"s": 27048,
"text": null
},
{
"code": null,
"e": 28117,
"s": 28109,
"text": "Output:"
},
{
"code": null,
"e": 28145,
"s": 28117,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 28172,
"s": 28145,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 28363,
"s": 28172,
"text": "Method 2: Using the URL interface: The URL interface is used to represent object URL. It can be used for getting the port, domain, and protocol as it has inbuilt methods to get these values."
},
{
"code": null,
"e": 28469,
"s": 28363,
"text": "The url.protocol property is used to return the protocol scheme of the URL along with the final colon(:)."
},
{
"code": null,
"e": 28527,
"s": 28469,
"text": "The url.hostname is used to return the domain of the URL."
},
{
"code": null,
"e": 28642,
"s": 28527,
"text": "The url.port property is used to return the port of the URL. It returns ” if the port is not described explicitly."
},
{
"code": null,
"e": 28699,
"s": 28642,
"text": "Note: This API is not supported in Internet Explorer 11."
},
{
"code": null,
"e": 28707,
"s": 28699,
"text": "Syntax:"
},
{
"code": null,
"e": 28865,
"s": 28707,
"text": "current_url = window.location.href;\nurl_object = new URL(current_url);\n\nprotocol = url_object.protocol;\ndomain = url_object.hostname;\nport = url_object.port;"
},
{
"code": null,
"e": 28874,
"s": 28865,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Get protocol, domain, and port from URL </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Get protocol, domain, and port from URL </b> <p>Protocol is: <span class=\"protocol\"></span></p> <p>Domain is: <span class=\"domain\"></span></p> <p>Port is: <span class=\"port\"></span></p> <button onclick=\"getDetails()\"> Get protocol, domain, port </button> <script type=\"text/javascript\"> function getDetails() { current_url = window.location.href; url_object = new URL(current_url); protocol = url_object.protocol; domain = url_object.hostname; port = url_object.port; document.querySelector('.protocol').textContent = protocol; document.querySelector('.domain').textContent = domain; document.querySelector('.port').textContent = port; } </script></body> </html> ",
"e": 29968,
"s": 28874,
"text": null
},
{
"code": null,
"e": 29976,
"s": 29968,
"text": "Output:"
},
{
"code": null,
"e": 30004,
"s": 29976,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 30031,
"s": 30004,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 30047,
"s": 30031,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30054,
"s": 30047,
"text": "Picked"
},
{
"code": null,
"e": 30065,
"s": 30054,
"text": "JavaScript"
},
{
"code": null,
"e": 30082,
"s": 30065,
"text": "Web Technologies"
},
{
"code": null,
"e": 30109,
"s": 30082,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30207,
"s": 30109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30247,
"s": 30207,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30292,
"s": 30247,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30353,
"s": 30292,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30425,
"s": 30353,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30466,
"s": 30425,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30506,
"s": 30466,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30539,
"s": 30506,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30584,
"s": 30539,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30627,
"s": 30584,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to embed tables in New Google Sites ? - GeeksforGeeks | 10 Sep, 2020
Sometimes, we have to display some data in a systematic manner, to do so we use tables. To embed the table in Google sites follow the steps:
Select embed option from the insert panel and then go to embed code division of the dialogue box appeared.
Write your iframe code in the space provided.
To insert a border-less table use the following code:
HTML
<body> <h2>Test Scores</h2> <table style="width:100%"> <tr> <th>Geek Name</th> <th>Score</th> </tr> <tr> <td>Geek 1</td> <td>50</td> </tr> <tr> <td>Geek 2</td> <td>94</td> </tr> </table></body>
To add a bordered table just use the following code:
HTML
<head> <style> table, th, td { border: 1px solid black; } </style></head> <body> <h2>Test Scores</h2> <table style="width:100%"> <tr> <th>Geek Name</th> <th>Score</th> </tr> <tr> <td>Geek 1</td> <td>50</td> </tr> <tr> <td>Geek 2</td> <td>94</td> </tr> </table></body>
To add a table with some background color use the following code:
HTML
<head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 15px; text-align: left; background-color: lightGreen; } </style></head> <body> <h2>Test Scores</h2> <table style="width:100%"> <tr> <th>Geek Name</th> <th>Score</th> </tr> <tr> <td>Geek 1</td> <td>50</td> </tr> <tr> <td>Geek 2</td> <td>94</td> </tr> </table></body>
You can change the style and content of the table as per your requirement.
Google Sites
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
File uploading in React.js
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 26245,
"s": 26217,
"text": "\n10 Sep, 2020"
},
{
"code": null,
"e": 26386,
"s": 26245,
"text": "Sometimes, we have to display some data in a systematic manner, to do so we use tables. To embed the table in Google sites follow the steps:"
},
{
"code": null,
"e": 26493,
"s": 26386,
"text": "Select embed option from the insert panel and then go to embed code division of the dialogue box appeared."
},
{
"code": null,
"e": 26539,
"s": 26493,
"text": "Write your iframe code in the space provided."
},
{
"code": null,
"e": 26593,
"s": 26539,
"text": "To insert a border-less table use the following code:"
},
{
"code": null,
"e": 26598,
"s": 26593,
"text": "HTML"
},
{
"code": "<body> <h2>Test Scores</h2> <table style=\"width:100%\"> <tr> <th>Geek Name</th> <th>Score</th> </tr> <tr> <td>Geek 1</td> <td>50</td> </tr> <tr> <td>Geek 2</td> <td>94</td> </tr> </table></body>",
"e": 26913,
"s": 26598,
"text": null
},
{
"code": null,
"e": 26966,
"s": 26913,
"text": "To add a bordered table just use the following code:"
},
{
"code": null,
"e": 26971,
"s": 26966,
"text": "HTML"
},
{
"code": "<head> <style> table, th, td { border: 1px solid black; } </style></head> <body> <h2>Test Scores</h2> <table style=\"width:100%\"> <tr> <th>Geek Name</th> <th>Score</th> </tr> <tr> <td>Geek 1</td> <td>50</td> </tr> <tr> <td>Geek 2</td> <td>94</td> </tr> </table></body>",
"e": 27402,
"s": 26971,
"text": null
},
{
"code": null,
"e": 27468,
"s": 27402,
"text": "To add a table with some background color use the following code:"
},
{
"code": null,
"e": 27473,
"s": 27468,
"text": "HTML"
},
{
"code": "<head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 15px; text-align: left; background-color: lightGreen; } </style></head> <body> <h2>Test Scores</h2> <table style=\"width:100%\"> <tr> <th>Geek Name</th> <th>Score</th> </tr> <tr> <td>Geek 1</td> <td>50</td> </tr> <tr> <td>Geek 2</td> <td>94</td> </tr> </table></body>",
"e": 28072,
"s": 27473,
"text": null
},
{
"code": null,
"e": 28147,
"s": 28072,
"text": "You can change the style and content of the table as per your requirement."
},
{
"code": null,
"e": 28160,
"s": 28147,
"text": "Google Sites"
},
{
"code": null,
"e": 28177,
"s": 28160,
"text": "Web Technologies"
},
{
"code": null,
"e": 28275,
"s": 28177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28315,
"s": 28275,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28360,
"s": 28315,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28403,
"s": 28360,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28464,
"s": 28403,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28536,
"s": 28464,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28594,
"s": 28536,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28654,
"s": 28594,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28681,
"s": 28654,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 28714,
"s": 28681,
"text": "Node.js fs.readFileSync() Method"
}
] |
How To Generate SSH Key With ssh-keygen In Linux? - GeeksforGeeks | 30 Jun, 2021
Secure Shell(SSH) is a cryptographic network protocol used for operating remote services securely. It is used for remote operation of devices on secure channels using a client-server architecture that generally operates on Port 22. SSH is the successor of Telnet. SSH uses public and private keys to validate and authenticate users. ssh-keygen is used to generate these key pairs.
You can learn more about SSH and Telnet here
SSH protocol needs to have 2 pairs. A Public Key and a Private Key
The Public Key is added to the remote server (or) device into a special folder $HOME/.ssh/authorized_keys.
When the server sends any response encrypted using the public key, as only the client has the private key, it can only decrypt the response.
After successful authentication, a shell session is created or the requested command is executed on the remote server.
How SSH works
ssh-keygen is the utility used to generate, manage, and convert authentication keys for SSH. ssh-keygen comes installed with SSH in most of the operating systems. ssh-keygen is able to generate a key using one of three different digital signature algorithms.
RSA
DSA
ECDSA
Files generated by ssh-keygen
$HOME/.ssh/identity: File containing the RSA private key when using SSH protocol version 1.
$HOME/.ssh/identity.pub: File containing the RSA public key for authentication when you are using the SSH protocol version
$HOME/.ssh/id_dsa: File containing the protocol version 2 DSA authentication identity of the user.
$HOME/.ssh/id_dsa.pub: File containing the DSA public key for authentication when you are using the SSH protocol version.
$HOME/.ssh/id_rsa: File containing the protocol version 2 RSA authentication identity of the user. This file should not be readable by anyone but the user.
$HOME/.ssh/id_rsa.pub: File containing the protocol version 2 RSA public key for authentication.
“.pub” files should be copied to the $HOME/.ssh/authorized_keys file of the remote system where a user wants to log in using SSH authentication.
Almost all Unix and Linux Distro’s come pre-installed with SSH and ssh-keygen, so we will have no need to install. We will get started directly. This process is almost similar to almost all Linux Distros’s
Open your terminal and type ssh-keygen
ssh-keygen
It asks for the names of the ssh key pairs. If you wish to enter the passphrase, go on and ssh-keygen will automatically create your keys.
//Output
Generating public/private rsa key pair.
// enter the name for ssh key pairs
Enter file in which to save the key (/home/kushwanth/.ssh/id_rsa): gfg
// enter passpharse for security
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
// ssh keys generated
Your identification has been saved in gfg
Your public key has been saved in gfg.pub
ssh key gen created
A public key looks like the one below.
Sample public key
This is the key you need to copy into your remote device to get successful SSH authentication.
After the key pair is created, now we need to copy the public key into the server. There are 2 ways to do this, using ssh-copy-id (or) manually copying it into the server.
Using ssh-copy-id
Use the ssh-copy-id command to copy your public key file (e.g., $HOME/.ssh/id_rsa.pub) to your user account on the remote server.
ssh-copy-id -i $HOME/.ssh/id_rsa.pub <user>@<your-remote-host>
Manually copying the public key
Login to your remote server using the password and create a directory at $HOME/.ssh. You can use the command below.
ssh <user>@<your-remote-host> “umask 077; test -d .ssh || mkdir .ssh”
ssh <user>@<host> allows you to login into your remote host server
If the .ssh directory is already present, it will set the permissions of the directory to 077 so that it allows read, write, and execute permission for the file’s owner, but prohibits reading, writing, and execute permission for everyone else.
If the directory is not present, then it will create a new one.
Now send your public key to the remote server,
cat $HOME/.ssh/id_rsa.pub | ssh <user>@<your-remote-host> “cat >> .ssh/authorized_keys”
cat allows you to print the contents of the file in the terminal.
The output from the cat is piped into SSH to append the public key to a remote server.
Now you can logout and test whether you can connect to the remote server using the SSH protocol.
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Create and Setup Spring Boot Project in Eclipse IDE?
How to Install Jupyter Notebook on MacOS?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples | [
{
"code": null,
"e": 26307,
"s": 26279,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26688,
"s": 26307,
"text": "Secure Shell(SSH) is a cryptographic network protocol used for operating remote services securely. It is used for remote operation of devices on secure channels using a client-server architecture that generally operates on Port 22. SSH is the successor of Telnet. SSH uses public and private keys to validate and authenticate users. ssh-keygen is used to generate these key pairs."
},
{
"code": null,
"e": 26733,
"s": 26688,
"text": "You can learn more about SSH and Telnet here"
},
{
"code": null,
"e": 26800,
"s": 26733,
"text": "SSH protocol needs to have 2 pairs. A Public Key and a Private Key"
},
{
"code": null,
"e": 26907,
"s": 26800,
"text": "The Public Key is added to the remote server (or) device into a special folder $HOME/.ssh/authorized_keys."
},
{
"code": null,
"e": 27048,
"s": 26907,
"text": "When the server sends any response encrypted using the public key, as only the client has the private key, it can only decrypt the response."
},
{
"code": null,
"e": 27167,
"s": 27048,
"text": "After successful authentication, a shell session is created or the requested command is executed on the remote server."
},
{
"code": null,
"e": 27181,
"s": 27167,
"text": "How SSH works"
},
{
"code": null,
"e": 27440,
"s": 27181,
"text": "ssh-keygen is the utility used to generate, manage, and convert authentication keys for SSH. ssh-keygen comes installed with SSH in most of the operating systems. ssh-keygen is able to generate a key using one of three different digital signature algorithms."
},
{
"code": null,
"e": 27444,
"s": 27440,
"text": "RSA"
},
{
"code": null,
"e": 27448,
"s": 27444,
"text": "DSA"
},
{
"code": null,
"e": 27454,
"s": 27448,
"text": "ECDSA"
},
{
"code": null,
"e": 27484,
"s": 27454,
"text": "Files generated by ssh-keygen"
},
{
"code": null,
"e": 27576,
"s": 27484,
"text": "$HOME/.ssh/identity: File containing the RSA private key when using SSH protocol version 1."
},
{
"code": null,
"e": 27699,
"s": 27576,
"text": "$HOME/.ssh/identity.pub: File containing the RSA public key for authentication when you are using the SSH protocol version"
},
{
"code": null,
"e": 27798,
"s": 27699,
"text": "$HOME/.ssh/id_dsa: File containing the protocol version 2 DSA authentication identity of the user."
},
{
"code": null,
"e": 27920,
"s": 27798,
"text": "$HOME/.ssh/id_dsa.pub: File containing the DSA public key for authentication when you are using the SSH protocol version."
},
{
"code": null,
"e": 28076,
"s": 27920,
"text": "$HOME/.ssh/id_rsa: File containing the protocol version 2 RSA authentication identity of the user. This file should not be readable by anyone but the user."
},
{
"code": null,
"e": 28173,
"s": 28076,
"text": "$HOME/.ssh/id_rsa.pub: File containing the protocol version 2 RSA public key for authentication."
},
{
"code": null,
"e": 28318,
"s": 28173,
"text": "“.pub” files should be copied to the $HOME/.ssh/authorized_keys file of the remote system where a user wants to log in using SSH authentication."
},
{
"code": null,
"e": 28524,
"s": 28318,
"text": "Almost all Unix and Linux Distro’s come pre-installed with SSH and ssh-keygen, so we will have no need to install. We will get started directly. This process is almost similar to almost all Linux Distros’s"
},
{
"code": null,
"e": 28563,
"s": 28524,
"text": "Open your terminal and type ssh-keygen"
},
{
"code": null,
"e": 28574,
"s": 28563,
"text": "ssh-keygen"
},
{
"code": null,
"e": 28713,
"s": 28574,
"text": "It asks for the names of the ssh key pairs. If you wish to enter the passphrase, go on and ssh-keygen will automatically create your keys."
},
{
"code": null,
"e": 29087,
"s": 28713,
"text": "//Output\n\nGenerating public/private rsa key pair.\n\n// enter the name for ssh key pairs\nEnter file in which to save the key (/home/kushwanth/.ssh/id_rsa): gfg\n\n// enter passpharse for security\nEnter passphrase (empty for no passphrase): \nEnter same passphrase again: \n\n// ssh keys generated\nYour identification has been saved in gfg\nYour public key has been saved in gfg.pub"
},
{
"code": null,
"e": 29107,
"s": 29087,
"text": "ssh key gen created"
},
{
"code": null,
"e": 29146,
"s": 29107,
"text": "A public key looks like the one below."
},
{
"code": null,
"e": 29164,
"s": 29146,
"text": "Sample public key"
},
{
"code": null,
"e": 29259,
"s": 29164,
"text": "This is the key you need to copy into your remote device to get successful SSH authentication."
},
{
"code": null,
"e": 29431,
"s": 29259,
"text": "After the key pair is created, now we need to copy the public key into the server. There are 2 ways to do this, using ssh-copy-id (or) manually copying it into the server."
},
{
"code": null,
"e": 29449,
"s": 29431,
"text": "Using ssh-copy-id"
},
{
"code": null,
"e": 29579,
"s": 29449,
"text": "Use the ssh-copy-id command to copy your public key file (e.g., $HOME/.ssh/id_rsa.pub) to your user account on the remote server."
},
{
"code": null,
"e": 29642,
"s": 29579,
"text": "ssh-copy-id -i $HOME/.ssh/id_rsa.pub <user>@<your-remote-host>"
},
{
"code": null,
"e": 29674,
"s": 29642,
"text": "Manually copying the public key"
},
{
"code": null,
"e": 29790,
"s": 29674,
"text": "Login to your remote server using the password and create a directory at $HOME/.ssh. You can use the command below."
},
{
"code": null,
"e": 29860,
"s": 29790,
"text": "ssh <user>@<your-remote-host> “umask 077; test -d .ssh || mkdir .ssh”"
},
{
"code": null,
"e": 29927,
"s": 29860,
"text": "ssh <user>@<host> allows you to login into your remote host server"
},
{
"code": null,
"e": 30171,
"s": 29927,
"text": "If the .ssh directory is already present, it will set the permissions of the directory to 077 so that it allows read, write, and execute permission for the file’s owner, but prohibits reading, writing, and execute permission for everyone else."
},
{
"code": null,
"e": 30235,
"s": 30171,
"text": "If the directory is not present, then it will create a new one."
},
{
"code": null,
"e": 30282,
"s": 30235,
"text": "Now send your public key to the remote server,"
},
{
"code": null,
"e": 30370,
"s": 30282,
"text": "cat $HOME/.ssh/id_rsa.pub | ssh <user>@<your-remote-host> “cat >> .ssh/authorized_keys”"
},
{
"code": null,
"e": 30436,
"s": 30370,
"text": "cat allows you to print the contents of the file in the terminal."
},
{
"code": null,
"e": 30524,
"s": 30436,
"text": "The output from the cat is piped into SSH to append the public key to a remote server."
},
{
"code": null,
"e": 30621,
"s": 30524,
"text": "Now you can logout and test whether you can connect to the remote server using the SSH protocol."
},
{
"code": null,
"e": 30628,
"s": 30621,
"text": "Picked"
},
{
"code": null,
"e": 30635,
"s": 30628,
"text": "How To"
},
{
"code": null,
"e": 30646,
"s": 30635,
"text": "Linux-Unix"
},
{
"code": null,
"e": 30744,
"s": 30646,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30778,
"s": 30744,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 30836,
"s": 30778,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 30885,
"s": 30836,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 30945,
"s": 30885,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 30987,
"s": 30945,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 31027,
"s": 30987,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 31067,
"s": 31027,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 31094,
"s": 31067,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 31129,
"s": 31094,
"text": "cut command in Linux with examples"
}
] |
Find if a degree sequence can form a simple graph | Havel-Hakimi Algorithm - GeeksforGeeks | 25 Aug, 2021
Given a sequence of non-negative integers arr[], the task is to check if there exists a simple graph corresponding to this degree sequence. Note that a simple graph is a graph with no self-loops and parallel edges.
Examples:
Input: arr[] = {3, 3, 3, 3} Output: Yes This is actually a complete graph(K4)
Input: arr[] = {3, 2, 1, 0} Output: No A vertex has degree n-1 so it’s connected to all the other n-1 vertices. But another vertex has degree 0 i.e. isolated. It’s a contradiction.
Approach: One way to check the existence of a simple graph is by Havel-Hakimi algorithm given below:
Sort the sequence of non-negative integers in non-increasing order.
Delete the first element(say V). Subtract 1 from the next V elements.
Repeat 1 and 2 until one of the stopping conditions is met.
Stopping conditions:
All the elements remaining are equal to 0 (Simple graph exists).
Negative number encounter after subtraction (No simple graph exists).
Not enough elements remaining for the subtraction step (No simple graph exists).
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 that returns true if// a simple graph existsbool graphExists(vector<int> &a, int n){ // Keep performing the operations until one // of the stopping condition is met while (1) { // Sort the list in non-decreasing order sort(a.begin(), a.end(), greater<>()); // Check if all the elements are equal to 0 if (a[0] == 0) return true; // Store the first element in a variable // and delete it from the list int v = a[0]; a.erase(a.begin() + 0); // Check if enough elements // are present in the list if (v > a.size()) return false; // Subtract first element from next v elements for (int i = 0; i < v; i++) { a[i]--; // Check if negative element is // encountered after subtraction if (a[i] < 0) return false; } }} // Driver Codeint main(){ vector<int> a = {3, 3, 3, 3}; int n = a.size(); graphExists(a, n) ? cout << "Yes" : cout << "NO" << endl; return 0;} // This code is contributed by// sanjeev2552
// Java implementation of the approachimport java.util.*; @SuppressWarnings("unchecked") class GFG{ // Function that returns true if// a simple graph existsstatic boolean graphExists(ArrayList a, int n){ // Keep performing the operations until one // of the stopping condition is met while (true) { // Sort the list in non-decreasing order Collections.sort(a, Collections.reverseOrder()); // Check if all the elements are equal to 0 if ((int)a.get(0) == 0) return true; // Store the first element in a variable // and delete it from the list int v = (int)a.get(0); a.remove(a.get(0)); // Check if enough elements // are present in the list if (v > a.size()) return false; // Subtract first element from // next v elements for(int i = 0; i < v; i++) { a.set(i, (int)a.get(i) - 1); // Check if negative element is // encountered after subtraction if ((int)a.get(i) < 0) return false; } }} // Driver Codepublic static void main(String[] args){ ArrayList a = new ArrayList(); a.add(3); a.add(3); a.add(3); a.add(3); int n = a.size(); if (graphExists(a, n)) { System.out.print("Yes"); } else { System.out.print("NO"); }}} // This code is contributed by pratham76
# Python3 implementation of the approach # Function that returns true if# a simple graph existsdef graphExists(a): # Keep performing the operations until one # of the stopping condition is met while True: # Sort the list in non-decreasing order a = sorted(a, reverse = True) # Check if all the elements are equal to 0 if a[0]== 0 and a[len(a)-1]== 0: return True # Store the first element in a variable # and delete it from the list v = a[0] a = a[1:] # Check if enough elements # are present in the list if v>len(a): return False # Subtract first element from next v elements for i in range(v): a[i]-= 1 # Check if negative element is # encountered after subtraction if a[i]<0: return False # Driver codea = [3, 3, 3, 3]if(graphExists(a)): print("Yes")else: print("No")
// C# implementation of the approachusing System;using System.Collections; class GFG{ // Function that returns true if// a simple graph existsstatic bool graphExists(ArrayList a, int n){ // Keep performing the operations until one // of the stopping condition is met while (true) { // Sort the list in non-decreasing order a.Sort(); a.Reverse(); // Check if all the elements are equal to 0 if ((int)a[0] == 0) return true; // Store the first element in a variable // and delete it from the list int v = (int)a[0]; a.Remove(a[0]); // Check if enough elements // are present in the list if (v > a.Count) return false; // Subtract first element from // next v elements for(int i = 0; i < v; i++) { a[i] = (int)a[i] - 1; // Check if negative element is // encountered after subtraction if ((int)a[i] < 0) return false; } }} // Driver Codepublic static void Main(string[] args){ ArrayList a = new ArrayList(){ 3, 3, 3, 3 }; int n = a.Count; if (graphExists(a, n)) { Console.Write("Yes"); } else { Console.Write("NO"); }}} // This code is contributed by rutvik_56
<script> // Javascript implementation of the approach // Function that returns true if// a simple graph existsfunction graphExists(a, n){ // Keep performing the operations until one // of the stopping condition is met while (1) { // Sort the list in non-decreasing order a.sort((a, b) => b - a) // Check if all the elements are equal to 0 if (a[0] == 0) return true; // Store the first element in a variable // and delete it from the list var v = a[0]; a.shift(); // Check if enough elements // are present in the list if (v > a.length) return false; // Subtract first element from next v elements for(var i = 0; i < v; i++) { a[i]--; // Check if negative element is // encountered after subtraction if (a[i] < 0) return false; } }} // Driver Codevar a = [ 3, 3, 3, 3 ];var n = a.length;graphExists(a, n) ? document.write("Yes"): document.write("NO"); // This code is contributed by rrrtnx </script>
Yes
Time Complexity: O()Auxiliary Space: O(1)
sanjeev2552
Tapaj
rutvik_56
pratham76
rrrtnx
pankajsharmagfg
Algorithms
Graph
Mathematical
Python
Mathematical
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Playfair Cipher with Examples
How to write a Pseudo Code?
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Graph and its representations | [
{
"code": null,
"e": 25031,
"s": 25003,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 25246,
"s": 25031,
"text": "Given a sequence of non-negative integers arr[], the task is to check if there exists a simple graph corresponding to this degree sequence. Note that a simple graph is a graph with no self-loops and parallel edges."
},
{
"code": null,
"e": 25257,
"s": 25246,
"text": "Examples: "
},
{
"code": null,
"e": 25335,
"s": 25257,
"text": "Input: arr[] = {3, 3, 3, 3} Output: Yes This is actually a complete graph(K4)"
},
{
"code": null,
"e": 25517,
"s": 25335,
"text": "Input: arr[] = {3, 2, 1, 0} Output: No A vertex has degree n-1 so it’s connected to all the other n-1 vertices. But another vertex has degree 0 i.e. isolated. It’s a contradiction. "
},
{
"code": null,
"e": 25619,
"s": 25517,
"text": "Approach: One way to check the existence of a simple graph is by Havel-Hakimi algorithm given below: "
},
{
"code": null,
"e": 25687,
"s": 25619,
"text": "Sort the sequence of non-negative integers in non-increasing order."
},
{
"code": null,
"e": 25757,
"s": 25687,
"text": "Delete the first element(say V). Subtract 1 from the next V elements."
},
{
"code": null,
"e": 25817,
"s": 25757,
"text": "Repeat 1 and 2 until one of the stopping conditions is met."
},
{
"code": null,
"e": 25839,
"s": 25817,
"text": "Stopping conditions: "
},
{
"code": null,
"e": 25904,
"s": 25839,
"text": "All the elements remaining are equal to 0 (Simple graph exists)."
},
{
"code": null,
"e": 25974,
"s": 25904,
"text": "Negative number encounter after subtraction (No simple graph exists)."
},
{
"code": null,
"e": 26055,
"s": 25974,
"text": "Not enough elements remaining for the subtraction step (No simple graph exists)."
},
{
"code": null,
"e": 26106,
"s": 26055,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26110,
"s": 26106,
"text": "C++"
},
{
"code": null,
"e": 26115,
"s": 26110,
"text": "Java"
},
{
"code": null,
"e": 26123,
"s": 26115,
"text": "Python3"
},
{
"code": null,
"e": 26126,
"s": 26123,
"text": "C#"
},
{
"code": null,
"e": 26137,
"s": 26126,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if// a simple graph existsbool graphExists(vector<int> &a, int n){ // Keep performing the operations until one // of the stopping condition is met while (1) { // Sort the list in non-decreasing order sort(a.begin(), a.end(), greater<>()); // Check if all the elements are equal to 0 if (a[0] == 0) return true; // Store the first element in a variable // and delete it from the list int v = a[0]; a.erase(a.begin() + 0); // Check if enough elements // are present in the list if (v > a.size()) return false; // Subtract first element from next v elements for (int i = 0; i < v; i++) { a[i]--; // Check if negative element is // encountered after subtraction if (a[i] < 0) return false; } }} // Driver Codeint main(){ vector<int> a = {3, 3, 3, 3}; int n = a.size(); graphExists(a, n) ? cout << \"Yes\" : cout << \"NO\" << endl; return 0;} // This code is contributed by// sanjeev2552",
"e": 27371,
"s": 26137,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; @SuppressWarnings(\"unchecked\") class GFG{ // Function that returns true if// a simple graph existsstatic boolean graphExists(ArrayList a, int n){ // Keep performing the operations until one // of the stopping condition is met while (true) { // Sort the list in non-decreasing order Collections.sort(a, Collections.reverseOrder()); // Check if all the elements are equal to 0 if ((int)a.get(0) == 0) return true; // Store the first element in a variable // and delete it from the list int v = (int)a.get(0); a.remove(a.get(0)); // Check if enough elements // are present in the list if (v > a.size()) return false; // Subtract first element from // next v elements for(int i = 0; i < v; i++) { a.set(i, (int)a.get(i) - 1); // Check if negative element is // encountered after subtraction if ((int)a.get(i) < 0) return false; } }} // Driver Codepublic static void main(String[] args){ ArrayList a = new ArrayList(); a.add(3); a.add(3); a.add(3); a.add(3); int n = a.size(); if (graphExists(a, n)) { System.out.print(\"Yes\"); } else { System.out.print(\"NO\"); }}} // This code is contributed by pratham76",
"e": 28842,
"s": 27371,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns true if# a simple graph existsdef graphExists(a): # Keep performing the operations until one # of the stopping condition is met while True: # Sort the list in non-decreasing order a = sorted(a, reverse = True) # Check if all the elements are equal to 0 if a[0]== 0 and a[len(a)-1]== 0: return True # Store the first element in a variable # and delete it from the list v = a[0] a = a[1:] # Check if enough elements # are present in the list if v>len(a): return False # Subtract first element from next v elements for i in range(v): a[i]-= 1 # Check if negative element is # encountered after subtraction if a[i]<0: return False # Driver codea = [3, 3, 3, 3]if(graphExists(a)): print(\"Yes\")else: print(\"No\")",
"e": 29808,
"s": 28842,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections; class GFG{ // Function that returns true if// a simple graph existsstatic bool graphExists(ArrayList a, int n){ // Keep performing the operations until one // of the stopping condition is met while (true) { // Sort the list in non-decreasing order a.Sort(); a.Reverse(); // Check if all the elements are equal to 0 if ((int)a[0] == 0) return true; // Store the first element in a variable // and delete it from the list int v = (int)a[0]; a.Remove(a[0]); // Check if enough elements // are present in the list if (v > a.Count) return false; // Subtract first element from // next v elements for(int i = 0; i < v; i++) { a[i] = (int)a[i] - 1; // Check if negative element is // encountered after subtraction if ((int)a[i] < 0) return false; } }} // Driver Codepublic static void Main(string[] args){ ArrayList a = new ArrayList(){ 3, 3, 3, 3 }; int n = a.Count; if (graphExists(a, n)) { Console.Write(\"Yes\"); } else { Console.Write(\"NO\"); }}} // This code is contributed by rutvik_56",
"e": 31161,
"s": 29808,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that returns true if// a simple graph existsfunction graphExists(a, n){ // Keep performing the operations until one // of the stopping condition is met while (1) { // Sort the list in non-decreasing order a.sort((a, b) => b - a) // Check if all the elements are equal to 0 if (a[0] == 0) return true; // Store the first element in a variable // and delete it from the list var v = a[0]; a.shift(); // Check if enough elements // are present in the list if (v > a.length) return false; // Subtract first element from next v elements for(var i = 0; i < v; i++) { a[i]--; // Check if negative element is // encountered after subtraction if (a[i] < 0) return false; } }} // Driver Codevar a = [ 3, 3, 3, 3 ];var n = a.length;graphExists(a, n) ? document.write(\"Yes\"): document.write(\"NO\"); // This code is contributed by rrrtnx </script>",
"e": 32320,
"s": 31161,
"text": null
},
{
"code": null,
"e": 32324,
"s": 32320,
"text": "Yes"
},
{
"code": null,
"e": 32368,
"s": 32326,
"text": "Time Complexity: O()Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32380,
"s": 32368,
"text": "sanjeev2552"
},
{
"code": null,
"e": 32386,
"s": 32380,
"text": "Tapaj"
},
{
"code": null,
"e": 32396,
"s": 32386,
"text": "rutvik_56"
},
{
"code": null,
"e": 32406,
"s": 32396,
"text": "pratham76"
},
{
"code": null,
"e": 32413,
"s": 32406,
"text": "rrrtnx"
},
{
"code": null,
"e": 32429,
"s": 32413,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 32440,
"s": 32429,
"text": "Algorithms"
},
{
"code": null,
"e": 32446,
"s": 32440,
"text": "Graph"
},
{
"code": null,
"e": 32459,
"s": 32446,
"text": "Mathematical"
},
{
"code": null,
"e": 32466,
"s": 32459,
"text": "Python"
},
{
"code": null,
"e": 32479,
"s": 32466,
"text": "Mathematical"
},
{
"code": null,
"e": 32485,
"s": 32479,
"text": "Graph"
},
{
"code": null,
"e": 32496,
"s": 32485,
"text": "Algorithms"
},
{
"code": null,
"e": 32594,
"s": 32496,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32603,
"s": 32594,
"text": "Comments"
},
{
"code": null,
"e": 32616,
"s": 32603,
"text": "Old Comments"
},
{
"code": null,
"e": 32665,
"s": 32616,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 32690,
"s": 32665,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32717,
"s": 32690,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 32747,
"s": 32717,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 32775,
"s": 32747,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 32826,
"s": 32775,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 32877,
"s": 32826,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 32935,
"s": 32877,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Find a peak element in a 2D array - GeeksforGeeks | 29 Apr, 2021
An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. For example neighbors for A[i][j] are A[i-1][j], A[i+1][j], A[i][j-1] and A[i][j+1]. For corner elements, missing neighbors are considered of negative infinite value.Examples:
Input : 10 20 15
21 30 14
7 16 32
Output : 30
30 is a peak element because all its
neighbors are smaller or equal to it.
32 can also be picked as a peak.
Input : 10 7
11 17
Output : 17
Below are some facts about this problem: 1: A Diagonal adjacent is not considered as neighbor. 2: A peak element is not necessarily the maximal element. 3: More than one such elements can exist. 4: There is always a peak element. We can see this property by creating some matrices using pen and paper.Method 1: (Brute Force) Iterate through all the elements of Matrix and check if it is greater/equal to all its neighbors. If yes, return the element.Time Complexity: O(rows * columns) Auxiliary Space: O(1)Method 2 : (Efficient) This problem is mainly an extension of Find a peak element in 1D array. We apply similar Binary Search based solution here.
Consider mid column and find maximum element in it.Let index of mid column be ‘mid’, value of maximum element in mid column be ‘max’ and maximum element be at ‘mat[max_index][mid]’. If max >= A[index][mid-1] & max >= A[index][pick+1], max is a peak, return max.If max < mat[max_index][mid-1], recur for left half of matrix.If max < mat[max_index][mid+1], recur for right half of matrix.
Consider mid column and find maximum element in it.
Let index of mid column be ‘mid’, value of maximum element in mid column be ‘max’ and maximum element be at ‘mat[max_index][mid]’.
If max >= A[index][mid-1] & max >= A[index][pick+1], max is a peak, return max.
If max < mat[max_index][mid-1], recur for left half of matrix.
If max < mat[max_index][mid+1], recur for right half of matrix.
Below is the implementation of above algorithm:
C++
Java
Python3
C#
Javascript
// Finding peak element in a 2D Array.#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find the maximum in column 'mid'// 'rows' is number of rows.int findMax(int arr[][MAX], int rows, int mid, int& max){ int max_index = 0; for (int i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; max_index = i; } } return max_index;} // Function to find a peak elementint findPeakRec(int arr[][MAX], int rows, int columns, int mid){ // Evaluating maximum of mid column. Note max is // passed by reference. int max = 0; int max_index = findMax(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index][mid - 1] && max >= arr[max_index][mid + 1]) return max; // If max is less than its left if (max < arr[max_index][mid - 1]) return findPeakRec(arr, rows, columns, mid - ceil((double)mid / 2)); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, mid + ceil((double)mid / 2));} // A wrapper over findPeakRec()int findPeak(int arr[][MAX], int rows, int columns){ return findPeakRec(arr, rows, columns, columns / 2);} // Driver Codeint main(){ int arr[][MAX] = { { 10, 8, 10, 10 }, { 14, 13, 12, 11 }, { 15, 9, 11, 21 }, { 16, 17, 19, 20 } }; // Number of Columns int rows = 4, columns = 4; cout << findPeak(arr, rows, columns); return 0;}
// Finding peak element in a 2D Array.class GFG{ static int MAX = 100; // Function to find the maximum in column // 'mid', 'rows' is number of rows. static int findMax(int[][] arr, int rows, int mid, int max) { int max_index = 0; for (int i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; max_index = i; } } return max_index; } // Function to change the value of [max] static int Max(int[][] arr, int rows, int mid, int max) { for (int i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; } } return max; } // Function to find a peak element static int findPeakRec(int[][] arr, int rows, int columns, int mid) { // Evaluating maximum of mid column. // Note max is passed by reference. int max = 0; int max_index = findMax(arr, rows, mid, max); max = Max(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index][mid - 1] && max >= arr[max_index][mid + 1]) return max; // If max is less than its left if (max < arr[max_index][mid - 1]) return findPeakRec(arr, rows, columns, (int)(mid - Math.ceil((double) mid / 2))); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, (int)(mid + Math.ceil((double) mid / 2))); } // A wrapper over findPeakRec() static int findPeak(int[][] arr, int rows, int columns) { return findPeakRec(arr, rows, columns, columns / 2); } // Driver Code public static void main(String[] args) { int[][] arr = {{ 10, 8, 10, 10 }, { 14, 13, 12, 11 }, { 15, 9, 11, 21 }, { 16, 17, 19, 20 }}; // Number of Columns int rows = 4, columns = 4; System.out.println(findPeak(arr, rows, columns)); }} // This code is contributed by// sanjeev2552
# Finding peak element in a 2D Array.MAX = 100from math import ceil # Function to find the maximum in column 'mid'# 'rows' is number of rows.def findMax(arr, rows, mid,max): max_index = 0 for i in range(rows): if (max < arr[i][mid]): # Saving global maximum and its index # to check its neighbours max = arr[i][mid] max_index = i #print(max_index) return max,max_index # Function to find a peak elementdef findPeakRec(arr, rows, columns,mid): # Evaluating maximum of mid column. # Note max is passed by reference. max = 0 max, max_index = findMax(arr, rows, mid, max) # If we are on the first or last column, # max is a peak if (mid == 0 or mid == columns - 1): return max # If mid column maximum is also peak if (max >= arr[max_index][mid - 1] and max >= arr[max_index][mid + 1]): return max # If max is less than its left if (max < arr[max_index][mid - 1]): return findPeakRec(arr, rows, columns, mid - ceil(mid / 2.0)) # If max is less than its left # if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, mid + ceil(mid / 2.0)) # A wrapper over findPeakRec()def findPeak(arr, rows, columns): return findPeakRec(arr, rows, columns, columns // 2) # Driver Codearr = [ [ 10, 8, 10, 10 ], [ 14, 13, 12, 11 ], [ 15, 9, 11, 21 ], [ 16, 17, 19, 20 ] ] # Number of Columnsrows = 4columns = 4print(findPeak(arr, rows, columns)) # This code is contributed by Mohit Kumar
// Finding peak element in a 2D Array.using System; class GFG{ // Function to find the maximum in column // 'mid', 'rows' is number of rows. static int findMax(int[,] arr, int rows, int mid, int max) { int max_index = 0; for (int i = 0; i < rows; i++) { if (max < arr[i,mid]) { // Saving global maximum and its // index to check its neighbours max = arr[i,mid]; max_index = i; } } return max_index; } // Function to change the value of [max] static int Max(int[,] arr, int rows, int mid, int max) { for (int i = 0; i < rows; i++) { if (max < arr[i, mid]) { // Saving global maximum and its // index to check its neighbours max = arr[i, mid]; } } return max; } // Function to find a peak element static int findPeakRec(int[,] arr, int rows, int columns, int mid) { // Evaluating maximum of mid column. // Note max is passed by reference. int max = 0; int max_index = findMax(arr, rows, mid, max); max = Max(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index, mid - 1] && max >= arr[max_index, mid + 1]) return max; // If max is less than its left if (max < arr[max_index,mid - 1]) return findPeakRec(arr, rows, columns, (int)(mid - Math.Ceiling((double) mid / 2))); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, (int)(mid + Math.Ceiling((double) mid / 2))); } // A wrapper over findPeakRec() static int findPeak(int[,] arr, int rows, int columns) { return findPeakRec(arr, rows, columns, columns / 2); } // Driver Code static public void Main () { int[,] arr = {{ 10, 8, 10, 10 }, { 14, 13, 12, 11 }, { 15, 9, 11, 21 }, { 16, 17, 19, 20 }}; // Number of Columns int rows = 4, columns = 4; Console.Write(findPeak(arr, rows, columns)); }} // This code is contributed by ajit.
<script> // Finding peak element in a 2D Array. let MAX = 100; // Function to find the maximum in column // 'mid', 'rows' is number of rows. function findMax(arr, rows, mid, max) { let max_index = 0; for (let i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; max_index = i; } } return max_index; } // Function to change the value of [max] function Max(arr, rows, mid, max) { for (let i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; } } return max; } // Function to find a peak element function findPeakRec(arr, rows, columns, mid) { // Evaluating maximum of mid column. // Note max is passed by reference. let max = 0; let max_index = findMax(arr, rows, mid, max); max = Max(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index][mid - 1] && max >= arr[max_index][mid + 1]) return max; // If max is less than its left if (max < arr[max_index][mid - 1]) return findPeakRec(arr, rows, columns, (mid - Math.ceil(mid / 2))); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, (mid + Math.ceil(mid / 2))); } // A wrapper over findPeakRec() function findPeak(arr, rows, columns) { return findPeakRec(arr, rows, columns, parseInt(columns / 2, 10)); } let arr = [[ 10, 8, 10, 10 ], [ 14, 13, 12, 11 ], [ 15, 9, 11, 21 ], [ 16, 17, 19, 20 ]]; // Number of Columns let rows = 4, columns = 4; document.write(findPeak(arr, rows, columns)); </script>
Output:
21
Time Complexity : O(rows * log(columns)). We recur for half the number of columns. In every recursive call, we linearly search for the maximum in the current mid column.Auxiliary Space: O(columns/2) for Recursion Call Stack Source: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/MIT6_006F11_lec01.pdf
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Nikhil Gupta 18
mohit kumar 29
sanjeev2552
jit_t
mukesh07
Binary Search
Divide and Conquer
Matrix
Divide and Conquer
Matrix
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program for Tower of Hanoi
Divide and Conquer Algorithm | Introduction
Median of two sorted arrays of different sizes
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Write a program to calculate pow(x,n)
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2 | [
{
"code": null,
"e": 25146,
"s": 25118,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 25436,
"s": 25146,
"text": "An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. For example neighbors for A[i][j] are A[i-1][j], A[i+1][j], A[i][j-1] and A[i][j+1]. For corner elements, missing neighbors are considered of negative infinite value.Examples: "
},
{
"code": null,
"e": 25650,
"s": 25436,
"text": "Input : 10 20 15\n 21 30 14\n 7 16 32 \nOutput : 30\n30 is a peak element because all its \nneighbors are smaller or equal to it. \n32 can also be picked as a peak.\n\nInput : 10 7\n 11 17\nOutput : 17"
},
{
"code": null,
"e": 26307,
"s": 25652,
"text": "Below are some facts about this problem: 1: A Diagonal adjacent is not considered as neighbor. 2: A peak element is not necessarily the maximal element. 3: More than one such elements can exist. 4: There is always a peak element. We can see this property by creating some matrices using pen and paper.Method 1: (Brute Force) Iterate through all the elements of Matrix and check if it is greater/equal to all its neighbors. If yes, return the element.Time Complexity: O(rows * columns) Auxiliary Space: O(1)Method 2 : (Efficient) This problem is mainly an extension of Find a peak element in 1D array. We apply similar Binary Search based solution here. "
},
{
"code": null,
"e": 26695,
"s": 26307,
"text": "Consider mid column and find maximum element in it.Let index of mid column be ‘mid’, value of maximum element in mid column be ‘max’ and maximum element be at ‘mat[max_index][mid]’. If max >= A[index][mid-1] & max >= A[index][pick+1], max is a peak, return max.If max < mat[max_index][mid-1], recur for left half of matrix.If max < mat[max_index][mid+1], recur for right half of matrix."
},
{
"code": null,
"e": 26747,
"s": 26695,
"text": "Consider mid column and find maximum element in it."
},
{
"code": null,
"e": 26880,
"s": 26747,
"text": "Let index of mid column be ‘mid’, value of maximum element in mid column be ‘max’ and maximum element be at ‘mat[max_index][mid]’. "
},
{
"code": null,
"e": 26960,
"s": 26880,
"text": "If max >= A[index][mid-1] & max >= A[index][pick+1], max is a peak, return max."
},
{
"code": null,
"e": 27023,
"s": 26960,
"text": "If max < mat[max_index][mid-1], recur for left half of matrix."
},
{
"code": null,
"e": 27087,
"s": 27023,
"text": "If max < mat[max_index][mid+1], recur for right half of matrix."
},
{
"code": null,
"e": 27137,
"s": 27087,
"text": "Below is the implementation of above algorithm: "
},
{
"code": null,
"e": 27141,
"s": 27137,
"text": "C++"
},
{
"code": null,
"e": 27146,
"s": 27141,
"text": "Java"
},
{
"code": null,
"e": 27154,
"s": 27146,
"text": "Python3"
},
{
"code": null,
"e": 27157,
"s": 27154,
"text": "C#"
},
{
"code": null,
"e": 27168,
"s": 27157,
"text": "Javascript"
},
{
"code": "// Finding peak element in a 2D Array.#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find the maximum in column 'mid'// 'rows' is number of rows.int findMax(int arr[][MAX], int rows, int mid, int& max){ int max_index = 0; for (int i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; max_index = i; } } return max_index;} // Function to find a peak elementint findPeakRec(int arr[][MAX], int rows, int columns, int mid){ // Evaluating maximum of mid column. Note max is // passed by reference. int max = 0; int max_index = findMax(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index][mid - 1] && max >= arr[max_index][mid + 1]) return max; // If max is less than its left if (max < arr[max_index][mid - 1]) return findPeakRec(arr, rows, columns, mid - ceil((double)mid / 2)); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, mid + ceil((double)mid / 2));} // A wrapper over findPeakRec()int findPeak(int arr[][MAX], int rows, int columns){ return findPeakRec(arr, rows, columns, columns / 2);} // Driver Codeint main(){ int arr[][MAX] = { { 10, 8, 10, 10 }, { 14, 13, 12, 11 }, { 15, 9, 11, 21 }, { 16, 17, 19, 20 } }; // Number of Columns int rows = 4, columns = 4; cout << findPeak(arr, rows, columns); return 0;}",
"e": 28934,
"s": 27168,
"text": null
},
{
"code": "// Finding peak element in a 2D Array.class GFG{ static int MAX = 100; // Function to find the maximum in column // 'mid', 'rows' is number of rows. static int findMax(int[][] arr, int rows, int mid, int max) { int max_index = 0; for (int i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; max_index = i; } } return max_index; } // Function to change the value of [max] static int Max(int[][] arr, int rows, int mid, int max) { for (int i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; } } return max; } // Function to find a peak element static int findPeakRec(int[][] arr, int rows, int columns, int mid) { // Evaluating maximum of mid column. // Note max is passed by reference. int max = 0; int max_index = findMax(arr, rows, mid, max); max = Max(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index][mid - 1] && max >= arr[max_index][mid + 1]) return max; // If max is less than its left if (max < arr[max_index][mid - 1]) return findPeakRec(arr, rows, columns, (int)(mid - Math.ceil((double) mid / 2))); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, (int)(mid + Math.ceil((double) mid / 2))); } // A wrapper over findPeakRec() static int findPeak(int[][] arr, int rows, int columns) { return findPeakRec(arr, rows, columns, columns / 2); } // Driver Code public static void main(String[] args) { int[][] arr = {{ 10, 8, 10, 10 }, { 14, 13, 12, 11 }, { 15, 9, 11, 21 }, { 16, 17, 19, 20 }}; // Number of Columns int rows = 4, columns = 4; System.out.println(findPeak(arr, rows, columns)); }} // This code is contributed by// sanjeev2552",
"e": 31556,
"s": 28934,
"text": null
},
{
"code": "# Finding peak element in a 2D Array.MAX = 100from math import ceil # Function to find the maximum in column 'mid'# 'rows' is number of rows.def findMax(arr, rows, mid,max): max_index = 0 for i in range(rows): if (max < arr[i][mid]): # Saving global maximum and its index # to check its neighbours max = arr[i][mid] max_index = i #print(max_index) return max,max_index # Function to find a peak elementdef findPeakRec(arr, rows, columns,mid): # Evaluating maximum of mid column. # Note max is passed by reference. max = 0 max, max_index = findMax(arr, rows, mid, max) # If we are on the first or last column, # max is a peak if (mid == 0 or mid == columns - 1): return max # If mid column maximum is also peak if (max >= arr[max_index][mid - 1] and max >= arr[max_index][mid + 1]): return max # If max is less than its left if (max < arr[max_index][mid - 1]): return findPeakRec(arr, rows, columns, mid - ceil(mid / 2.0)) # If max is less than its left # if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, mid + ceil(mid / 2.0)) # A wrapper over findPeakRec()def findPeak(arr, rows, columns): return findPeakRec(arr, rows, columns, columns // 2) # Driver Codearr = [ [ 10, 8, 10, 10 ], [ 14, 13, 12, 11 ], [ 15, 9, 11, 21 ], [ 16, 17, 19, 20 ] ] # Number of Columnsrows = 4columns = 4print(findPeak(arr, rows, columns)) # This code is contributed by Mohit Kumar",
"e": 33186,
"s": 31556,
"text": null
},
{
"code": "// Finding peak element in a 2D Array.using System; class GFG{ // Function to find the maximum in column // 'mid', 'rows' is number of rows. static int findMax(int[,] arr, int rows, int mid, int max) { int max_index = 0; for (int i = 0; i < rows; i++) { if (max < arr[i,mid]) { // Saving global maximum and its // index to check its neighbours max = arr[i,mid]; max_index = i; } } return max_index; } // Function to change the value of [max] static int Max(int[,] arr, int rows, int mid, int max) { for (int i = 0; i < rows; i++) { if (max < arr[i, mid]) { // Saving global maximum and its // index to check its neighbours max = arr[i, mid]; } } return max; } // Function to find a peak element static int findPeakRec(int[,] arr, int rows, int columns, int mid) { // Evaluating maximum of mid column. // Note max is passed by reference. int max = 0; int max_index = findMax(arr, rows, mid, max); max = Max(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index, mid - 1] && max >= arr[max_index, mid + 1]) return max; // If max is less than its left if (max < arr[max_index,mid - 1]) return findPeakRec(arr, rows, columns, (int)(mid - Math.Ceiling((double) mid / 2))); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, (int)(mid + Math.Ceiling((double) mid / 2))); } // A wrapper over findPeakRec() static int findPeak(int[,] arr, int rows, int columns) { return findPeakRec(arr, rows, columns, columns / 2); } // Driver Code static public void Main () { int[,] arr = {{ 10, 8, 10, 10 }, { 14, 13, 12, 11 }, { 15, 9, 11, 21 }, { 16, 17, 19, 20 }}; // Number of Columns int rows = 4, columns = 4; Console.Write(findPeak(arr, rows, columns)); }} // This code is contributed by ajit.",
"e": 35811,
"s": 33186,
"text": null
},
{
"code": "<script> // Finding peak element in a 2D Array. let MAX = 100; // Function to find the maximum in column // 'mid', 'rows' is number of rows. function findMax(arr, rows, mid, max) { let max_index = 0; for (let i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; max_index = i; } } return max_index; } // Function to change the value of [max] function Max(arr, rows, mid, max) { for (let i = 0; i < rows; i++) { if (max < arr[i][mid]) { // Saving global maximum and its index // to check its neighbours max = arr[i][mid]; } } return max; } // Function to find a peak element function findPeakRec(arr, rows, columns, mid) { // Evaluating maximum of mid column. // Note max is passed by reference. let max = 0; let max_index = findMax(arr, rows, mid, max); max = Max(arr, rows, mid, max); // If we are on the first or last column, // max is a peak if (mid == 0 || mid == columns - 1) return max; // If mid column maximum is also peak if (max >= arr[max_index][mid - 1] && max >= arr[max_index][mid + 1]) return max; // If max is less than its left if (max < arr[max_index][mid - 1]) return findPeakRec(arr, rows, columns, (mid - Math.ceil(mid / 2))); // If max is less than its left // if (max < arr[max_index][mid+1]) return findPeakRec(arr, rows, columns, (mid + Math.ceil(mid / 2))); } // A wrapper over findPeakRec() function findPeak(arr, rows, columns) { return findPeakRec(arr, rows, columns, parseInt(columns / 2, 10)); } let arr = [[ 10, 8, 10, 10 ], [ 14, 13, 12, 11 ], [ 15, 9, 11, 21 ], [ 16, 17, 19, 20 ]]; // Number of Columns let rows = 4, columns = 4; document.write(findPeak(arr, rows, columns)); </script>",
"e": 38100,
"s": 35811,
"text": null
},
{
"code": null,
"e": 38110,
"s": 38100,
"text": "Output: "
},
{
"code": null,
"e": 38113,
"s": 38110,
"text": "21"
},
{
"code": null,
"e": 38497,
"s": 38113,
"text": "Time Complexity : O(rows * log(columns)). We recur for half the number of columns. In every recursive call, we linearly search for the maximum in the current mid column.Auxiliary Space: O(columns/2) for Recursion Call Stack Source: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/MIT6_006F11_lec01.pdf"
},
{
"code": null,
"e": 38920,
"s": 38497,
"text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 38936,
"s": 38920,
"text": "Nikhil Gupta 18"
},
{
"code": null,
"e": 38951,
"s": 38936,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 38963,
"s": 38951,
"text": "sanjeev2552"
},
{
"code": null,
"e": 38969,
"s": 38963,
"text": "jit_t"
},
{
"code": null,
"e": 38978,
"s": 38969,
"text": "mukesh07"
},
{
"code": null,
"e": 38992,
"s": 38978,
"text": "Binary Search"
},
{
"code": null,
"e": 39011,
"s": 38992,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 39018,
"s": 39011,
"text": "Matrix"
},
{
"code": null,
"e": 39037,
"s": 39018,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 39044,
"s": 39037,
"text": "Matrix"
},
{
"code": null,
"e": 39058,
"s": 39044,
"text": "Binary Search"
},
{
"code": null,
"e": 39156,
"s": 39058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39165,
"s": 39156,
"text": "Comments"
},
{
"code": null,
"e": 39178,
"s": 39165,
"text": "Old Comments"
},
{
"code": null,
"e": 39205,
"s": 39178,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 39249,
"s": 39205,
"text": "Divide and Conquer Algorithm | Introduction"
},
{
"code": null,
"e": 39296,
"s": 39249,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 39358,
"s": 39296,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 39396,
"s": 39358,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 39431,
"s": 39396,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 39475,
"s": 39431,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 39511,
"s": 39475,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 39535,
"s": 39511,
"text": "Sudoku | Backtracking-7"
}
] |
Python | Column deletion from list of lists - GeeksforGeeks | 26 Feb, 2019
The problem of removing a row from a list is quite simple and we just need to pop a list out of list of lists. But there can be a utility where we need to delete a column i.e particular index element of each of the list. This is problem that can occur if we store any database data into containers. Let’s discuss certain ways in which this can be performed.
Method #1 : Using del + loopIn this strategy, we just delete the column element one by one using a loop to iterate the row number at each of the iteration.
# Python3 code to demonstrate # deleting columns of list of lists# using del + loop # initializing list test_list = [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]] # printing original listprint ("The original list is : " + str(test_list)) # using del + loop# deleting column element of rowfor j in test_list: del j[1] # printing result print ("The modified mesh after column deletion : " + str(test_list))
Output :
The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]]The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]
Method #2 : Using pop() + list comprehensionWe can do this particular task in an easier and shorter way using the list comprehension technique and using the pop function which can be used to remove the list element.
# Python3 code to demonstrate # deleting columns of list of lists# using pop() + list comprehension # initializing list test_list = [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]] # printing original listprint ("The original list is : " + str(test_list)) # using pop() + list comprehension# deleting column element of row[j.pop(1) for j in test_list] # printing result print ("The modified mesh after column deletion : " + str(test_list))
Output :
The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]]The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary | [
{
"code": null,
"e": 25048,
"s": 25020,
"text": "\n26 Feb, 2019"
},
{
"code": null,
"e": 25406,
"s": 25048,
"text": "The problem of removing a row from a list is quite simple and we just need to pop a list out of list of lists. But there can be a utility where we need to delete a column i.e particular index element of each of the list. This is problem that can occur if we store any database data into containers. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 25562,
"s": 25406,
"text": "Method #1 : Using del + loopIn this strategy, we just delete the column element one by one using a loop to iterate the row number at each of the iteration."
},
{
"code": "# Python3 code to demonstrate # deleting columns of list of lists# using del + loop # initializing list test_list = [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]] # printing original listprint (\"The original list is : \" + str(test_list)) # using del + loop# deleting column element of rowfor j in test_list: del j[1] # printing result print (\"The modified mesh after column deletion : \" + str(test_list))",
"e": 26000,
"s": 25562,
"text": null
},
{
"code": null,
"e": 26009,
"s": 26000,
"text": "Output :"
},
{
"code": null,
"e": 26159,
"s": 26009,
"text": "The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]]The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]"
},
{
"code": null,
"e": 26377,
"s": 26161,
"text": "Method #2 : Using pop() + list comprehensionWe can do this particular task in an easier and shorter way using the list comprehension technique and using the pop function which can be used to remove the list element."
},
{
"code": "# Python3 code to demonstrate # deleting columns of list of lists# using pop() + list comprehension # initializing list test_list = [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]] # printing original listprint (\"The original list is : \" + str(test_list)) # using pop() + list comprehension# deleting column element of row[j.pop(1) for j in test_list] # printing result print (\"The modified mesh after column deletion : \" + str(test_list))",
"e": 26845,
"s": 26377,
"text": null
},
{
"code": null,
"e": 26854,
"s": 26845,
"text": "Output :"
},
{
"code": null,
"e": 27004,
"s": 26854,
"text": "The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]]The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]"
},
{
"code": null,
"e": 27025,
"s": 27004,
"text": "Python list-programs"
},
{
"code": null,
"e": 27032,
"s": 27025,
"text": "Python"
},
{
"code": null,
"e": 27048,
"s": 27032,
"text": "Python Programs"
},
{
"code": null,
"e": 27146,
"s": 27048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27155,
"s": 27146,
"text": "Comments"
},
{
"code": null,
"e": 27168,
"s": 27155,
"text": "Old Comments"
},
{
"code": null,
"e": 27186,
"s": 27168,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27221,
"s": 27186,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27243,
"s": 27221,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27275,
"s": 27243,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27305,
"s": 27275,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27348,
"s": 27305,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27370,
"s": 27348,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27416,
"s": 27370,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27455,
"s": 27416,
"text": "Python | Get dictionary keys as a list"
}
] |
Building a Naive Bayes Machine Learning Model to Classify Text | by Aden Haussmann | Towards Data Science | Natural Language Processing (NLP) is an extremely exciting field. It lies at the confluence of computer science, linguistics and artificial intelligence, and is concerned with the interaction between human language and computers. More specifically: its goal is to understand how to program computers to understand and interpret our natural language.
It’s a very hot area of research right now, and I’m fortunate enough to be attending one of the universities at the absolute forefront of this research. Although as a lowly undergrad, I’m not exposed to this cutting-edge work often — as if I would understand it if I was!
Nonetheless, building models to classify natural language is relatively straightforward. It’s a cool exercise because it’s relevant. This is a very real application of ML that you could use in your own projects.
One of the simpler supervised Bayesian Network models, the Naive Bayes algorithm is a probabilistic classifier based on Bayes’ Theorem (which you might remember from high school statistics). But its simplicity doesn’t make it a poor choice, it can produce highly accurate predictions even when the dataset is not very large (just a few thousand samples).
If you’re really new to Machine Learning, I suggest reading some of my articles on more basic algorithms, and then coming back to this one, as I will be building upon concepts that are explained in detail in those.
towardsdatascience.com
Essentially, the conditional probabilities of the occurrence of two events are computed, based on the conditional probabilities of each individual event. So, the probability of each tag for a given piece of text is calculated, and the tag with the highest probability is outputted.
There are other suitable options as well, such as Support Vector Machine (SVM), which takes more time and computational resources to work, but will produce more accurate predictions than Naive Bayes. Alternatively, you might consider a Deep Learning approach based on neural networks, but this would require far more training data.
This is the approach:
Import and setup the data.Do some analysis to learn more about the data landscape.Create our dependent and independent variable lists for training and validation.Encode the labels.Extract features from the descriptions.Fit the data to the model.Check the model’s accuracy.
Import and setup the data.
Do some analysis to learn more about the data landscape.
Create our dependent and independent variable lists for training and validation.
Encode the labels.
Extract features from the descriptions.
Fit the data to the model.
Check the model’s accuracy.
What this project will demonstrate is classifying bank transactions into categories based on their descriptions. My dataset, which contains 12500 samples, includes other features like the transaction amount and transaction type, and you can use as many features as you want in your model — even do some feature selection to see which ones have the highest impact on the predictions — but for the sake of simplicity, we’ll just use the descriptions.
In my dataset, the descriptions are things like:
citylink1Jul19 OYSTERtravelodge6Jul19 RINGGOSUNDRY DEBIT CONTACTLESS CAMDEN PARKINGstgcoachtrainlineFin: CMT UK LTD Cash at Transact
Of course, start with the imports.
Pandas for creating dataframes.Scikit-Learn for label encoding, feature extraction, modelling and measuring success metrics
Pandas for creating dataframes.
Scikit-Learn for label encoding, feature extraction, modelling and measuring success metrics
import pandas as pdfrom sklearn.preprocessing import LabelEncoderfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn import naive_bayes, metrics
Next, let’s process the csv files and get them ready for the model. (Of curse, you may not be working with csv files, just import whatever data you have into a Pandas dataframe):
features = pd.read_csv("bank_transaction_features.csv")labels = pd.read_csv("bank_transaction_labels.csv")
I have two datasets: one with features, one with labels (categories). These are their respective columns:
bank_transaction_features:bank_transaction_id, bank_transaction_amount, bank_transaction_typebank_transaction_labels:bank_transaction_id, bank_transaction_category, bank_transaction_dataset
They have in common, an ID column. So I’ll merge them on this column and delete any rows with null entries (in my data there are very few — you should calculate how many — so removing them will have negligible effect on the predictions):
combined_df = pd.merge(left=features, right=labels)combined_df = combined_df.dropna()
Always begin with some exploratory data analysis. My dataset has thousands of samples, I can’t see what all the categories are just by scanning it. We need to do some simple things to gain a better understanding of the data.
This dataset has a column that designates whether a sample is for training or validating. This will come in handy later as we won’t need to create our own train/validate split. But for exploratory analysis, we can drop this column (taking to only drop the column from a new dataframe variable which we will create, retaining the one with this column).
explore_df = combined_df.drop(labels=['bank_transaction_dataset'], axis=1)
We can easily see what categories are present in the data as well as how many samples there are in each category:
print(explore_df['bank_transaction_category'].value_counts())
The result:
ACCOMMODATION_AND_MEALS 3765TRAVEL 3166BANK_OR_FINANCE_CHARGES 2659MOTOR_EXPENSES 1609INSURANCE 1170Name: bank_transaction_category, dtype: int64
Now let’s just check what the train/validate split is (using the dataframe which still has the relevant column):
train_set = combined_df.loc[combined_df["bank_transaction_dataset"] == "TRAIN"]val_set = combined_df.loc[combined_df["bank_transaction_dataset"] == "VAL"]len_train = len(train_set)len_val = len(val_set)len_whole = len(explore_df)print('Amount of training data: ', len_train)print('Amount of validation data: ', len_val)
Output:
Amount of training data: 9891Amount of validation data: 2478
Which makes the train/validate split 80/20, a good ratio, so no need to adjust that at all.
Finally, the fun bit. First, create the x and y training and validating subsets. We can accomplish this by creating lists containing only the data in the relevant columns:
y_train = train_set['bank_transaction_category'].valuesx_train = train_set['bank_transaction_description'].valuesy_val = val_set['bank_transaction_category'].valuesx_val = val_set['bank_transaction_description'].values
Now it gets really interesting. The thing to keep in mind is that ML models don’t “understand” text and words. They understand numbers. Therefore, the first thing that needs to be done to prepare the data to be fitted to the model, is to encode the labels. All that means, is assigning a number to each label. For example:
ACCOMMODATION_AND_MEALS => 0TRAVEL => 1BANK_OR_FINANCE_CHARGES => 2MOTOR_EXPENSES => 3INSURANCE => 4
This is accomplished by creating a LabelEncoder object and using its fit_transform function on the dependent variable data (y):
label_encoder = LabelEncoder()y_train = label_encoder.fit_transform(y_train)y_test = label_encoder.fit_transform(y_val)
The same goes for the description data, except this is a little more complicated. In some models, where you have a set number of uniform descriptions and you know what they are, you can just encode each one to an integer and they’re ready to go. But here, each transaction description is potentially unique.
The solution is to extract features from the text and turn those into vectors that can be understood by the model.
Although technically complicated, this can be implemented simply, by using the CountVectorizer to convert the texts into a matrix of tokens and transforming the training and validation independent variable (x):
count_vector = CountVectorizer(analyzer='word', token_pattern=r'\w{1,}')count_vector.fit(combined_df['bank_transaction_description'])x_train_count = count_vector.transform(x_train)x_valid_count = count_vector.transform(x_val)
And that’s it! We can fit the data, train the model and make predictions:
classifier = naive_bayes.MultinomialNB()classifier.fit(x_train_count, y_train)predictions = classifier.predict(x_valid_count)
There are several metrics you can use to determine how well the model is working. We’ll use accuracy. this will tell us how often the model is correctly predicting the category of the bank transactions:
print(metrics.accuracy_score(predictions, y_test))
The accuracy for this model was:
0.91
Not bad at all.
This was a fun example because it was tangible. Classifying bank transactions into categories in, for example, a mobile finance tracking app, is a very real use case for this algorithm. I hope you gained a good high level understanding of how Naive Bayes works, and how to implement it for classifying text, specifically.
If you did learn something, have any more questions, think I missed anything important, or are planning to use this algorithm in a project of your own, let me know by leaving a response and we can discuss it.
Happy coding!
Scikit Learn sklearn.preprocessing.LabelEncoder https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html
Scikit Learn sklearn.feature_extraction.text.CountVectorizer https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
Wikipedia Natural Language Processing https://en.wikipedia.org/wiki/Natural_language_processing
MonkeyLearn Text Classification https://monkeylearn.com/text-classification/ | [
{
"code": null,
"e": 522,
"s": 172,
"text": "Natural Language Processing (NLP) is an extremely exciting field. It lies at the confluence of computer science, linguistics and artificial intelligence, and is concerned with the interaction between human language and computers. More specifically: its goal is to understand how to program computers to understand and interpret our natural language."
},
{
"code": null,
"e": 794,
"s": 522,
"text": "It’s a very hot area of research right now, and I’m fortunate enough to be attending one of the universities at the absolute forefront of this research. Although as a lowly undergrad, I’m not exposed to this cutting-edge work often — as if I would understand it if I was!"
},
{
"code": null,
"e": 1006,
"s": 794,
"text": "Nonetheless, building models to classify natural language is relatively straightforward. It’s a cool exercise because it’s relevant. This is a very real application of ML that you could use in your own projects."
},
{
"code": null,
"e": 1361,
"s": 1006,
"text": "One of the simpler supervised Bayesian Network models, the Naive Bayes algorithm is a probabilistic classifier based on Bayes’ Theorem (which you might remember from high school statistics). But its simplicity doesn’t make it a poor choice, it can produce highly accurate predictions even when the dataset is not very large (just a few thousand samples)."
},
{
"code": null,
"e": 1576,
"s": 1361,
"text": "If you’re really new to Machine Learning, I suggest reading some of my articles on more basic algorithms, and then coming back to this one, as I will be building upon concepts that are explained in detail in those."
},
{
"code": null,
"e": 1599,
"s": 1576,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1881,
"s": 1599,
"text": "Essentially, the conditional probabilities of the occurrence of two events are computed, based on the conditional probabilities of each individual event. So, the probability of each tag for a given piece of text is calculated, and the tag with the highest probability is outputted."
},
{
"code": null,
"e": 2213,
"s": 1881,
"text": "There are other suitable options as well, such as Support Vector Machine (SVM), which takes more time and computational resources to work, but will produce more accurate predictions than Naive Bayes. Alternatively, you might consider a Deep Learning approach based on neural networks, but this would require far more training data."
},
{
"code": null,
"e": 2235,
"s": 2213,
"text": "This is the approach:"
},
{
"code": null,
"e": 2508,
"s": 2235,
"text": "Import and setup the data.Do some analysis to learn more about the data landscape.Create our dependent and independent variable lists for training and validation.Encode the labels.Extract features from the descriptions.Fit the data to the model.Check the model’s accuracy."
},
{
"code": null,
"e": 2535,
"s": 2508,
"text": "Import and setup the data."
},
{
"code": null,
"e": 2592,
"s": 2535,
"text": "Do some analysis to learn more about the data landscape."
},
{
"code": null,
"e": 2673,
"s": 2592,
"text": "Create our dependent and independent variable lists for training and validation."
},
{
"code": null,
"e": 2692,
"s": 2673,
"text": "Encode the labels."
},
{
"code": null,
"e": 2732,
"s": 2692,
"text": "Extract features from the descriptions."
},
{
"code": null,
"e": 2759,
"s": 2732,
"text": "Fit the data to the model."
},
{
"code": null,
"e": 2787,
"s": 2759,
"text": "Check the model’s accuracy."
},
{
"code": null,
"e": 3236,
"s": 2787,
"text": "What this project will demonstrate is classifying bank transactions into categories based on their descriptions. My dataset, which contains 12500 samples, includes other features like the transaction amount and transaction type, and you can use as many features as you want in your model — even do some feature selection to see which ones have the highest impact on the predictions — but for the sake of simplicity, we’ll just use the descriptions."
},
{
"code": null,
"e": 3285,
"s": 3236,
"text": "In my dataset, the descriptions are things like:"
},
{
"code": null,
"e": 3419,
"s": 3285,
"text": "citylink1Jul19 OYSTERtravelodge6Jul19 RINGGOSUNDRY DEBIT CONTACTLESS CAMDEN PARKINGstgcoachtrainlineFin: CMT UK LTD Cash at Transact"
},
{
"code": null,
"e": 3454,
"s": 3419,
"text": "Of course, start with the imports."
},
{
"code": null,
"e": 3578,
"s": 3454,
"text": "Pandas for creating dataframes.Scikit-Learn for label encoding, feature extraction, modelling and measuring success metrics"
},
{
"code": null,
"e": 3610,
"s": 3578,
"text": "Pandas for creating dataframes."
},
{
"code": null,
"e": 3703,
"s": 3610,
"text": "Scikit-Learn for label encoding, feature extraction, modelling and measuring success metrics"
},
{
"code": null,
"e": 3868,
"s": 3703,
"text": "import pandas as pdfrom sklearn.preprocessing import LabelEncoderfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn import naive_bayes, metrics"
},
{
"code": null,
"e": 4047,
"s": 3868,
"text": "Next, let’s process the csv files and get them ready for the model. (Of curse, you may not be working with csv files, just import whatever data you have into a Pandas dataframe):"
},
{
"code": null,
"e": 4154,
"s": 4047,
"text": "features = pd.read_csv(\"bank_transaction_features.csv\")labels = pd.read_csv(\"bank_transaction_labels.csv\")"
},
{
"code": null,
"e": 4260,
"s": 4154,
"text": "I have two datasets: one with features, one with labels (categories). These are their respective columns:"
},
{
"code": null,
"e": 4450,
"s": 4260,
"text": "bank_transaction_features:bank_transaction_id, bank_transaction_amount, bank_transaction_typebank_transaction_labels:bank_transaction_id, bank_transaction_category, bank_transaction_dataset"
},
{
"code": null,
"e": 4688,
"s": 4450,
"text": "They have in common, an ID column. So I’ll merge them on this column and delete any rows with null entries (in my data there are very few — you should calculate how many — so removing them will have negligible effect on the predictions):"
},
{
"code": null,
"e": 4774,
"s": 4688,
"text": "combined_df = pd.merge(left=features, right=labels)combined_df = combined_df.dropna()"
},
{
"code": null,
"e": 4999,
"s": 4774,
"text": "Always begin with some exploratory data analysis. My dataset has thousands of samples, I can’t see what all the categories are just by scanning it. We need to do some simple things to gain a better understanding of the data."
},
{
"code": null,
"e": 5351,
"s": 4999,
"text": "This dataset has a column that designates whether a sample is for training or validating. This will come in handy later as we won’t need to create our own train/validate split. But for exploratory analysis, we can drop this column (taking to only drop the column from a new dataframe variable which we will create, retaining the one with this column)."
},
{
"code": null,
"e": 5426,
"s": 5351,
"text": "explore_df = combined_df.drop(labels=['bank_transaction_dataset'], axis=1)"
},
{
"code": null,
"e": 5540,
"s": 5426,
"text": "We can easily see what categories are present in the data as well as how many samples there are in each category:"
},
{
"code": null,
"e": 5602,
"s": 5540,
"text": "print(explore_df['bank_transaction_category'].value_counts())"
},
{
"code": null,
"e": 5614,
"s": 5602,
"text": "The result:"
},
{
"code": null,
"e": 5815,
"s": 5614,
"text": "ACCOMMODATION_AND_MEALS 3765TRAVEL 3166BANK_OR_FINANCE_CHARGES 2659MOTOR_EXPENSES 1609INSURANCE 1170Name: bank_transaction_category, dtype: int64"
},
{
"code": null,
"e": 5928,
"s": 5815,
"text": "Now let’s just check what the train/validate split is (using the dataframe which still has the relevant column):"
},
{
"code": null,
"e": 6248,
"s": 5928,
"text": "train_set = combined_df.loc[combined_df[\"bank_transaction_dataset\"] == \"TRAIN\"]val_set = combined_df.loc[combined_df[\"bank_transaction_dataset\"] == \"VAL\"]len_train = len(train_set)len_val = len(val_set)len_whole = len(explore_df)print('Amount of training data: ', len_train)print('Amount of validation data: ', len_val)"
},
{
"code": null,
"e": 6256,
"s": 6248,
"text": "Output:"
},
{
"code": null,
"e": 6319,
"s": 6256,
"text": "Amount of training data: 9891Amount of validation data: 2478"
},
{
"code": null,
"e": 6411,
"s": 6319,
"text": "Which makes the train/validate split 80/20, a good ratio, so no need to adjust that at all."
},
{
"code": null,
"e": 6583,
"s": 6411,
"text": "Finally, the fun bit. First, create the x and y training and validating subsets. We can accomplish this by creating lists containing only the data in the relevant columns:"
},
{
"code": null,
"e": 6802,
"s": 6583,
"text": "y_train = train_set['bank_transaction_category'].valuesx_train = train_set['bank_transaction_description'].valuesy_val = val_set['bank_transaction_category'].valuesx_val = val_set['bank_transaction_description'].values"
},
{
"code": null,
"e": 7125,
"s": 6802,
"text": "Now it gets really interesting. The thing to keep in mind is that ML models don’t “understand” text and words. They understand numbers. Therefore, the first thing that needs to be done to prepare the data to be fitted to the model, is to encode the labels. All that means, is assigning a number to each label. For example:"
},
{
"code": null,
"e": 7281,
"s": 7125,
"text": "ACCOMMODATION_AND_MEALS => 0TRAVEL => 1BANK_OR_FINANCE_CHARGES => 2MOTOR_EXPENSES => 3INSURANCE => 4"
},
{
"code": null,
"e": 7409,
"s": 7281,
"text": "This is accomplished by creating a LabelEncoder object and using its fit_transform function on the dependent variable data (y):"
},
{
"code": null,
"e": 7529,
"s": 7409,
"text": "label_encoder = LabelEncoder()y_train = label_encoder.fit_transform(y_train)y_test = label_encoder.fit_transform(y_val)"
},
{
"code": null,
"e": 7837,
"s": 7529,
"text": "The same goes for the description data, except this is a little more complicated. In some models, where you have a set number of uniform descriptions and you know what they are, you can just encode each one to an integer and they’re ready to go. But here, each transaction description is potentially unique."
},
{
"code": null,
"e": 7952,
"s": 7837,
"text": "The solution is to extract features from the text and turn those into vectors that can be understood by the model."
},
{
"code": null,
"e": 8163,
"s": 7952,
"text": "Although technically complicated, this can be implemented simply, by using the CountVectorizer to convert the texts into a matrix of tokens and transforming the training and validation independent variable (x):"
},
{
"code": null,
"e": 8389,
"s": 8163,
"text": "count_vector = CountVectorizer(analyzer='word', token_pattern=r'\\w{1,}')count_vector.fit(combined_df['bank_transaction_description'])x_train_count = count_vector.transform(x_train)x_valid_count = count_vector.transform(x_val)"
},
{
"code": null,
"e": 8463,
"s": 8389,
"text": "And that’s it! We can fit the data, train the model and make predictions:"
},
{
"code": null,
"e": 8589,
"s": 8463,
"text": "classifier = naive_bayes.MultinomialNB()classifier.fit(x_train_count, y_train)predictions = classifier.predict(x_valid_count)"
},
{
"code": null,
"e": 8792,
"s": 8589,
"text": "There are several metrics you can use to determine how well the model is working. We’ll use accuracy. this will tell us how often the model is correctly predicting the category of the bank transactions:"
},
{
"code": null,
"e": 8843,
"s": 8792,
"text": "print(metrics.accuracy_score(predictions, y_test))"
},
{
"code": null,
"e": 8876,
"s": 8843,
"text": "The accuracy for this model was:"
},
{
"code": null,
"e": 8881,
"s": 8876,
"text": "0.91"
},
{
"code": null,
"e": 8897,
"s": 8881,
"text": "Not bad at all."
},
{
"code": null,
"e": 9219,
"s": 8897,
"text": "This was a fun example because it was tangible. Classifying bank transactions into categories in, for example, a mobile finance tracking app, is a very real use case for this algorithm. I hope you gained a good high level understanding of how Naive Bayes works, and how to implement it for classifying text, specifically."
},
{
"code": null,
"e": 9428,
"s": 9219,
"text": "If you did learn something, have any more questions, think I missed anything important, or are planning to use this algorithm in a project of your own, let me know by leaving a response and we can discuss it."
},
{
"code": null,
"e": 9442,
"s": 9428,
"text": "Happy coding!"
},
{
"code": null,
"e": 9580,
"s": 9442,
"text": "Scikit Learn sklearn.preprocessing.LabelEncoder https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html"
},
{
"code": null,
"e": 9744,
"s": 9580,
"text": "Scikit Learn sklearn.feature_extraction.text.CountVectorizer https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html"
},
{
"code": null,
"e": 9840,
"s": 9744,
"text": "Wikipedia Natural Language Processing https://en.wikipedia.org/wiki/Natural_language_processing"
}
] |
Find if a string is interleaved of two other strings | DP-33 - GeeksforGeeks | 29 Mar, 2022
Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. C is said to be interleaving A and B, if it contains all and only characters of A and B and order of all characters in individual strings is preserved.
Example:
Input: strings: "XXXXZY", "XXY", "XXZ"
Output: XXXXZY is interleaved of XXY and XXZ
The string XXXXZY can be made by
interleaving XXY and XXZ
String: XXXXZY
String 1: XX Y
String 2: XX Z
Input: strings: "XXY", "YX", "X"
Output: XXY is not interleaved of YX and X
XXY cannot be formed by interleaving YX and X.
The strings that can be formed are YXX and XYX
Simple Solution: Recursion. Approach: A simple solution is discussed here: Check whether a given string is an interleaving of two other given string. The simple solution doesn’t work if the strings A and B have some common characters. For example, let the given string be A and the other strings be B and C. Let A = “XXY”, string B = “XXZ” and string C = “XXZXXXY”. Create a recursive function that takes parameters A, B, and C. To handle all cases, two possibilities need to be considered.
If the first character of C matches the first character of A, we move one character ahead in A and C and recursively check.If the first character of C matches the first character of B, we move one character ahead in B and C and recursively check.
If the first character of C matches the first character of A, we move one character ahead in A and C and recursively check.
If the first character of C matches the first character of B, we move one character ahead in B and C and recursively check.
If any of the above function returns true or A, B and C are empty then return true else return false.Thanks to Frederic for suggesting this approach.
C
// A simple recursive function to check// whether C is an interleaving of A and Bbool isInterleaved( char* A, char* B, char* C){ // Base Case: If all strings are empty if (!(*A || *B || *C)) return true; // If C is empty and any of the // two strings is not empty if (*C == '\0') return false; // If any of the above mentioned // two possibilities is true, // then return true, otherwise false return ((*C == *A) && isInterleaved( A + 1, B, C + 1)) || ((*C == *B) && isInterleaved( A, B + 1, C + 1));}
Complexity Analysis:
Time Complexity: O(2^n), where n is the length of the given string. We need to iterate the whole string only once hence this is possible in O(n).
Space Complexity: O(1). The space complexity is constant.
Efficient Solution: Dynamic Programming. Approach: The above recursive solution certainly has many overlapping sub-problems. For example, if we consider A = “XXX”, B = “XXX” and C = “XXXXXX” and draw a recursion tree, there will be many overlapping subproblems. Therefore, like any other typical Dynamic Programming problems, we can solve it by creating a table and store results of sub-problems in a bottom-up manner. The top-down approach of the above solution can be modified by adding a Hash Map.
Algorithm:
Create a DP array (matrix) of size M*N, where m is the size of the first string and n is the size of the second string. Initialize the matrix to false.If the sum of sizes of smaller strings is not equal to the size of the larger string then return false and break the array as they cant be the interleaved to form the larger string.Run a nested loop the outer loop from 0 to m and the inner loop from 0 to n. Loop counters are i and j.If the values of i and j are both zeroes then mark dp[i][j] as true. If the value of i is zero and j is non zero and the j-1 character of B is equal to j-1 character of C the assign dp[i][j] as dp[i][j-1] and similarly if j is 0 then match i-1 th character of C and A and if it matches then assign dp[i][j] as dp[i-1][j].Take three characters x, y, z as (i-1)th character of A and (j-1)th character of B and (i + j – 1)th character of C.if x matches with z and y does not match with z then assign dp[i][j] as dp[i-1][j] similarly if x is not equal to z and y is equal to z then assign dp[i][j] as dp[i][j-1]if x is equal to y and y is equal to z then assign dp[i][j] as bitwise OR of dp[i][j-1] and dp[i-1][j].return value of dp[m][n].
Create a DP array (matrix) of size M*N, where m is the size of the first string and n is the size of the second string. Initialize the matrix to false.
If the sum of sizes of smaller strings is not equal to the size of the larger string then return false and break the array as they cant be the interleaved to form the larger string.
Run a nested loop the outer loop from 0 to m and the inner loop from 0 to n. Loop counters are i and j.
If the values of i and j are both zeroes then mark dp[i][j] as true. If the value of i is zero and j is non zero and the j-1 character of B is equal to j-1 character of C the assign dp[i][j] as dp[i][j-1] and similarly if j is 0 then match i-1 th character of C and A and if it matches then assign dp[i][j] as dp[i-1][j].
Take three characters x, y, z as (i-1)th character of A and (j-1)th character of B and (i + j – 1)th character of C.
if x matches with z and y does not match with z then assign dp[i][j] as dp[i-1][j] similarly if x is not equal to z and y is equal to z then assign dp[i][j] as dp[i][j-1]
if x is equal to y and y is equal to z then assign dp[i][j] as bitwise OR of dp[i][j-1] and dp[i-1][j].
return value of dp[m][n].
Thanks to Abhinav Ramana for suggesting this method of implementation.
C++
Java
Python3
C#
Javascript
// A Dynamic Programming based program// to check whether a string C is// an interleaving of two other// strings A and B.#include <iostream>#include <string.h>using namespace std; // The main function that// returns true if C is// an interleaving of A// and B, otherwise false.bool isInterleaved( char* A, char* B, char* C){ // Find lengths of the two strings int M = strlen(A), N = strlen(B); // Let us create a 2D table // to store solutions of // subproblems. C[i][j] will // be true if C[0..i+j-1] // is an interleaving of // A[0..i-1] and B[0..j-1]. bool IL[M + 1][N + 1]; // Initialize all values as false. memset(IL, 0, sizeof(IL)); // C can be an interleaving of // A and B only of the sum // of lengths of A & B is equal // to the length of C. if ((M + N) != strlen(C)) return false; // Process all characters of A and B for (int i = 0; i <= M; ++i) { for (int j = 0; j <= N; ++j) { // two empty strings have an // empty string as interleaving if (i == 0 && j == 0) IL[i][j] = true; // A is empty else if (i == 0) { if (B[j - 1] == C[j - 1]) IL[i][j] = IL[i][j - 1]; } // B is empty else if (j == 0) { if (A[i - 1] == C[i - 1]) IL[i][j] = IL[i - 1][j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character of B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] != C[i + j - 1]) IL[i][j] = IL[i - 1][j]; // Current character of C matches // with current character of B, // but doesn't match with current // character of A else if ( A[i - 1] != C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = IL[i][j - 1]; // Current character of C matches // with that of both A and B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = (IL[i - 1][j] || IL[i][j - 1]); } } return IL[M][N];} // A function to run test casesvoid test(char* A, char* B, char* C){ if (isInterleaved(A, B, C)) cout << C << " is interleaved of " << A << " and " << B << endl; else cout << C << " is not interleaved of " << A << " and " << B << endl;} // Driver program to test above functionsint main(){ test("XXY", "XXZ", "XXZXXXY"); test("XY", "WZ", "WZXY"); test("XY", "X", "XXY"); test("YX", "X", "XXY"); test("XXY", "XXZ", "XXXXZY"); return 0;}
// A Dynamic Programming based program// to check whether a string C is// an interleaving of two other// strings A and B.import java.io.*;import java.util.*;import java.lang.*; class GFG{ // The main function that returns// true if C is an interleaving of A// and B, otherwise false. static boolean isInterleaved(String A, String B, String C){ // Find lengths of the two strings int M = A.length(), N = B.length(); // Let us create a 2D table to store // solutions of subproblems. C[i][j] // will be true if C[0..i+j-1] is an // interleaving of A[0..i-1] and B[0..j-1]. boolean IL[][] = new boolean[M + 1][N + 1]; // IL is default initialised by false // C can be an interleaving of A and B // only if the sum of lengths of A and B // is equal to length of C if ((M + N) != C.length()) return false; // Process all characters of A and B for(int i = 0; i <= M; i++) { for(int j = 0; j <= N; j++) { // Two empty strings have an // empty strings as interleaving if (i == 0 && j == 0) IL[i][j] = true; // A is empty else if (i == 0) { if (B.charAt(j - 1) == C.charAt(j - 1)) IL[i][j] = IL[i][j - 1]; } // B is empty else if (j == 0) { if (A.charAt(i - 1) == C.charAt(i - 1)) IL[i][j] = IL[i - 1][j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character if B else if (A.charAt(i - 1) == C.charAt(i + j - 1) && B.charAt(j - 1) != C.charAt(i + j - 1)) IL[i][j] = IL[i - 1][j]; // Current character of C matches // with current character of B, but // doesn't match with current // character if A else if (A.charAt(i - 1) != C.charAt(i + j - 1) && B.charAt(j - 1) == C.charAt(i + j - 1)) IL[i][j] = IL[i][j - 1]; // Current character of C matches // with that of both A and B else if (A.charAt(i - 1) == C.charAt(i + j - 1) && B.charAt(j - 1) == C.charAt(i + j - 1)) IL[i][j] = (IL[i - 1][j] || IL[i][j - 1]); } } return IL[M][N];} // Function to run test casesstatic void test(String A, String B, String C){ if (isInterleaved(A, B, C)) System.out.println(C + " is interleaved of " + A + " and " + B); else System.out.println(C + " is not interleaved of " + A + " and " + B);} // Driver codepublic static void main(String[] args){ test("XXY", "XXZ", "XXZXXXY"); test("XY", "WZ", "WZXY"); test("XY", "X", "XXY"); test("YX", "X", "XXY"); test("XXY", "XXZ", "XXXXZY");}} // This code is contributed by th_aditi
# A Dynamic Programming based python3 program# to check whether a string C is an interleaving# of two other strings A and B. # The main function that returns true if C is# an interleaving of A and B, otherwise false.def isInterleaved(A, B, C): # Find lengths of the two strings M = len(A) N = len(B) # Let us create a 2D table to store solutions of # subproblems. C[i][j] will be true if C[0..i + j-1] # is an interleaving of A[0..i-1] and B[0..j-1]. # Initialize all values as false. IL = [[False] * (N + 1) for i in range(M + 1)] # C can be an interleaving of A and B only of sum # of lengths of A & B is equal to length of C. if ((M + N) != len(C)): return False # Process all characters of A and B for i in range(0, M + 1): for j in range(0, N + 1): # two empty strings have an empty string # as interleaving if (i == 0 and j == 0): IL[i][j] = True # A is empty elif (i == 0): if (B[j - 1] == C[j - 1]): IL[i][j] = IL[i][j - 1] # B is empty elif (j == 0): if (A[i - 1] == C[i - 1]): IL[i][j] = IL[i - 1][j] # Current character of C matches with # current character of A, but doesn't match # with current character of B elif (A[i - 1] == C[i + j - 1] and B[j - 1] != C[i + j - 1]): IL[i][j] = IL[i - 1][j] # Current character of C matches with # current character of B, but doesn't match # with current character of A elif (A[i - 1] != C[i + j - 1] and B[j - 1] == C[i + j - 1]): IL[i][j] = IL[i][j - 1] # Current character of C matches with # that of both A and B elif (A[i - 1] == C[i + j - 1] and B[j - 1] == C[i + j - 1]): IL[i][j] = (IL[i - 1][j] or IL[i][j - 1]) return IL[M][N] # A function to run test casesdef test(A, B, C): if (isInterleaved(A, B, C)): print(C, "is interleaved of", A, "and", B) else: print(C, "is not interleaved of", A, "and", B) # Driver Codeif __name__ == '__main__': test("XXY", "XXZ", "XXZXXXY") test("XY", "WZ", "WZXY") test("XY", "X", "XXY") test("YX", "X", "XXY") test("XXY", "XXZ", "XXXXZY") # This code is contributed by ashutosh450
// A Dynamic Programming based program // to check whether a string C is // an interleaving of two other // strings A and B.using System;class GFG{ // The main function that returns // true if C is an interleaving of A // and B, otherwise false. static bool isInterleaved(string A, string B, string C) { // Find lengths of the two strings int M = A.Length, N = B.Length; // Let us create a 2D table to store // solutions of subproblems. C[i][j] // will be true if C[0..i+j-1] is an // interleaving of A[0..i-1] and B[0..j-1]. bool[ , ] IL = new bool[M + 1, N + 1]; // IL is default initialised by false // C can be an interleaving of A and B // only if the sum of lengths of A and B // is equal to length of C if ((M + N) != C.Length) return false; // Process all characters of A and B for(int i = 0; i <= M; i++) { for(int j = 0; j <= N; j++) { // Two empty strings have an // empty strings as interleaving if (i == 0 && j == 0) IL[i, j] = true; // A is empty else if (i == 0) { if (B[j - 1] == C[j - 1]) IL[i, j] = IL[i, j - 1]; } // B is empty else if (j == 0) { if (A[i - 1] == C[i - 1]) IL[i, j] = IL[i - 1, j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character if B else if (A[i - 1] == C[i + j - 1] && B[j - 1] != C[i + j - 1]) IL[i, j] = IL[i - 1, j]; // Current character of C matches // with current character of B, but // doesn't match with current // character if A else if (A[i - 1] != C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i, j] = IL[i, j - 1]; // Current character of C matches // with that of both A and B else if (A[i - 1] == C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i, j] = (IL[i - 1, j] || IL[i, j - 1]); } } return IL[M, N]; } // Function to run test cases static void test(string A, string B, string C) { if (isInterleaved(A, B, C)) Console.WriteLine(C + " is interleaved of " + A + " and " + B); else Console.WriteLine(C + " is not interleaved of " + A + " and " + B); } // Driver code static void Main() { test("XXY", "XXZ", "XXZXXXY"); test("XY", "WZ", "WZXY"); test("XY", "X", "XXY"); test("YX", "X", "XXY"); test("XXY", "XXZ", "XXXXZY"); }} // This code is contributed by divyeshrabadiya07
<script> // A Dynamic Programming based program// to check whether a string C is// an interleaving of two other// strings A and B. // The main function that// returns true if C is// an interleaving of A// and B, otherwise false.function isInterleaved(A, B, C){ // Find lengths of the two strings let M = A.length, N = B.length; // Let us create a 2D table // to store solutions of // subproblems. C[i][j] will // be true if C[0..i+j-1] // is an interleaving of // A[0..i-1] and B[0..j-1]. // Initialize all values as false. let IL = new Array(M + 1); for(let i=0;i<M+1;i++){ IL[i] = new Array(N + 1).fill(0); } // C can be an interleaving of // A and B only of the sum // of lengths of A & B is equal // to the length of C. if ((M + N) != C.length) return false; // Process all characters of A and B for (let i = 0; i <= M; ++i) { for (let j = 0; j <= N; ++j) { // two empty strings have an // empty string as interleaving if (i == 0 && j == 0) IL[i][j] = true; // A is empty else if (i == 0) { if (B[j - 1] == C[j - 1]) IL[i][j] = IL[i][j - 1]; } // B is empty else if (j == 0) { if (A[i - 1] == C[i - 1]) IL[i][j] = IL[i - 1][j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character of B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] != C[i + j - 1]) IL[i][j] = IL[i - 1][j]; // Current character of C matches // with current character of B, // but doesn't match with current // character of A else if ( A[i - 1] != C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = IL[i][j - 1]; // Current character of C matches // with that of both A and B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = (IL[i - 1][j] || IL[i][j - 1]); } } return IL[M][N];} // A function to run test casesfunction test(A, B, C){ if (isInterleaved(A, B, C)) document.write(C + " is interleaved of " + A + " and " + B,"</br>"); else document.write(C + " is not interleaved of " + A + " and " + B,"</br>");} // Driver program to test above functions test("XXY", "XXZ", "XXZXXXY");test("XY", "WZ", "WZXY");test("XY", "X", "XXY");test("YX", "X", "XXY");test("XXY", "XXZ", "XXXXZY"); // This code is contributed by shinjanpatra</script>
Output:
XXZXXXY is not interleaved of XXY and XXZ
WZXY is interleaved of XY and WZ
XXY is interleaved of XY and X
XXY is not interleaved of YX and X
XXXXZY is interleaved of XXY and XXZ
See this for more test cases.Complexity Analysis:
Time Complexity: O(M*N). Since a traversal of DP array is needed, so the time complexity is O(M*N).
Space Complexity: O(M*N). This is the space required to store the DP array.
https://youtu.be/WBXy-sztEwI Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gp6
ankita91994
ashutosh450
andrew1234
psyduck
divyeshrabadiya07
kashisharora4110
roho
janmanshh
ajaysingh37
prasunroy212
surinderdawra388
shinjanpatra
simmytarika5
prashantchandelme
FactSet
Google
Microsoft
Yahoo
Zillious
Dynamic Programming
Strings
Microsoft
FactSet
Google
Zillious
Yahoo
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Palindromic Substring | Set 1
Subset Sum Problem | DP-25
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 24680,
"s": 24652,
"text": "\n29 Mar, 2022"
},
{
"code": null,
"e": 24935,
"s": 24680,
"text": "Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. C is said to be interleaving A and B, if it contains all and only characters of A and B and order of all characters in individual strings is preserved. "
},
{
"code": null,
"e": 24945,
"s": 24935,
"text": "Example: "
},
{
"code": null,
"e": 25312,
"s": 24945,
"text": "Input: strings: \"XXXXZY\", \"XXY\", \"XXZ\"\nOutput: XXXXZY is interleaved of XXY and XXZ\nThe string XXXXZY can be made by \ninterleaving XXY and XXZ\nString: XXXXZY\nString 1: XX Y\nString 2: XX Z\n\nInput: strings: \"XXY\", \"YX\", \"X\"\nOutput: XXY is not interleaved of YX and X\nXXY cannot be formed by interleaving YX and X.\nThe strings that can be formed are YXX and XYX"
},
{
"code": null,
"e": 25803,
"s": 25312,
"text": "Simple Solution: Recursion. Approach: A simple solution is discussed here: Check whether a given string is an interleaving of two other given string. The simple solution doesn’t work if the strings A and B have some common characters. For example, let the given string be A and the other strings be B and C. Let A = “XXY”, string B = “XXZ” and string C = “XXZXXXY”. Create a recursive function that takes parameters A, B, and C. To handle all cases, two possibilities need to be considered."
},
{
"code": null,
"e": 26050,
"s": 25803,
"text": "If the first character of C matches the first character of A, we move one character ahead in A and C and recursively check.If the first character of C matches the first character of B, we move one character ahead in B and C and recursively check."
},
{
"code": null,
"e": 26174,
"s": 26050,
"text": "If the first character of C matches the first character of A, we move one character ahead in A and C and recursively check."
},
{
"code": null,
"e": 26298,
"s": 26174,
"text": "If the first character of C matches the first character of B, we move one character ahead in B and C and recursively check."
},
{
"code": null,
"e": 26448,
"s": 26298,
"text": "If any of the above function returns true or A, B and C are empty then return true else return false.Thanks to Frederic for suggesting this approach."
},
{
"code": null,
"e": 26450,
"s": 26448,
"text": "C"
},
{
"code": "// A simple recursive function to check// whether C is an interleaving of A and Bbool isInterleaved( char* A, char* B, char* C){ // Base Case: If all strings are empty if (!(*A || *B || *C)) return true; // If C is empty and any of the // two strings is not empty if (*C == '\\0') return false; // If any of the above mentioned // two possibilities is true, // then return true, otherwise false return ((*C == *A) && isInterleaved( A + 1, B, C + 1)) || ((*C == *B) && isInterleaved( A, B + 1, C + 1));}",
"e": 27069,
"s": 26450,
"text": null
},
{
"code": null,
"e": 27091,
"s": 27069,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 27237,
"s": 27091,
"text": "Time Complexity: O(2^n), where n is the length of the given string. We need to iterate the whole string only once hence this is possible in O(n)."
},
{
"code": null,
"e": 27295,
"s": 27237,
"text": "Space Complexity: O(1). The space complexity is constant."
},
{
"code": null,
"e": 27796,
"s": 27295,
"text": "Efficient Solution: Dynamic Programming. Approach: The above recursive solution certainly has many overlapping sub-problems. For example, if we consider A = “XXX”, B = “XXX” and C = “XXXXXX” and draw a recursion tree, there will be many overlapping subproblems. Therefore, like any other typical Dynamic Programming problems, we can solve it by creating a table and store results of sub-problems in a bottom-up manner. The top-down approach of the above solution can be modified by adding a Hash Map."
},
{
"code": null,
"e": 27808,
"s": 27796,
"text": "Algorithm: "
},
{
"code": null,
"e": 28979,
"s": 27808,
"text": "Create a DP array (matrix) of size M*N, where m is the size of the first string and n is the size of the second string. Initialize the matrix to false.If the sum of sizes of smaller strings is not equal to the size of the larger string then return false and break the array as they cant be the interleaved to form the larger string.Run a nested loop the outer loop from 0 to m and the inner loop from 0 to n. Loop counters are i and j.If the values of i and j are both zeroes then mark dp[i][j] as true. If the value of i is zero and j is non zero and the j-1 character of B is equal to j-1 character of C the assign dp[i][j] as dp[i][j-1] and similarly if j is 0 then match i-1 th character of C and A and if it matches then assign dp[i][j] as dp[i-1][j].Take three characters x, y, z as (i-1)th character of A and (j-1)th character of B and (i + j – 1)th character of C.if x matches with z and y does not match with z then assign dp[i][j] as dp[i-1][j] similarly if x is not equal to z and y is equal to z then assign dp[i][j] as dp[i][j-1]if x is equal to y and y is equal to z then assign dp[i][j] as bitwise OR of dp[i][j-1] and dp[i-1][j].return value of dp[m][n]."
},
{
"code": null,
"e": 29131,
"s": 28979,
"text": "Create a DP array (matrix) of size M*N, where m is the size of the first string and n is the size of the second string. Initialize the matrix to false."
},
{
"code": null,
"e": 29313,
"s": 29131,
"text": "If the sum of sizes of smaller strings is not equal to the size of the larger string then return false and break the array as they cant be the interleaved to form the larger string."
},
{
"code": null,
"e": 29417,
"s": 29313,
"text": "Run a nested loop the outer loop from 0 to m and the inner loop from 0 to n. Loop counters are i and j."
},
{
"code": null,
"e": 29739,
"s": 29417,
"text": "If the values of i and j are both zeroes then mark dp[i][j] as true. If the value of i is zero and j is non zero and the j-1 character of B is equal to j-1 character of C the assign dp[i][j] as dp[i][j-1] and similarly if j is 0 then match i-1 th character of C and A and if it matches then assign dp[i][j] as dp[i-1][j]."
},
{
"code": null,
"e": 29856,
"s": 29739,
"text": "Take three characters x, y, z as (i-1)th character of A and (j-1)th character of B and (i + j – 1)th character of C."
},
{
"code": null,
"e": 30027,
"s": 29856,
"text": "if x matches with z and y does not match with z then assign dp[i][j] as dp[i-1][j] similarly if x is not equal to z and y is equal to z then assign dp[i][j] as dp[i][j-1]"
},
{
"code": null,
"e": 30131,
"s": 30027,
"text": "if x is equal to y and y is equal to z then assign dp[i][j] as bitwise OR of dp[i][j-1] and dp[i-1][j]."
},
{
"code": null,
"e": 30157,
"s": 30131,
"text": "return value of dp[m][n]."
},
{
"code": null,
"e": 30229,
"s": 30157,
"text": "Thanks to Abhinav Ramana for suggesting this method of implementation. "
},
{
"code": null,
"e": 30233,
"s": 30229,
"text": "C++"
},
{
"code": null,
"e": 30238,
"s": 30233,
"text": "Java"
},
{
"code": null,
"e": 30246,
"s": 30238,
"text": "Python3"
},
{
"code": null,
"e": 30249,
"s": 30246,
"text": "C#"
},
{
"code": null,
"e": 30260,
"s": 30249,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based program// to check whether a string C is// an interleaving of two other// strings A and B.#include <iostream>#include <string.h>using namespace std; // The main function that// returns true if C is// an interleaving of A// and B, otherwise false.bool isInterleaved( char* A, char* B, char* C){ // Find lengths of the two strings int M = strlen(A), N = strlen(B); // Let us create a 2D table // to store solutions of // subproblems. C[i][j] will // be true if C[0..i+j-1] // is an interleaving of // A[0..i-1] and B[0..j-1]. bool IL[M + 1][N + 1]; // Initialize all values as false. memset(IL, 0, sizeof(IL)); // C can be an interleaving of // A and B only of the sum // of lengths of A & B is equal // to the length of C. if ((M + N) != strlen(C)) return false; // Process all characters of A and B for (int i = 0; i <= M; ++i) { for (int j = 0; j <= N; ++j) { // two empty strings have an // empty string as interleaving if (i == 0 && j == 0) IL[i][j] = true; // A is empty else if (i == 0) { if (B[j - 1] == C[j - 1]) IL[i][j] = IL[i][j - 1]; } // B is empty else if (j == 0) { if (A[i - 1] == C[i - 1]) IL[i][j] = IL[i - 1][j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character of B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] != C[i + j - 1]) IL[i][j] = IL[i - 1][j]; // Current character of C matches // with current character of B, // but doesn't match with current // character of A else if ( A[i - 1] != C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = IL[i][j - 1]; // Current character of C matches // with that of both A and B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = (IL[i - 1][j] || IL[i][j - 1]); } } return IL[M][N];} // A function to run test casesvoid test(char* A, char* B, char* C){ if (isInterleaved(A, B, C)) cout << C << \" is interleaved of \" << A << \" and \" << B << endl; else cout << C << \" is not interleaved of \" << A << \" and \" << B << endl;} // Driver program to test above functionsint main(){ test(\"XXY\", \"XXZ\", \"XXZXXXY\"); test(\"XY\", \"WZ\", \"WZXY\"); test(\"XY\", \"X\", \"XXY\"); test(\"YX\", \"X\", \"XXY\"); test(\"XXY\", \"XXZ\", \"XXXXZY\"); return 0;}",
"e": 33124,
"s": 30260,
"text": null
},
{
"code": "// A Dynamic Programming based program// to check whether a string C is// an interleaving of two other// strings A and B.import java.io.*;import java.util.*;import java.lang.*; class GFG{ // The main function that returns// true if C is an interleaving of A// and B, otherwise false. static boolean isInterleaved(String A, String B, String C){ // Find lengths of the two strings int M = A.length(), N = B.length(); // Let us create a 2D table to store // solutions of subproblems. C[i][j] // will be true if C[0..i+j-1] is an // interleaving of A[0..i-1] and B[0..j-1]. boolean IL[][] = new boolean[M + 1][N + 1]; // IL is default initialised by false // C can be an interleaving of A and B // only if the sum of lengths of A and B // is equal to length of C if ((M + N) != C.length()) return false; // Process all characters of A and B for(int i = 0; i <= M; i++) { for(int j = 0; j <= N; j++) { // Two empty strings have an // empty strings as interleaving if (i == 0 && j == 0) IL[i][j] = true; // A is empty else if (i == 0) { if (B.charAt(j - 1) == C.charAt(j - 1)) IL[i][j] = IL[i][j - 1]; } // B is empty else if (j == 0) { if (A.charAt(i - 1) == C.charAt(i - 1)) IL[i][j] = IL[i - 1][j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character if B else if (A.charAt(i - 1) == C.charAt(i + j - 1) && B.charAt(j - 1) != C.charAt(i + j - 1)) IL[i][j] = IL[i - 1][j]; // Current character of C matches // with current character of B, but // doesn't match with current // character if A else if (A.charAt(i - 1) != C.charAt(i + j - 1) && B.charAt(j - 1) == C.charAt(i + j - 1)) IL[i][j] = IL[i][j - 1]; // Current character of C matches // with that of both A and B else if (A.charAt(i - 1) == C.charAt(i + j - 1) && B.charAt(j - 1) == C.charAt(i + j - 1)) IL[i][j] = (IL[i - 1][j] || IL[i][j - 1]); } } return IL[M][N];} // Function to run test casesstatic void test(String A, String B, String C){ if (isInterleaved(A, B, C)) System.out.println(C + \" is interleaved of \" + A + \" and \" + B); else System.out.println(C + \" is not interleaved of \" + A + \" and \" + B);} // Driver codepublic static void main(String[] args){ test(\"XXY\", \"XXZ\", \"XXZXXXY\"); test(\"XY\", \"WZ\", \"WZXY\"); test(\"XY\", \"X\", \"XXY\"); test(\"YX\", \"X\", \"XXY\"); test(\"XXY\", \"XXZ\", \"XXXXZY\");}} // This code is contributed by th_aditi",
"e": 36346,
"s": 33124,
"text": null
},
{
"code": "# A Dynamic Programming based python3 program# to check whether a string C is an interleaving# of two other strings A and B. # The main function that returns true if C is# an interleaving of A and B, otherwise false.def isInterleaved(A, B, C): # Find lengths of the two strings M = len(A) N = len(B) # Let us create a 2D table to store solutions of # subproblems. C[i][j] will be true if C[0..i + j-1] # is an interleaving of A[0..i-1] and B[0..j-1]. # Initialize all values as false. IL = [[False] * (N + 1) for i in range(M + 1)] # C can be an interleaving of A and B only of sum # of lengths of A & B is equal to length of C. if ((M + N) != len(C)): return False # Process all characters of A and B for i in range(0, M + 1): for j in range(0, N + 1): # two empty strings have an empty string # as interleaving if (i == 0 and j == 0): IL[i][j] = True # A is empty elif (i == 0): if (B[j - 1] == C[j - 1]): IL[i][j] = IL[i][j - 1] # B is empty elif (j == 0): if (A[i - 1] == C[i - 1]): IL[i][j] = IL[i - 1][j] # Current character of C matches with # current character of A, but doesn't match # with current character of B elif (A[i - 1] == C[i + j - 1] and B[j - 1] != C[i + j - 1]): IL[i][j] = IL[i - 1][j] # Current character of C matches with # current character of B, but doesn't match # with current character of A elif (A[i - 1] != C[i + j - 1] and B[j - 1] == C[i + j - 1]): IL[i][j] = IL[i][j - 1] # Current character of C matches with # that of both A and B elif (A[i - 1] == C[i + j - 1] and B[j - 1] == C[i + j - 1]): IL[i][j] = (IL[i - 1][j] or IL[i][j - 1]) return IL[M][N] # A function to run test casesdef test(A, B, C): if (isInterleaved(A, B, C)): print(C, \"is interleaved of\", A, \"and\", B) else: print(C, \"is not interleaved of\", A, \"and\", B) # Driver Codeif __name__ == '__main__': test(\"XXY\", \"XXZ\", \"XXZXXXY\") test(\"XY\", \"WZ\", \"WZXY\") test(\"XY\", \"X\", \"XXY\") test(\"YX\", \"X\", \"XXY\") test(\"XXY\", \"XXZ\", \"XXXXZY\") # This code is contributed by ashutosh450",
"e": 38848,
"s": 36346,
"text": null
},
{
"code": "// A Dynamic Programming based program // to check whether a string C is // an interleaving of two other // strings A and B.using System;class GFG{ // The main function that returns // true if C is an interleaving of A // and B, otherwise false. static bool isInterleaved(string A, string B, string C) { // Find lengths of the two strings int M = A.Length, N = B.Length; // Let us create a 2D table to store // solutions of subproblems. C[i][j] // will be true if C[0..i+j-1] is an // interleaving of A[0..i-1] and B[0..j-1]. bool[ , ] IL = new bool[M + 1, N + 1]; // IL is default initialised by false // C can be an interleaving of A and B // only if the sum of lengths of A and B // is equal to length of C if ((M + N) != C.Length) return false; // Process all characters of A and B for(int i = 0; i <= M; i++) { for(int j = 0; j <= N; j++) { // Two empty strings have an // empty strings as interleaving if (i == 0 && j == 0) IL[i, j] = true; // A is empty else if (i == 0) { if (B[j - 1] == C[j - 1]) IL[i, j] = IL[i, j - 1]; } // B is empty else if (j == 0) { if (A[i - 1] == C[i - 1]) IL[i, j] = IL[i - 1, j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character if B else if (A[i - 1] == C[i + j - 1] && B[j - 1] != C[i + j - 1]) IL[i, j] = IL[i - 1, j]; // Current character of C matches // with current character of B, but // doesn't match with current // character if A else if (A[i - 1] != C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i, j] = IL[i, j - 1]; // Current character of C matches // with that of both A and B else if (A[i - 1] == C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i, j] = (IL[i - 1, j] || IL[i, j - 1]); } } return IL[M, N]; } // Function to run test cases static void test(string A, string B, string C) { if (isInterleaved(A, B, C)) Console.WriteLine(C + \" is interleaved of \" + A + \" and \" + B); else Console.WriteLine(C + \" is not interleaved of \" + A + \" and \" + B); } // Driver code static void Main() { test(\"XXY\", \"XXZ\", \"XXZXXXY\"); test(\"XY\", \"WZ\", \"WZXY\"); test(\"XY\", \"X\", \"XXY\"); test(\"YX\", \"X\", \"XXY\"); test(\"XXY\", \"XXZ\", \"XXXXZY\"); }} // This code is contributed by divyeshrabadiya07",
"e": 42135,
"s": 38848,
"text": null
},
{
"code": "<script> // A Dynamic Programming based program// to check whether a string C is// an interleaving of two other// strings A and B. // The main function that// returns true if C is// an interleaving of A// and B, otherwise false.function isInterleaved(A, B, C){ // Find lengths of the two strings let M = A.length, N = B.length; // Let us create a 2D table // to store solutions of // subproblems. C[i][j] will // be true if C[0..i+j-1] // is an interleaving of // A[0..i-1] and B[0..j-1]. // Initialize all values as false. let IL = new Array(M + 1); for(let i=0;i<M+1;i++){ IL[i] = new Array(N + 1).fill(0); } // C can be an interleaving of // A and B only of the sum // of lengths of A & B is equal // to the length of C. if ((M + N) != C.length) return false; // Process all characters of A and B for (let i = 0; i <= M; ++i) { for (let j = 0; j <= N; ++j) { // two empty strings have an // empty string as interleaving if (i == 0 && j == 0) IL[i][j] = true; // A is empty else if (i == 0) { if (B[j - 1] == C[j - 1]) IL[i][j] = IL[i][j - 1]; } // B is empty else if (j == 0) { if (A[i - 1] == C[i - 1]) IL[i][j] = IL[i - 1][j]; } // Current character of C matches // with current character of A, // but doesn't match with current // character of B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] != C[i + j - 1]) IL[i][j] = IL[i - 1][j]; // Current character of C matches // with current character of B, // but doesn't match with current // character of A else if ( A[i - 1] != C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = IL[i][j - 1]; // Current character of C matches // with that of both A and B else if ( A[i - 1] == C[i + j - 1] && B[j - 1] == C[i + j - 1]) IL[i][j] = (IL[i - 1][j] || IL[i][j - 1]); } } return IL[M][N];} // A function to run test casesfunction test(A, B, C){ if (isInterleaved(A, B, C)) document.write(C + \" is interleaved of \" + A + \" and \" + B,\"</br>\"); else document.write(C + \" is not interleaved of \" + A + \" and \" + B,\"</br>\");} // Driver program to test above functions test(\"XXY\", \"XXZ\", \"XXZXXXY\");test(\"XY\", \"WZ\", \"WZXY\");test(\"XY\", \"X\", \"XXY\");test(\"YX\", \"X\", \"XXY\");test(\"XXY\", \"XXZ\", \"XXXXZY\"); // This code is contributed by shinjanpatra</script>",
"e": 44957,
"s": 42135,
"text": null
},
{
"code": null,
"e": 44966,
"s": 44957,
"text": "Output: "
},
{
"code": null,
"e": 45144,
"s": 44966,
"text": "XXZXXXY is not interleaved of XXY and XXZ\nWZXY is interleaved of XY and WZ\nXXY is interleaved of XY and X\nXXY is not interleaved of YX and X\nXXXXZY is interleaved of XXY and XXZ"
},
{
"code": null,
"e": 45195,
"s": 45144,
"text": "See this for more test cases.Complexity Analysis: "
},
{
"code": null,
"e": 45295,
"s": 45195,
"text": "Time Complexity: O(M*N). Since a traversal of DP array is needed, so the time complexity is O(M*N)."
},
{
"code": null,
"e": 45371,
"s": 45295,
"text": "Space Complexity: O(M*N). This is the space required to store the DP array."
},
{
"code": null,
"e": 45526,
"s": 45371,
"text": "https://youtu.be/WBXy-sztEwI Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 45530,
"s": 45526,
"text": "gp6"
},
{
"code": null,
"e": 45542,
"s": 45530,
"text": "ankita91994"
},
{
"code": null,
"e": 45554,
"s": 45542,
"text": "ashutosh450"
},
{
"code": null,
"e": 45565,
"s": 45554,
"text": "andrew1234"
},
{
"code": null,
"e": 45573,
"s": 45565,
"text": "psyduck"
},
{
"code": null,
"e": 45591,
"s": 45573,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 45608,
"s": 45591,
"text": "kashisharora4110"
},
{
"code": null,
"e": 45613,
"s": 45608,
"text": "roho"
},
{
"code": null,
"e": 45623,
"s": 45613,
"text": "janmanshh"
},
{
"code": null,
"e": 45635,
"s": 45623,
"text": "ajaysingh37"
},
{
"code": null,
"e": 45648,
"s": 45635,
"text": "prasunroy212"
},
{
"code": null,
"e": 45665,
"s": 45648,
"text": "surinderdawra388"
},
{
"code": null,
"e": 45678,
"s": 45665,
"text": "shinjanpatra"
},
{
"code": null,
"e": 45691,
"s": 45678,
"text": "simmytarika5"
},
{
"code": null,
"e": 45709,
"s": 45691,
"text": "prashantchandelme"
},
{
"code": null,
"e": 45717,
"s": 45709,
"text": "FactSet"
},
{
"code": null,
"e": 45724,
"s": 45717,
"text": "Google"
},
{
"code": null,
"e": 45734,
"s": 45724,
"text": "Microsoft"
},
{
"code": null,
"e": 45740,
"s": 45734,
"text": "Yahoo"
},
{
"code": null,
"e": 45749,
"s": 45740,
"text": "Zillious"
},
{
"code": null,
"e": 45769,
"s": 45749,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45777,
"s": 45769,
"text": "Strings"
},
{
"code": null,
"e": 45787,
"s": 45777,
"text": "Microsoft"
},
{
"code": null,
"e": 45795,
"s": 45787,
"text": "FactSet"
},
{
"code": null,
"e": 45802,
"s": 45795,
"text": "Google"
},
{
"code": null,
"e": 45811,
"s": 45802,
"text": "Zillious"
},
{
"code": null,
"e": 45817,
"s": 45811,
"text": "Yahoo"
},
{
"code": null,
"e": 45825,
"s": 45817,
"text": "Strings"
},
{
"code": null,
"e": 45845,
"s": 45825,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45943,
"s": 45845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45952,
"s": 45943,
"text": "Comments"
},
{
"code": null,
"e": 45965,
"s": 45952,
"text": "Old Comments"
},
{
"code": null,
"e": 45996,
"s": 45965,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 46029,
"s": 45996,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 46067,
"s": 46029,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 46094,
"s": 46067,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 46162,
"s": 46094,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 46187,
"s": 46162,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 46233,
"s": 46187,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 46248,
"s": 46233,
"text": "C++ Data Types"
},
{
"code": null,
"e": 46308,
"s": 46248,
"text": "Write a program to print all permutations of a given string"
}
] |
Program to print the pattern 1020304017018019020 **50607014015016 ****809012013 ******10011... - GeeksforGeeks | 21 May, 2021
Given an integer N, the task is to print the pattern below for the given value of N.
For N = 5, below is the given pattern:
Examples:
Input: N = 4 Output: 1020304017018019020 **50607014015016 ****809012013 ******10011
Input: N = 3 Output: 10203010011012 **4050809 ****607
Approach: The idea to understand the logic behind the given pattern is stated below:
By looking closely, we see that by replacing in-between zeroes with spaces, the pattern can be seen more clearly. The pattern is further divided into three different patterns.
Case 1: Asterisk (*) character pattern follows a sequence from 0 and adds two more asterisks in each row, where the row is equal to N.Case 2: In this part, the pattern is very simple to understand. i.e the number of columns and rows will be equal to N and follows a sequence like 1, 2, 3, 4, 5...Case 3: Follow-up or bottom-up sequence is the interesting part where the numbers are represented from bottom to top.
Case 1: Asterisk (*) character pattern follows a sequence from 0 and adds two more asterisks in each row, where the row is equal to N.
Case 2: In this part, the pattern is very simple to understand. i.e the number of columns and rows will be equal to N and follows a sequence like 1, 2, 3, 4, 5...
Case 3: Follow-up or bottom-up sequence is the interesting part where the numbers are represented from bottom to top.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to print// the given pattern#include <bits/stdc++.h>using namespace std; // Function to find the sum of// N integers from 1 to Nint sum(int n){ return n * (n - 1) / 2;} // Function to print the given// patternvoid BSpattern(int N){ int Val = 0, Pthree = 0, cnt = 0, initial; string s = "**"; // Iterate over [0, N - 1] for (int i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { cout << s; s += "**"; } // Sub-Pattern - 2 for (int j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 and 3 // will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... cout << ++Val; cout << 0; } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { int Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for (int k = i; k < N; k++) { cout << Pthree++; // Skip printing zero at the last if (k != N - 1) { cout << 0; } } cout << "\n"; }} // Driver Codeint main(){ // Given N int N = 5; // Function Call BSpattern(N); return 0;}
// Java implementation to print// the given patternimport java.util.*; class GFG{ // Function to find the sum of// N integers from 1 to Nstatic int sum(int n){ return n * (n - 1) / 2;} // Function to print the given// patternstatic void BSpattern(int N){ int Val = 0, Pthree = 0, cnt = 0, initial = -1; String s = "**"; // Iterate over [0, N - 1] for(int i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { System.out.print(s); s += "**"; } // Sub-Pattern - 2 for(int j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 // and 3 will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... System.out.print(++Val); System.out.print("0"); } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { int Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for(int k = i; k < N; k++) { System.out.print(Pthree++); // Skip printing zero at the last if (k != N - 1) { System.out.print("0"); } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Given N int N = 5; // Function call BSpattern(N);}} // This code is contributed by offbeat
# Python3 implementation to print# the given pattern # Function to find the sum of# N integers from 1 to Ndef sum(n): return n * (n - 1) // 2 # Function to print the given# patterndef BSpattern(N): Val = 0 Pthree = 0, cnt = 0 initial = -1 s = "**" # Iterate over [0, N - 1] for i in range(N): cnt = 0 # Sub-Pattern - 1 if (i > 0): print(s, end = "") s += "**" # Sub-Pattern - 2 for j in range(i, N): # Count the number of element # in rows and sub-pattern 2 and 3 # will have same rows if (i > 0): cnt += 1 # Increment Val to print the # series 1, 2, 3, 4, 5 ... Val += 1 print(Val, end = "") print(0, end = "") # To get the first element of sub # pattern 3 find the sum of first N-1 # elements first N-1 elements in row1 # previous of Sub-Pattern 2 # Finally, add the (N-1)th element # i.e., 5 and increment it by 1 if (i == 0): Sumbeforelast = sum(Val) * 2 Pthree = Val + Sumbeforelast + 1 initial = Pthree # Initial is used to give the initial # value of the row in Sub-Pattern 3 initial = initial - cnt Pthree = initial # Sub-Pattern 3 for k in range(i, N): print(Pthree, end = "") Pthree += 1 # Skip printing zero at the last if (k != N - 1): print(0, end = "") print() # Driver Code # Given NN = 5 # Function callBSpattern(N) # This code is contributed by sanjoy_62
// C# implementation to print// the given patternusing System;class GFG{ // Function to find the sum of// N integers from 1 to Nstatic int sum(int n){ return n * (n - 1) / 2;} // Function to print the given// patternstatic void BSpattern(int N){ int Val = 0, Pthree = 0, cnt = 0, initial = -1; String s = "**"; // Iterate over [0, N - 1] for(int i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { Console.Write(s); s += "**"; } // Sub-Pattern - 2 for(int j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 // and 3 will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... Console.Write(++Val); Console.Write("0"); } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { int Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for(int k = i; k < N; k++) { Console.Write(Pthree++); // Skip printing zero at the last if (k != N - 1) { Console.Write("0"); } } Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ // Given N int N = 5; // Function call BSpattern(N);}} // This code is contributed by shikhasingrajput
<script>//Javascript implementation to print// the given pattern // Function to find the sum of// N integers from 1 to Nfunction sum( n){ return n * parseInt((n - 1) / 2);} // Function to print the given// patternfunction BSpattern( N){ var Val = 0, Pthree = 0, cnt = 0, initial; var s = "**"; // Iterate over [0, N - 1] for (var i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { document.write( s); s += "**"; } // Sub-Pattern - 2 for (var j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 and 3 // will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... document.write( ++Val); document.write( 0); } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { var Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for (var k = i; k < N; k++) { document.write(Pthree++); // Skip printing zero at the last if (k != N - 1) { document.write( 0); } } document.write( "<br>"); }} // Given Nvar N = 5;// Function CallBSpattern(N); // This code is contributed by SoumikMondal</script>
102030405026027028029030
**6070809022023024025
****10011012019020021
******13014017018
********15016
Time Complexity: O(N2) Auxiliary Space: O(1)
offbeat
shikhasingrajput
sanjoy_62
nidhi_biet
SoumikMondal
interview-preparation
Juspay
pattern-printing
Pattern Searching
School Programming
pattern-printing
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Boyer Moore Algorithm for Pattern Searching
Check if an URL is valid or not using Regular Expression
Search a Word in a 2D Grid of characters
How to check if string contains only digits in Java
Check if a string contains uppercase, lowercase, special characters and numeric values
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 26557,
"s": 26529,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26644,
"s": 26557,
"text": "Given an integer N, the task is to print the pattern below for the given value of N. "
},
{
"code": null,
"e": 26685,
"s": 26644,
"text": "For N = 5, below is the given pattern: "
},
{
"code": null,
"e": 26697,
"s": 26685,
"text": "Examples: "
},
{
"code": null,
"e": 26781,
"s": 26697,
"text": "Input: N = 4 Output: 1020304017018019020 **50607014015016 ****809012013 ******10011"
},
{
"code": null,
"e": 26836,
"s": 26781,
"text": "Input: N = 3 Output: 10203010011012 **4050809 ****607 "
},
{
"code": null,
"e": 26921,
"s": 26836,
"text": "Approach: The idea to understand the logic behind the given pattern is stated below:"
},
{
"code": null,
"e": 27097,
"s": 26921,
"text": "By looking closely, we see that by replacing in-between zeroes with spaces, the pattern can be seen more clearly. The pattern is further divided into three different patterns."
},
{
"code": null,
"e": 27511,
"s": 27097,
"text": "Case 1: Asterisk (*) character pattern follows a sequence from 0 and adds two more asterisks in each row, where the row is equal to N.Case 2: In this part, the pattern is very simple to understand. i.e the number of columns and rows will be equal to N and follows a sequence like 1, 2, 3, 4, 5...Case 3: Follow-up or bottom-up sequence is the interesting part where the numbers are represented from bottom to top."
},
{
"code": null,
"e": 27646,
"s": 27511,
"text": "Case 1: Asterisk (*) character pattern follows a sequence from 0 and adds two more asterisks in each row, where the row is equal to N."
},
{
"code": null,
"e": 27809,
"s": 27646,
"text": "Case 2: In this part, the pattern is very simple to understand. i.e the number of columns and rows will be equal to N and follows a sequence like 1, 2, 3, 4, 5..."
},
{
"code": null,
"e": 27927,
"s": 27809,
"text": "Case 3: Follow-up or bottom-up sequence is the interesting part where the numbers are represented from bottom to top."
},
{
"code": null,
"e": 27979,
"s": 27927,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27983,
"s": 27979,
"text": "C++"
},
{
"code": null,
"e": 27988,
"s": 27983,
"text": "Java"
},
{
"code": null,
"e": 27996,
"s": 27988,
"text": "Python3"
},
{
"code": null,
"e": 27999,
"s": 27996,
"text": "C#"
},
{
"code": null,
"e": 28010,
"s": 27999,
"text": "Javascript"
},
{
"code": "// C++ implementation to print// the given pattern#include <bits/stdc++.h>using namespace std; // Function to find the sum of// N integers from 1 to Nint sum(int n){ return n * (n - 1) / 2;} // Function to print the given// patternvoid BSpattern(int N){ int Val = 0, Pthree = 0, cnt = 0, initial; string s = \"**\"; // Iterate over [0, N - 1] for (int i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { cout << s; s += \"**\"; } // Sub-Pattern - 2 for (int j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 and 3 // will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... cout << ++Val; cout << 0; } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { int Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for (int k = i; k < N; k++) { cout << Pthree++; // Skip printing zero at the last if (k != N - 1) { cout << 0; } } cout << \"\\n\"; }} // Driver Codeint main(){ // Given N int N = 5; // Function Call BSpattern(N); return 0;}",
"e": 29806,
"s": 28010,
"text": null
},
{
"code": "// Java implementation to print// the given patternimport java.util.*; class GFG{ // Function to find the sum of// N integers from 1 to Nstatic int sum(int n){ return n * (n - 1) / 2;} // Function to print the given// patternstatic void BSpattern(int N){ int Val = 0, Pthree = 0, cnt = 0, initial = -1; String s = \"**\"; // Iterate over [0, N - 1] for(int i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { System.out.print(s); s += \"**\"; } // Sub-Pattern - 2 for(int j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 // and 3 will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... System.out.print(++Val); System.out.print(\"0\"); } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { int Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for(int k = i; k < N; k++) { System.out.print(Pthree++); // Skip printing zero at the last if (k != N - 1) { System.out.print(\"0\"); } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Given N int N = 5; // Function call BSpattern(N);}} // This code is contributed by offbeat",
"e": 31815,
"s": 29806,
"text": null
},
{
"code": "# Python3 implementation to print# the given pattern # Function to find the sum of# N integers from 1 to Ndef sum(n): return n * (n - 1) // 2 # Function to print the given# patterndef BSpattern(N): Val = 0 Pthree = 0, cnt = 0 initial = -1 s = \"**\" # Iterate over [0, N - 1] for i in range(N): cnt = 0 # Sub-Pattern - 1 if (i > 0): print(s, end = \"\") s += \"**\" # Sub-Pattern - 2 for j in range(i, N): # Count the number of element # in rows and sub-pattern 2 and 3 # will have same rows if (i > 0): cnt += 1 # Increment Val to print the # series 1, 2, 3, 4, 5 ... Val += 1 print(Val, end = \"\") print(0, end = \"\") # To get the first element of sub # pattern 3 find the sum of first N-1 # elements first N-1 elements in row1 # previous of Sub-Pattern 2 # Finally, add the (N-1)th element # i.e., 5 and increment it by 1 if (i == 0): Sumbeforelast = sum(Val) * 2 Pthree = Val + Sumbeforelast + 1 initial = Pthree # Initial is used to give the initial # value of the row in Sub-Pattern 3 initial = initial - cnt Pthree = initial # Sub-Pattern 3 for k in range(i, N): print(Pthree, end = \"\") Pthree += 1 # Skip printing zero at the last if (k != N - 1): print(0, end = \"\") print() # Driver Code # Given NN = 5 # Function callBSpattern(N) # This code is contributed by sanjoy_62",
"e": 33579,
"s": 31815,
"text": null
},
{
"code": "// C# implementation to print// the given patternusing System;class GFG{ // Function to find the sum of// N integers from 1 to Nstatic int sum(int n){ return n * (n - 1) / 2;} // Function to print the given// patternstatic void BSpattern(int N){ int Val = 0, Pthree = 0, cnt = 0, initial = -1; String s = \"**\"; // Iterate over [0, N - 1] for(int i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { Console.Write(s); s += \"**\"; } // Sub-Pattern - 2 for(int j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 // and 3 will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... Console.Write(++Val); Console.Write(\"0\"); } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { int Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for(int k = i; k < N; k++) { Console.Write(Pthree++); // Skip printing zero at the last if (k != N - 1) { Console.Write(\"0\"); } } Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ // Given N int N = 5; // Function call BSpattern(N);}} // This code is contributed by shikhasingrajput",
"e": 35590,
"s": 33579,
"text": null
},
{
"code": "<script>//Javascript implementation to print// the given pattern // Function to find the sum of// N integers from 1 to Nfunction sum( n){ return n * parseInt((n - 1) / 2);} // Function to print the given// patternfunction BSpattern( N){ var Val = 0, Pthree = 0, cnt = 0, initial; var s = \"**\"; // Iterate over [0, N - 1] for (var i = 0; i < N; i++) { cnt = 0; // Sub-Pattern - 1 if (i > 0) { document.write( s); s += \"**\"; } // Sub-Pattern - 2 for (var j = i; j < N; j++) { // Count the number of element // in rows and sub-pattern 2 and 3 // will have same rows if (i > 0) { cnt++; } // Increment Val to print the // series 1, 2, 3, 4, 5 ... document.write( ++Val); document.write( 0); } // To get the first element of sub // pattern 3 find the sum of first N-1 // elements first N-1 elements in row1 // previous of Sub-Pattern 2 // Finally, add the (N-1)th element // i.e., 5 and increment it by 1 if (i == 0) { var Sumbeforelast = sum(Val) * 2; Pthree = Val + Sumbeforelast + 1; initial = Pthree; } // Initial is used to give the initial // value of the row in Sub-Pattern 3 initial = initial - cnt; Pthree = initial; // Sub-Pattern 3 for (var k = i; k < N; k++) { document.write(Pthree++); // Skip printing zero at the last if (k != N - 1) { document.write( 0); } } document.write( \"<br>\"); }} // Given Nvar N = 5;// Function CallBSpattern(N); // This code is contributed by SoumikMondal</script>",
"e": 37418,
"s": 35590,
"text": null
},
{
"code": null,
"e": 37519,
"s": 37418,
"text": "102030405026027028029030\n**6070809022023024025\n****10011012019020021\n******13014017018\n********15016"
},
{
"code": null,
"e": 37567,
"s": 37521,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 37575,
"s": 37567,
"text": "offbeat"
},
{
"code": null,
"e": 37592,
"s": 37575,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 37602,
"s": 37592,
"text": "sanjoy_62"
},
{
"code": null,
"e": 37613,
"s": 37602,
"text": "nidhi_biet"
},
{
"code": null,
"e": 37626,
"s": 37613,
"text": "SoumikMondal"
},
{
"code": null,
"e": 37648,
"s": 37626,
"text": "interview-preparation"
},
{
"code": null,
"e": 37655,
"s": 37648,
"text": "Juspay"
},
{
"code": null,
"e": 37672,
"s": 37655,
"text": "pattern-printing"
},
{
"code": null,
"e": 37690,
"s": 37672,
"text": "Pattern Searching"
},
{
"code": null,
"e": 37709,
"s": 37690,
"text": "School Programming"
},
{
"code": null,
"e": 37726,
"s": 37709,
"text": "pattern-printing"
},
{
"code": null,
"e": 37744,
"s": 37726,
"text": "Pattern Searching"
},
{
"code": null,
"e": 37842,
"s": 37744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37886,
"s": 37842,
"text": "Boyer Moore Algorithm for Pattern Searching"
},
{
"code": null,
"e": 37943,
"s": 37886,
"text": "Check if an URL is valid or not using Regular Expression"
},
{
"code": null,
"e": 37984,
"s": 37943,
"text": "Search a Word in a 2D Grid of characters"
},
{
"code": null,
"e": 38036,
"s": 37984,
"text": "How to check if string contains only digits in Java"
},
{
"code": null,
"e": 38123,
"s": 38036,
"text": "Check if a string contains uppercase, lowercase, special characters and numeric values"
},
{
"code": null,
"e": 38141,
"s": 38123,
"text": "Python Dictionary"
},
{
"code": null,
"e": 38157,
"s": 38141,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 38176,
"s": 38157,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 38201,
"s": 38176,
"text": "Reverse a string in Java"
}
] |
X of a Kind in a Deck of Cards in C++ | Suppose we have a deck of cards, each card has an integer written on it. We have to check whether we can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where the following condition satisfies: Each group has exactly X number of cards. All of the cards in each group have the same number.
So, if the input is like deck = [1,2,3,4,4,3,2,1], then the output will be True, as possible partitions are [1,1],[2,2],[3,3],[4,4].
To solve this, we will follow these steps −
Define one map mp
for all x in deck(increase mp[x] by 1)
(increase mp[x] by 1)
for all key-value pair x in mpans := gcd of (ans and value of x)
ans := gcd of (ans and value of x)
return true when ans > 1, otherwise false
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int, int> mp;
int ans;
for (auto x : deck)
mp[x]++;
for (auto x : mp)
ans = __gcd(ans, x.second);
return (ans > 1);
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,4,3,2,1};
cout << (ob.hasGroupsSizeX(v));
}
{1,2,3,4,4,3,2,1}
1 | [
{
"code": null,
"e": 1399,
"s": 1062,
"text": "Suppose we have a deck of cards, each card has an integer written on it. We have to check whether we can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where the following condition satisfies: Each group has exactly X number of cards. All of the cards in each group have the same number."
},
{
"code": null,
"e": 1532,
"s": 1399,
"text": "So, if the input is like deck = [1,2,3,4,4,3,2,1], then the output will be True, as possible partitions are [1,1],[2,2],[3,3],[4,4]."
},
{
"code": null,
"e": 1576,
"s": 1532,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1594,
"s": 1576,
"text": "Define one map mp"
},
{
"code": null,
"e": 1633,
"s": 1594,
"text": "for all x in deck(increase mp[x] by 1)"
},
{
"code": null,
"e": 1655,
"s": 1633,
"text": "(increase mp[x] by 1)"
},
{
"code": null,
"e": 1720,
"s": 1655,
"text": "for all key-value pair x in mpans := gcd of (ans and value of x)"
},
{
"code": null,
"e": 1755,
"s": 1720,
"text": "ans := gcd of (ans and value of x)"
},
{
"code": null,
"e": 1797,
"s": 1755,
"text": "return true when ans > 1, otherwise false"
},
{
"code": null,
"e": 1867,
"s": 1797,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1878,
"s": 1867,
"text": " Live Demo"
},
{
"code": null,
"e": 2278,
"s": 1878,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n bool hasGroupsSizeX(vector<int>& deck) {\n unordered_map<int, int> mp;\n int ans;\n for (auto x : deck)\n mp[x]++;\n for (auto x : mp)\n ans = __gcd(ans, x.second);\n return (ans > 1);\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,2,3,4,4,3,2,1};\n cout << (ob.hasGroupsSizeX(v));\n}"
},
{
"code": null,
"e": 2296,
"s": 2278,
"text": "{1,2,3,4,4,3,2,1}"
},
{
"code": null,
"e": 2298,
"s": 2296,
"text": "1"
}
] |
Microsoft Azure – Resizing Virtual Machine Using PowerShell Script | 16 Dec, 2021
In this article, we will look into the process of resizing azure VMs at once using the Azure PowerShell automation script in the Azure portal by using the cloud shell.
Resizing Multiple VMs at once in a follow for select subscription
Saves the time of the User
Simplifying the Actions by Automating the process
Re-usable Script
Step 1: Log in to Azure Portal
Step 2: Open Cloud Shell and Select PowerShell
Step 3: Create a Folder named “Automation”
mkdir Automation
Step 4: Change directory
cd ./Automation/
Step 5: Create file “test-resize.ps1”
touch test-resize.ps1
Step 6: Azure PowerShell Script
Change the following two-line in the below-given code:
Line Number 3 >> $VMsList = @(“TestVM”, “TestVM2′′,”TestVM3”,...) #Provide your VM List that need to be resizedLine Number 4 >> $NewAzureSize = “Standard_B2s” #Provide your New Azure VM Size
Line Number 3 >> $VMsList = @(“TestVM”, “TestVM2′′,”TestVM3”,...) #Provide your VM List that need to be resized
Line Number 4 >> $NewAzureSize = “Standard_B2s” #Provide your New Azure VM Size
Then, paste the code in test-resize.ps1 file and save and close.
$AzVMs = Get-AzureRmVM | Select-Object -Property Name, ResourceGroupName, Location, Type, ProvisioningState
$VMsList = @("TestVM", "TestVM2", "TestVM3") #Provide your VM List that need to be Resized
$NewAzureSize = "Standard_B2s" #Provide your New Azure VM Size
foreach ($VM in $AzVMs)
{
$VMName = $VM.Name
$ResourceGroupName = $VM.ResourceGroupName
$Type = $VM.Type
$Location = $VM.Location
$ProvisioningState = $VM.ProvisioningState
if ($VMsList -contains $VMName)
{
Write-Host "--------------------------------------------------------------------"
Write-Host "Virtual Machine: $VMName"
Write-Host "ResourceGroup : $ResourceGroupName"
Write-Host "Location : $Location"
Write-Host "ResourceType : $Type"
Write-Host "ProvisioningState : $ProvisioningState"
Write-Host "--------------------------------------------------------------------"
Write-Host "Deallocating $VMName VM."
Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force
Write-Host "$VMName VM Stopped."
Write-Host "--------------------------------------------------------------------"
Write-Host "Updating $VMName VMSize."
$vm = Get-AzVM -ResourceGroupName $ResourceGroupName -VMName $VMName
$vm.HardwareProfile.VmSize = $AzureSize
Update-AzVM -VM $vm -ResourceGroupName $ResourceGroupName
Write-Host "Successfully resized $VMName VM to size $NewAzureSize."
Write-Host "--------------------------------------------------------------------"
Write-Host "Starting $VMName VM"
Start-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName
Write-Host "$VMName VM Started."
Write-Host "--------------------------------------------------------------------"
}
}
Step 7: Now, it’s time to run the code. Use the following syntax to execute the Azure PowerShell script for Resizing.
./test-resize.ps1
Step 8: Output looks like the following for all the listed VMs in Script. That’s it, You are done.
At this point, we have successfully managed to resize our Azure VM using Powershell script.
azure-virtual-machine
Cloud-Computing
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Azure - Enable Linux System Logs in Azure for Monitoring
Microsoft Azure - Azure Firewall Flow Logs From Select Source IP
What are Azure Virtual Machines?
Microsoft Azure SQL Database
Microsoft Azure - Azure SQL Database Deployment Options
Microsoft Azure - Introduction to Spot Virtual Machines
Microsoft Azure - KQL Query to Get the VM Computer Properties
Microsoft Azure - Map a Network File Share to Azure Windows VM
How Microsoft Azure Works?
7 Tips to Reduce Cost with Azure Virtual Machines | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "In this article, we will look into the process of resizing azure VMs at once using the Azure PowerShell automation script in the Azure portal by using the cloud shell."
},
{
"code": null,
"e": 262,
"s": 196,
"text": "Resizing Multiple VMs at once in a follow for select subscription"
},
{
"code": null,
"e": 289,
"s": 262,
"text": "Saves the time of the User"
},
{
"code": null,
"e": 339,
"s": 289,
"text": "Simplifying the Actions by Automating the process"
},
{
"code": null,
"e": 356,
"s": 339,
"text": "Re-usable Script"
},
{
"code": null,
"e": 387,
"s": 356,
"text": "Step 1: Log in to Azure Portal"
},
{
"code": null,
"e": 434,
"s": 387,
"text": "Step 2: Open Cloud Shell and Select PowerShell"
},
{
"code": null,
"e": 477,
"s": 434,
"text": "Step 3: Create a Folder named “Automation”"
},
{
"code": null,
"e": 494,
"s": 477,
"text": "mkdir Automation"
},
{
"code": null,
"e": 520,
"s": 494,
"text": "Step 4: Change directory "
},
{
"code": null,
"e": 537,
"s": 520,
"text": "cd ./Automation/"
},
{
"code": null,
"e": 575,
"s": 537,
"text": "Step 5: Create file “test-resize.ps1”"
},
{
"code": null,
"e": 597,
"s": 575,
"text": "touch test-resize.ps1"
},
{
"code": null,
"e": 630,
"s": 597,
"text": "Step 6: Azure PowerShell Script"
},
{
"code": null,
"e": 685,
"s": 630,
"text": "Change the following two-line in the below-given code:"
},
{
"code": null,
"e": 876,
"s": 685,
"text": "Line Number 3 >> $VMsList = @(“TestVM”, “TestVM2′′,”TestVM3”,...) #Provide your VM List that need to be resizedLine Number 4 >> $NewAzureSize = “Standard_B2s” #Provide your New Azure VM Size"
},
{
"code": null,
"e": 988,
"s": 876,
"text": "Line Number 3 >> $VMsList = @(“TestVM”, “TestVM2′′,”TestVM3”,...) #Provide your VM List that need to be resized"
},
{
"code": null,
"e": 1068,
"s": 988,
"text": "Line Number 4 >> $NewAzureSize = “Standard_B2s” #Provide your New Azure VM Size"
},
{
"code": null,
"e": 1133,
"s": 1068,
"text": "Then, paste the code in test-resize.ps1 file and save and close."
},
{
"code": null,
"e": 2975,
"s": 1133,
"text": "$AzVMs = Get-AzureRmVM | Select-Object -Property Name, ResourceGroupName, Location, Type, ProvisioningState\n\n$VMsList = @(\"TestVM\", \"TestVM2\", \"TestVM3\") #Provide your VM List that need to be Resized\n$NewAzureSize = \"Standard_B2s\" #Provide your New Azure VM Size\n\nforeach ($VM in $AzVMs)\n{\n $VMName = $VM.Name\n $ResourceGroupName = $VM.ResourceGroupName\n $Type = $VM.Type\n $Location = $VM.Location\n $ProvisioningState = $VM.ProvisioningState\n\n if ($VMsList -contains $VMName)\n {\n Write-Host \"--------------------------------------------------------------------\"\n Write-Host \"Virtual Machine: $VMName\"\n Write-Host \"ResourceGroup : $ResourceGroupName\"\n Write-Host \"Location : $Location\"\n Write-Host \"ResourceType : $Type\"\n Write-Host \"ProvisioningState : $ProvisioningState\" \n Write-Host \"--------------------------------------------------------------------\"\n Write-Host \"Deallocating $VMName VM.\"\n Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force\n Write-Host \"$VMName VM Stopped.\"\n Write-Host \"--------------------------------------------------------------------\"\n Write-Host \"Updating $VMName VMSize.\"\n $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -VMName $VMName\n $vm.HardwareProfile.VmSize = $AzureSize\n Update-AzVM -VM $vm -ResourceGroupName $ResourceGroupName\n Write-Host \"Successfully resized $VMName VM to size $NewAzureSize.\"\n Write-Host \"--------------------------------------------------------------------\"\n Write-Host \"Starting $VMName VM\"\n Start-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName\n Write-Host \"$VMName VM Started.\"\n Write-Host \"--------------------------------------------------------------------\"\n }\n} "
},
{
"code": null,
"e": 3094,
"s": 2975,
"text": "Step 7: Now, it’s time to run the code. Use the following syntax to execute the Azure PowerShell script for Resizing."
},
{
"code": null,
"e": 3112,
"s": 3094,
"text": "./test-resize.ps1"
},
{
"code": null,
"e": 3211,
"s": 3112,
"text": "Step 8: Output looks like the following for all the listed VMs in Script. That’s it, You are done."
},
{
"code": null,
"e": 3303,
"s": 3211,
"text": "At this point, we have successfully managed to resize our Azure VM using Powershell script."
},
{
"code": null,
"e": 3325,
"s": 3303,
"text": "azure-virtual-machine"
},
{
"code": null,
"e": 3341,
"s": 3325,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 3357,
"s": 3341,
"text": "Microsoft Azure"
},
{
"code": null,
"e": 3455,
"s": 3357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3522,
"s": 3455,
"text": "Microsoft Azure - Enable Linux System Logs in Azure for Monitoring"
},
{
"code": null,
"e": 3587,
"s": 3522,
"text": "Microsoft Azure - Azure Firewall Flow Logs From Select Source IP"
},
{
"code": null,
"e": 3620,
"s": 3587,
"text": "What are Azure Virtual Machines?"
},
{
"code": null,
"e": 3649,
"s": 3620,
"text": "Microsoft Azure SQL Database"
},
{
"code": null,
"e": 3705,
"s": 3649,
"text": "Microsoft Azure - Azure SQL Database Deployment Options"
},
{
"code": null,
"e": 3761,
"s": 3705,
"text": "Microsoft Azure - Introduction to Spot Virtual Machines"
},
{
"code": null,
"e": 3823,
"s": 3761,
"text": "Microsoft Azure - KQL Query to Get the VM Computer Properties"
},
{
"code": null,
"e": 3886,
"s": 3823,
"text": "Microsoft Azure - Map a Network File Share to Azure Windows VM"
},
{
"code": null,
"e": 3913,
"s": 3886,
"text": "How Microsoft Azure Works?"
}
] |
TCP Client-Server Program to Check if a Given String is Palindrome | 02 Aug, 2019
Prerequisites:
Socket Programming in C/C++,
TCP and UDP server using select,
UDP Server-Client implementation in C
TCP Client-Server Implementation in C
This article describes a Client and Server setup where a Client connects, sends a string to the server and the server shows the original string and sends confirmation whether the string is a palindrome or not, to the client using socket connection.
Examples:
Input: naman
Output: Palindrome
Input: geek
Output: Not Palindrome
Approach:
In this, first set up a client-server connection.
When the connection will setup, the client will send the user input string to the server by the send system call.
At the server-side, the server will wait for a string sent by the client.
Server reads the string by the reading system call.
After this, the server will check if the string is a palindrome or not and sends the confirmation back to the client.
Compiling:
First, run the server program asgcc server.c -o server
./serverRun the client program on another terminalgcc client.c -o client
./clientServer program is waiting for the string sent by the client.Input the string in client-side.Server program will print original string.Client program will print result.
First, run the server program asgcc server.c -o server
./server
gcc server.c -o server
./server
Run the client program on another terminalgcc client.c -o client
./client
gcc client.c -o client
./client
Server program is waiting for the string sent by the client.
Input the string in client-side.
Server program will print original string.
Client program will print result.
Below is the implementation of the above approach:
TCP Server
TCP Client
// defines in_addr structure#include <arpa/inet.h> // contains constants and structures// needed for internet domain addresses#include <netinet/in.h> // standard input and output library#include <stdio.h> // contains string functions#include <string.h> // for socket creation#include <sys/socket.h> // contains constructs that facilitate getting// information about files attributes.#include <sys/stat.h> // contains a number of basic derived types// that should be used whenever appropriate#include <sys/types.h> main(){ struct sockaddr_in client, server; int s, n, sock, g, j, left, right, flag; char b1[20], b2[10], b3[10], b4[10]; // creating socket s = socket(AF_INET, SOCK_STREAM, 0); // assign IP, PORT server.sin_family = AF_INET; // this is the port number of running server server.sin_port = 2000; server.sin_addr.s_addr = inet_addr("127.0.0.1"); // Binding newly created socket // to given IP and verification bind(s, (struct sockaddr*)&server, sizeof server); listen(s, 1); n = sizeof client; sock = accept(s, (struct sockaddr*)&client, &n); for (;;) { recv(sock, b1, sizeof(b1), 0); // whenever a request from a client came. // It will be processed here. printf("\nThe string received is:%s\n", b1); if (strlen(b1) == 0) flag = 1; else { left = 0; right = strlen(b1) - 1; flag = 1; while (left < right && flag) { if (b1[left] != b1[right]) flag = 0; else { left++; right--; } } } send(sock, &flag, sizeof(int), 0); break; } close(sock); // close the socket close(s);}
// defines in_addr structure#include <arpa/inet.h> // contains constants and structures// needed for internet domain addresses#include <netinet/in.h> // standard input and output library#include <stdio.h> // contains string functions#include <string.h> // for socket creation#include <sys/socket.h> // contains constructs that facilitate getting// information about files attributes.#include <sys/stat.h> // contains a number of basic derived types// that should be used whenever appropriate#include <sys/types.h> main(){ struct sockaddr_in client; int s, flag; char buffer[20]; // socket create s = socket(AF_INET, SOCK_STREAM, 0); // assign IP, PORT client.sin_family = AF_INET; client.sin_port = 2000; client.sin_addr.s_addr = inet_addr("127.0.0.1"); // connect the client socket to server socket connect(s, (struct sockaddr*)&client, sizeof client); for (;;) { printf("\nEnter a string to check palindrome: "); scanf("%s", buffer); printf("\nClient: %s", buffer); send(s, buffer, sizeof(buffer), 0); recv(s, &flag, sizeof(int), 0); if (flag == 1) { printf("\nServer: The string is a Palindrome.\n"); break; } else { printf("\nServer: The string is not a palindrome.\n"); break; } } // close the socket close(s);}
Server Side:
Client Side:
cpp-multithreading
palindrome
C Programs
Computer Networks
palindrome
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Layers of OSI Model
TCP/IP Model
Basics of Computer Networking
Differences between TCP and UDP
Types of Network Topology | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 67,
"s": 52,
"text": "Prerequisites:"
},
{
"code": null,
"e": 96,
"s": 67,
"text": "Socket Programming in C/C++,"
},
{
"code": null,
"e": 129,
"s": 96,
"text": "TCP and UDP server using select,"
},
{
"code": null,
"e": 167,
"s": 129,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 205,
"s": 167,
"text": "TCP Client-Server Implementation in C"
},
{
"code": null,
"e": 454,
"s": 205,
"text": "This article describes a Client and Server setup where a Client connects, sends a string to the server and the server shows the original string and sends confirmation whether the string is a palindrome or not, to the client using socket connection."
},
{
"code": null,
"e": 464,
"s": 454,
"text": "Examples:"
},
{
"code": null,
"e": 533,
"s": 464,
"text": "Input: naman\nOutput: Palindrome\n\nInput: geek\nOutput: Not Palindrome\n"
},
{
"code": null,
"e": 543,
"s": 533,
"text": "Approach:"
},
{
"code": null,
"e": 593,
"s": 543,
"text": "In this, first set up a client-server connection."
},
{
"code": null,
"e": 707,
"s": 593,
"text": "When the connection will setup, the client will send the user input string to the server by the send system call."
},
{
"code": null,
"e": 781,
"s": 707,
"text": "At the server-side, the server will wait for a string sent by the client."
},
{
"code": null,
"e": 833,
"s": 781,
"text": "Server reads the string by the reading system call."
},
{
"code": null,
"e": 951,
"s": 833,
"text": "After this, the server will check if the string is a palindrome or not and sends the confirmation back to the client."
},
{
"code": null,
"e": 962,
"s": 951,
"text": "Compiling:"
},
{
"code": null,
"e": 1266,
"s": 962,
"text": "First, run the server program asgcc server.c -o server\n./serverRun the client program on another terminalgcc client.c -o client\n./clientServer program is waiting for the string sent by the client.Input the string in client-side.Server program will print original string.Client program will print result."
},
{
"code": null,
"e": 1330,
"s": 1266,
"text": "First, run the server program asgcc server.c -o server\n./server"
},
{
"code": null,
"e": 1362,
"s": 1330,
"text": "gcc server.c -o server\n./server"
},
{
"code": null,
"e": 1436,
"s": 1362,
"text": "Run the client program on another terminalgcc client.c -o client\n./client"
},
{
"code": null,
"e": 1468,
"s": 1436,
"text": "gcc client.c -o client\n./client"
},
{
"code": null,
"e": 1529,
"s": 1468,
"text": "Server program is waiting for the string sent by the client."
},
{
"code": null,
"e": 1562,
"s": 1529,
"text": "Input the string in client-side."
},
{
"code": null,
"e": 1605,
"s": 1562,
"text": "Server program will print original string."
},
{
"code": null,
"e": 1639,
"s": 1605,
"text": "Client program will print result."
},
{
"code": null,
"e": 1690,
"s": 1639,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1701,
"s": 1690,
"text": "TCP Server"
},
{
"code": null,
"e": 1712,
"s": 1701,
"text": "TCP Client"
},
{
"code": "// defines in_addr structure#include <arpa/inet.h> // contains constants and structures// needed for internet domain addresses#include <netinet/in.h> // standard input and output library#include <stdio.h> // contains string functions#include <string.h> // for socket creation#include <sys/socket.h> // contains constructs that facilitate getting// information about files attributes.#include <sys/stat.h> // contains a number of basic derived types// that should be used whenever appropriate#include <sys/types.h> main(){ struct sockaddr_in client, server; int s, n, sock, g, j, left, right, flag; char b1[20], b2[10], b3[10], b4[10]; // creating socket s = socket(AF_INET, SOCK_STREAM, 0); // assign IP, PORT server.sin_family = AF_INET; // this is the port number of running server server.sin_port = 2000; server.sin_addr.s_addr = inet_addr(\"127.0.0.1\"); // Binding newly created socket // to given IP and verification bind(s, (struct sockaddr*)&server, sizeof server); listen(s, 1); n = sizeof client; sock = accept(s, (struct sockaddr*)&client, &n); for (;;) { recv(sock, b1, sizeof(b1), 0); // whenever a request from a client came. // It will be processed here. printf(\"\\nThe string received is:%s\\n\", b1); if (strlen(b1) == 0) flag = 1; else { left = 0; right = strlen(b1) - 1; flag = 1; while (left < right && flag) { if (b1[left] != b1[right]) flag = 0; else { left++; right--; } } } send(sock, &flag, sizeof(int), 0); break; } close(sock); // close the socket close(s);}",
"e": 3508,
"s": 1712,
"text": null
},
{
"code": "// defines in_addr structure#include <arpa/inet.h> // contains constants and structures// needed for internet domain addresses#include <netinet/in.h> // standard input and output library#include <stdio.h> // contains string functions#include <string.h> // for socket creation#include <sys/socket.h> // contains constructs that facilitate getting// information about files attributes.#include <sys/stat.h> // contains a number of basic derived types// that should be used whenever appropriate#include <sys/types.h> main(){ struct sockaddr_in client; int s, flag; char buffer[20]; // socket create s = socket(AF_INET, SOCK_STREAM, 0); // assign IP, PORT client.sin_family = AF_INET; client.sin_port = 2000; client.sin_addr.s_addr = inet_addr(\"127.0.0.1\"); // connect the client socket to server socket connect(s, (struct sockaddr*)&client, sizeof client); for (;;) { printf(\"\\nEnter a string to check palindrome: \"); scanf(\"%s\", buffer); printf(\"\\nClient: %s\", buffer); send(s, buffer, sizeof(buffer), 0); recv(s, &flag, sizeof(int), 0); if (flag == 1) { printf(\"\\nServer: The string is a Palindrome.\\n\"); break; } else { printf(\"\\nServer: The string is not a palindrome.\\n\"); break; } } // close the socket close(s);}",
"e": 4898,
"s": 3508,
"text": null
},
{
"code": null,
"e": 4911,
"s": 4898,
"text": "Server Side:"
},
{
"code": null,
"e": 4924,
"s": 4911,
"text": "Client Side:"
},
{
"code": null,
"e": 4943,
"s": 4924,
"text": "cpp-multithreading"
},
{
"code": null,
"e": 4954,
"s": 4943,
"text": "palindrome"
},
{
"code": null,
"e": 4965,
"s": 4954,
"text": "C Programs"
},
{
"code": null,
"e": 4983,
"s": 4965,
"text": "Computer Networks"
},
{
"code": null,
"e": 4994,
"s": 4983,
"text": "palindrome"
},
{
"code": null,
"e": 5012,
"s": 4994,
"text": "Computer Networks"
},
{
"code": null,
"e": 5110,
"s": 5012,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5151,
"s": 5110,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 5182,
"s": 5151,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 5235,
"s": 5182,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 5269,
"s": 5235,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 5359,
"s": 5269,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 5379,
"s": 5359,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 5392,
"s": 5379,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 5422,
"s": 5392,
"text": "Basics of Computer Networking"
},
{
"code": null,
"e": 5454,
"s": 5422,
"text": "Differences between TCP and UDP"
}
] |
Python – Add Custom Column to Tuple list | 10 Jun, 2020
Sometimes, while working with Python records, we can have a problem in which we need to add custom column to tuples list. This kind of problem can have application in data domains such as web development. Lets discuss certain ways in which this task can be performed.
Input :test_list = [(3, ), (7, ), (2, )]cus_eles = [7, 8, 2]Output : [(3, 7), (7, 8), (2, 2)]
Input :test_list = [(3, 9, 6, 10)]cus_eles = [7]Output : [(3, 9, 6, 10, 7)]
Method #1 : Using list comprehension + zip()The combination of above functionalities can be used to solve this problem. In this, we perform the pairing of custom elements and tuples with the help of zip().
# Python3 code to demonstrate working of # Add Custom Column to Tuple list# Using list comprehension + zip() # initializing listtest_list = [(3, 4), (78, 76), (2, 3)] # printing original listprint("The original list is : " + str(test_list)) # initializing add listcus_eles = [17, 23, 12] # Add Custom Column to Tuple list# Using list comprehension + zip()res = [sub + (val, ) for sub, val in zip(test_list, cus_eles)] # printing result print("The tuples after adding elements : " + str(res))
The original list is : [(3, 4), (78, 76), (2, 3)]
The tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]
Method #2 : Using map() + lambdaThe combination of above functions can also be used to solve this problem. In this, we perform the task of extending logic to each tuple using map() and lambda is used to perform task of addition.
# Python3 code to demonstrate working of # Add Custom Column to Tuple list# Using map() + lambda # initializing listtest_list = [(3, 4), (78, 76), (2, 3)] # printing original listprint("The original list is : " + str(test_list)) # initializing add listcus_eles = [17, 23, 12] # Add Custom Column to Tuple list# Using map() + lambdares = list(map(lambda a, b: a +(b, ), test_list, cur_eles)) # printing result print("The tuples after adding elements : " + str(res))
The original list is : [(3, 4), (78, 76), (2, 3)]
The tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jun, 2020"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "Sometimes, while working with Python records, we can have a problem in which we need to add custom column to tuples list. This kind of problem can have application in data domains such as web development. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 390,
"s": 296,
"text": "Input :test_list = [(3, ), (7, ), (2, )]cus_eles = [7, 8, 2]Output : [(3, 7), (7, 8), (2, 2)]"
},
{
"code": null,
"e": 466,
"s": 390,
"text": "Input :test_list = [(3, 9, 6, 10)]cus_eles = [7]Output : [(3, 9, 6, 10, 7)]"
},
{
"code": null,
"e": 672,
"s": 466,
"text": "Method #1 : Using list comprehension + zip()The combination of above functionalities can be used to solve this problem. In this, we perform the pairing of custom elements and tuples with the help of zip()."
},
{
"code": "# Python3 code to demonstrate working of # Add Custom Column to Tuple list# Using list comprehension + zip() # initializing listtest_list = [(3, 4), (78, 76), (2, 3)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing add listcus_eles = [17, 23, 12] # Add Custom Column to Tuple list# Using list comprehension + zip()res = [sub + (val, ) for sub, val in zip(test_list, cus_eles)] # printing result print(\"The tuples after adding elements : \" + str(res)) ",
"e": 1170,
"s": 672,
"text": null
},
{
"code": null,
"e": 1295,
"s": 1170,
"text": "The original list is : [(3, 4), (78, 76), (2, 3)]\nThe tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]\n"
},
{
"code": null,
"e": 1526,
"s": 1297,
"text": "Method #2 : Using map() + lambdaThe combination of above functions can also be used to solve this problem. In this, we perform the task of extending logic to each tuple using map() and lambda is used to perform task of addition."
},
{
"code": "# Python3 code to demonstrate working of # Add Custom Column to Tuple list# Using map() + lambda # initializing listtest_list = [(3, 4), (78, 76), (2, 3)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing add listcus_eles = [17, 23, 12] # Add Custom Column to Tuple list# Using map() + lambdares = list(map(lambda a, b: a +(b, ), test_list, cur_eles)) # printing result print(\"The tuples after adding elements : \" + str(res)) ",
"e": 1997,
"s": 1526,
"text": null
},
{
"code": null,
"e": 2122,
"s": 1997,
"text": "The original list is : [(3, 4), (78, 76), (2, 3)]\nThe tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]\n"
},
{
"code": null,
"e": 2143,
"s": 2122,
"text": "Python list-programs"
},
{
"code": null,
"e": 2150,
"s": 2143,
"text": "Python"
},
{
"code": null,
"e": 2166,
"s": 2150,
"text": "Python Programs"
}
] |
String Class stripTrailing() Method in Java with Examples | 02 Feb, 2021
This method is used to strip trailing whitespaces from the string i.e stripTrailing() method removes all the whitespaces only at the ending of the string.
Example:
Input:
String name = " kapil ";
System.out.println("#" + name + "#);
System.out.println("#" + name.stripLeading());
Output:
# kapil #
# kapil# // trailing whitespaces are removed
Syntax:
public String stripTrailing()
Parameter: It accepts no parameters.
Returns: The string after removing all the whitespaces at the end of the string.
Note: Like the stripTrailing() method in java, we have strip() (removes leading and trailing whitespace) and stripLeading() (removes the only leading whitespace).
Java
// Java program to demonstrate the usage of// stripTrailing() method in comparison to // other methods class GFG { public static void main(String[] args) { // creating a string String str = " Hello, World "; // print the string without any function System.out.println("String is"); System.out.println("#" + str + "#"); System.out.println(); // using strip() method System.out.println("Using strip()"); System.out.println("#" + str.strip() + "#"); System.out.println(); // using stripLeading() method System.out.println("Using stripLeading()"); System.out.println("#" + str.stripLeading() + "#"); System.out.println(); // using stripTrailing() method System.out.println("Using stripTrailing()"); System.out.println("#" + str.stripTrailing() + "#"); }}
String is
# Hello, World #
Using strip()
#Hello, World#
Using stripLeading()
#Hello, World #
Using stripTrailing()
# Hello, World#
Java-Strings
Picked
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "This method is used to strip trailing whitespaces from the string i.e stripTrailing() method removes all the whitespaces only at the ending of the string. "
},
{
"code": null,
"e": 193,
"s": 184,
"text": "Example:"
},
{
"code": null,
"e": 387,
"s": 193,
"text": "Input:\n\nString name = \" kapil \";\nSystem.out.println(\"#\" + name + \"#);\nSystem.out.println(\"#\" + name.stripLeading());\n\n\nOutput:\n\n# kapil #\n# kapil# // trailing whitespaces are removed "
},
{
"code": null,
"e": 395,
"s": 387,
"text": "Syntax:"
},
{
"code": null,
"e": 425,
"s": 395,
"text": "public String stripTrailing()"
},
{
"code": null,
"e": 462,
"s": 425,
"text": "Parameter: It accepts no parameters."
},
{
"code": null,
"e": 543,
"s": 462,
"text": "Returns: The string after removing all the whitespaces at the end of the string."
},
{
"code": null,
"e": 707,
"s": 543,
"text": "Note: Like the stripTrailing() method in java, we have strip() (removes leading and trailing whitespace) and stripLeading() (removes the only leading whitespace). "
},
{
"code": null,
"e": 712,
"s": 707,
"text": "Java"
},
{
"code": "// Java program to demonstrate the usage of// stripTrailing() method in comparison to // other methods class GFG { public static void main(String[] args) { // creating a string String str = \" Hello, World \"; // print the string without any function System.out.println(\"String is\"); System.out.println(\"#\" + str + \"#\"); System.out.println(); // using strip() method System.out.println(\"Using strip()\"); System.out.println(\"#\" + str.strip() + \"#\"); System.out.println(); // using stripLeading() method System.out.println(\"Using stripLeading()\"); System.out.println(\"#\" + str.stripLeading() + \"#\"); System.out.println(); // using stripTrailing() method System.out.println(\"Using stripTrailing()\"); System.out.println(\"#\" + str.stripTrailing() + \"#\"); }}",
"e": 1604,
"s": 712,
"text": null
},
{
"code": null,
"e": 1745,
"s": 1604,
"text": "String is\n# Hello, World #\n\nUsing strip()\n#Hello, World#\n\nUsing stripLeading()\n#Hello, World #\n\nUsing stripTrailing()\n# Hello, World#\n"
},
{
"code": null,
"e": 1758,
"s": 1745,
"text": "Java-Strings"
},
{
"code": null,
"e": 1765,
"s": 1758,
"text": "Picked"
},
{
"code": null,
"e": 1770,
"s": 1765,
"text": "Java"
},
{
"code": null,
"e": 1783,
"s": 1770,
"text": "Java-Strings"
},
{
"code": null,
"e": 1788,
"s": 1783,
"text": "Java"
},
{
"code": null,
"e": 1886,
"s": 1788,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1901,
"s": 1886,
"text": "Stream In Java"
},
{
"code": null,
"e": 1922,
"s": 1901,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1943,
"s": 1922,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1962,
"s": 1943,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1979,
"s": 1962,
"text": "Generics in Java"
},
{
"code": null,
"e": 2009,
"s": 1979,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2035,
"s": 2009,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2051,
"s": 2035,
"text": "Strings in Java"
},
{
"code": null,
"e": 2088,
"s": 2051,
"text": "Differences between JDK, JRE and JVM"
}
] |
GATE | GATE CS 2019 | Question 28 | 07 Sep, 2021
Consider the following given grammar:
S → Aa
A → BD
B → b|ε
D → d|ε
Let a, b, d and $ be indexed as follows:Compute the FOLLOW set of the non-terminal B and write the index values for the symbols in the FOLLOW set in the descending order. (For example, if the FOLLOW set is {a, b, d, $}, then the answer should be 3210).
Note: This was Numerical Type question.(A) 31(B) 310(C) 230(D) 23Answer: (A)Explanation: Follow (B) to be the set of terminals that can appear immediately to the right of Non-Terminal B in some sentential form.
Therefore,
Follow (B) = {d, a}
Hence their index in descending order is 31.
PYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0031:30 / 44:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9LF8Bby1Qhc" 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
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 2011 | Question 49 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 66,
"s": 28,
"text": "Consider the following given grammar:"
},
{
"code": null,
"e": 97,
"s": 66,
"text": "S → Aa\nA → BD\nB → b|ε\nD → d|ε "
},
{
"code": null,
"e": 350,
"s": 97,
"text": "Let a, b, d and $ be indexed as follows:Compute the FOLLOW set of the non-terminal B and write the index values for the symbols in the FOLLOW set in the descending order. (For example, if the FOLLOW set is {a, b, d, $}, then the answer should be 3210)."
},
{
"code": null,
"e": 561,
"s": 350,
"text": "Note: This was Numerical Type question.(A) 31(B) 310(C) 230(D) 23Answer: (A)Explanation: Follow (B) to be the set of terminals that can appear immediately to the right of Non-Terminal B in some sentential form."
},
{
"code": null,
"e": 572,
"s": 561,
"text": "Therefore,"
},
{
"code": null,
"e": 593,
"s": 572,
"text": "Follow (B) = {d, a} "
},
{
"code": null,
"e": 638,
"s": 593,
"text": "Hence their index in descending order is 31."
},
{
"code": null,
"e": 1624,
"s": 638,
"text": "PYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0031:30 / 44:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9LF8Bby1Qhc\" 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": 1629,
"s": 1624,
"text": "GATE"
},
{
"code": null,
"e": 1727,
"s": 1629,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1769,
"s": 1727,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1831,
"s": 1769,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1865,
"s": 1831,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1907,
"s": 1865,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1941,
"s": 1907,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1983,
"s": 1941,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 2025,
"s": 1983,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 2059,
"s": 2025,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 2093,
"s": 2059,
"text": "GATE | GATE-CS-2004 | Question 31"
}
] |
Split the array elements into strictly increasing and decreasing sequence | 21 Jun, 2022
Given an array of N elements. The task is to split the elements into two arrays say a1[] and a2[] such that one contains strictly increasing elements and the other contains strictly decreasing elements and a1.size() + a2.size() = a.size(). If it is not possible to do so, print -1 or else print both the arrays.
Note: There can be multiple answers and the order of elements needs not to be the same in the child arrays.
Examples:
Input: a[] = {7, 2, 7, 3, 3, 1, 4} Output: a1[] = {1, 2, 3, 4, 7} , a2[] = {7, 3}
Input: a[] = {1, 2, 2, 1, 1} Output: -1 It is not possible
Approach: The following steps are followed to solve the above problem:
Initialize two vectors v1 and v2 which stores increasing and decreasing numbers.
Use hashing to know the occurrence of the number in the array.
If the number appears to come for the first time, then store it in v1.
If the number appears to come for the second time, then store it in v2.
If the number appears for more than 2 times, then it is not possible to store to create a strictly increasing and strictly decreasing array.
At last, sort the first vector in increasing order and the second vector in decreasing order and print them.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print both the arraysvoid PrintBothArrays(int a[], int n){ // Store both arrays vector<int> v1, v2; // Used for hashing unordered_map<int, int> mpp; // Iterate for every element for (int i = 0; i < n; i++) { // Increase the count mpp[a[i]]++; // If first occurrence if (mpp[a[i]] == 1) v1.push_back(a[i]); // If second occurrence else if (mpp[a[i]] == 2) v2.push_back(a[i]); // If occurs more than 2 times else { cout << "Not possible"; return; } } // Sort in increasing order sort(v1.begin(), v1.end()); // Print the increasing array cout << "Strictly increasing array is:\n"; for (auto it : v1) cout << it << " "; // Sort in reverse order sort(v2.begin(), v2.end(), greater<int>()); // Print the decreasing array cout << "\nStrictly decreasing array is:\n"; for (auto it : v2) cout << it << " ";} // Driver codeint main(){ int a[] = { 7, 2, 7, 3, 3, 1, 4 }; int n = sizeof(a) / sizeof(a[0]); PrintBothArrays(a, n); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to print both the arraysstatic void PrintBothArrays(int a[], int n){ // Store both arrays Vector<Integer> v1 = new Vector<Integer>(), v2 = new Vector<Integer>(); // Used for hashing HashMap<Integer, Integer> mpp = new HashMap<>(); // Iterate for every element for (int i = 0; i < n; i++) { // Increase the count mpp.put(a[i],(mpp.get(a[i]) == null?0:mpp.get(a[i]))+1); // If first occurrence if (mpp.get(a[i]) == 1) v1.add(a[i]); // If second occurrence else if (mpp.get(a[i]) == 2) v2.add(a[i]); // If occurs more than 2 times else { System.out.println( "Not possible"); return; } } // Sort in increasing order Collections.sort(v1); // Print the increasing array System.out.println("Strictly increasing array is:"); for (int i = 0; i < v1.size(); i++) System.out.print(v1.get(i) + " "); // Sort Collections.sort(v2); Collections.reverse(v2); // Print the decreasing array System.out.println("\nStrictly decreasing array is:"); for (int i = 0; i < v2.size(); i++) System.out.print(v2.get(i) + " ");} // Driver codepublic static void main(String args[]){ int a[] = { 7, 2, 7, 3, 3, 1, 4 }; int n = a.length; PrintBothArrays(a, n);}} // This code is contributed by Arnab Kundu
# Python3 program to implement# the above approach # Function to print both the arraysdef PrintBothArrays(a, n) : # Store both arrays v1, v2 = [], []; # Used for hashing mpp = dict.fromkeys(a, 0); # Iterate for every element for i in range(n) : # Increase the count mpp[a[i]] += 1; # If first occurrence if (mpp[a[i]] == 1) : v1.append(a[i]); # If second occurrence elif (mpp[a[i]] == 2) : v2.append(a[i]); # If occurs more than 2 times else : print("Not possible"); return; # Sort in increasing order v1.sort(); # Print the increasing array print("Strictly increasing array is:"); for it in v1: print(it, end = " "); # Sort in reverse order v2.sort(reverse = True); # Print the decreasing array print("\nStrictly decreasing array is:"); for it in v2 : print(it, end = " ") # Driver codeif __name__ == "__main__" : a = [ 7, 2, 7, 3, 3, 1, 4 ]; n = len(a); PrintBothArrays(a, n); # This code is contributed by Ryuga
// C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to print both the arrays static void PrintBothArrays(int [] a, int n) { // Store both arrays List<int> v1 = new List<int>(); List<int> v2 = new List<int>(); // Used for hashing Dictionary<int, int> mpp = new Dictionary<int, int>(); // Iterate for every element for (int i = 0; i < n; i++) { // Increase the Count if(mpp.ContainsKey(a[i])) mpp[a[i]] = mpp[a[i]] + 1; else mpp[a[i]] = 1; // If first occurrence if (mpp[a[i]] == 1) v1.Add(a[i]); // If second occurrence else if (mpp[a[i]] == 2) v2.Add(a[i]); // If occurs more than 2 times else { Console.WriteLine( "Not possible"); return; } } // Sort in increasing order v1.Sort(); // Print the increasing array Console.WriteLine("Strictly increasing array is:"); for (int i = 0; i < v1.Count; i++) Console.Write(v1[i] + " "); // Sort v2.Sort(); v2.Reverse(); // Print the decreasing array Console.WriteLine("\nStrictly decreasing array is:"); for (int i = 0; i < v2.Count; i++) Console.Write(v2[i] + " "); } // Driver code public static void Main() { int [] a = { 7, 2, 7, 3, 3, 1, 4 }; int n = a.Length; PrintBothArrays(a, n); }} // This code is contributed by ihritik
<script> // Javascript implementation of the approach // Function to print both the arraysfunction PrletBothArrays(a, n){ // Store both arrays let v1 = [], v2 = []; // Used for hashing let mpp = new Map(); // Iterate for every element for (let i = 0; i < n; i++) { // Increase the count mpp.set(a[i],(mpp.get(a[i]) == null?0:mpp.get(a[i]))+1); // If first occurrence if (mpp.get(a[i]) == 1) v1.push(a[i]); // If second occurrence else if (mpp.get(a[i]) == 2) v2.push(a[i]); // If occurs more than 2 times else { document.write( "Not possible"); return; } } // Sort in increasing order v1.sort(); // Print the increasing array document.write("Strictly increasing array is:" + "<br/>"); for (let i = 0; i < v1.length; i++) document.write(v1[i] + " "); // Sort v2.sort(); v2.reverse(); // Print the decreasing array document.write("<br/>" + "\nStrictly decreasing array is:" + "<br/>"); for (let i = 0; i < v2.length; i++) document.write(v2[i] + " ");} // Driver code let a = [ 7, 2, 7, 3, 3, 1, 4 ]; let n = a.length; PrletBothArrays(a, n); // This code is contributed by sanjoy_62.</script>
Strictly increasing array is:
1 2 3 4 7
Strictly decreasing array is:
7 3
Time Complexity: O(N*logN), as in the worst case we will be using an inbuilt sort function to sort an array of size N. Where N is the number of elements in the array.
Auxiliary Space: O(N), as we are using extra space for the map and array v1 and v2. Where N is the length of the string.
ankthon
andrew1234
ihritik
sanjoy_62
simmytarika5
ankita_saini
rohitsingh07052
Constructive Algorithms
Arrays
Hash
Sorting
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
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Longest Consecutive Subsequence
Sort string of characters | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 367,
"s": 54,
"text": "Given an array of N elements. The task is to split the elements into two arrays say a1[] and a2[] such that one contains strictly increasing elements and the other contains strictly decreasing elements and a1.size() + a2.size() = a.size(). If it is not possible to do so, print -1 or else print both the arrays. "
},
{
"code": null,
"e": 476,
"s": 367,
"text": "Note: There can be multiple answers and the order of elements needs not to be the same in the child arrays. "
},
{
"code": null,
"e": 487,
"s": 476,
"text": "Examples: "
},
{
"code": null,
"e": 570,
"s": 487,
"text": "Input: a[] = {7, 2, 7, 3, 3, 1, 4} Output: a1[] = {1, 2, 3, 4, 7} , a2[] = {7, 3} "
},
{
"code": null,
"e": 630,
"s": 570,
"text": "Input: a[] = {1, 2, 2, 1, 1} Output: -1 It is not possible "
},
{
"code": null,
"e": 703,
"s": 630,
"text": "Approach: The following steps are followed to solve the above problem: "
},
{
"code": null,
"e": 784,
"s": 703,
"text": "Initialize two vectors v1 and v2 which stores increasing and decreasing numbers."
},
{
"code": null,
"e": 847,
"s": 784,
"text": "Use hashing to know the occurrence of the number in the array."
},
{
"code": null,
"e": 918,
"s": 847,
"text": "If the number appears to come for the first time, then store it in v1."
},
{
"code": null,
"e": 990,
"s": 918,
"text": "If the number appears to come for the second time, then store it in v2."
},
{
"code": null,
"e": 1131,
"s": 990,
"text": "If the number appears for more than 2 times, then it is not possible to store to create a strictly increasing and strictly decreasing array."
},
{
"code": null,
"e": 1240,
"s": 1131,
"text": "At last, sort the first vector in increasing order and the second vector in decreasing order and print them."
},
{
"code": null,
"e": 1293,
"s": 1240,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1297,
"s": 1293,
"text": "C++"
},
{
"code": null,
"e": 1302,
"s": 1297,
"text": "Java"
},
{
"code": null,
"e": 1310,
"s": 1302,
"text": "Python3"
},
{
"code": null,
"e": 1313,
"s": 1310,
"text": "C#"
},
{
"code": null,
"e": 1324,
"s": 1313,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print both the arraysvoid PrintBothArrays(int a[], int n){ // Store both arrays vector<int> v1, v2; // Used for hashing unordered_map<int, int> mpp; // Iterate for every element for (int i = 0; i < n; i++) { // Increase the count mpp[a[i]]++; // If first occurrence if (mpp[a[i]] == 1) v1.push_back(a[i]); // If second occurrence else if (mpp[a[i]] == 2) v2.push_back(a[i]); // If occurs more than 2 times else { cout << \"Not possible\"; return; } } // Sort in increasing order sort(v1.begin(), v1.end()); // Print the increasing array cout << \"Strictly increasing array is:\\n\"; for (auto it : v1) cout << it << \" \"; // Sort in reverse order sort(v2.begin(), v2.end(), greater<int>()); // Print the decreasing array cout << \"\\nStrictly decreasing array is:\\n\"; for (auto it : v2) cout << it << \" \";} // Driver codeint main(){ int a[] = { 7, 2, 7, 3, 3, 1, 4 }; int n = sizeof(a) / sizeof(a[0]); PrintBothArrays(a, n); return 0;}",
"e": 2557,
"s": 1324,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to print both the arraysstatic void PrintBothArrays(int a[], int n){ // Store both arrays Vector<Integer> v1 = new Vector<Integer>(), v2 = new Vector<Integer>(); // Used for hashing HashMap<Integer, Integer> mpp = new HashMap<>(); // Iterate for every element for (int i = 0; i < n; i++) { // Increase the count mpp.put(a[i],(mpp.get(a[i]) == null?0:mpp.get(a[i]))+1); // If first occurrence if (mpp.get(a[i]) == 1) v1.add(a[i]); // If second occurrence else if (mpp.get(a[i]) == 2) v2.add(a[i]); // If occurs more than 2 times else { System.out.println( \"Not possible\"); return; } } // Sort in increasing order Collections.sort(v1); // Print the increasing array System.out.println(\"Strictly increasing array is:\"); for (int i = 0; i < v1.size(); i++) System.out.print(v1.get(i) + \" \"); // Sort Collections.sort(v2); Collections.reverse(v2); // Print the decreasing array System.out.println(\"\\nStrictly decreasing array is:\"); for (int i = 0; i < v2.size(); i++) System.out.print(v2.get(i) + \" \");} // Driver codepublic static void main(String args[]){ int a[] = { 7, 2, 7, 3, 3, 1, 4 }; int n = a.length; PrintBothArrays(a, n);}} // This code is contributed by Arnab Kundu",
"e": 4052,
"s": 2557,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to print both the arraysdef PrintBothArrays(a, n) : # Store both arrays v1, v2 = [], []; # Used for hashing mpp = dict.fromkeys(a, 0); # Iterate for every element for i in range(n) : # Increase the count mpp[a[i]] += 1; # If first occurrence if (mpp[a[i]] == 1) : v1.append(a[i]); # If second occurrence elif (mpp[a[i]] == 2) : v2.append(a[i]); # If occurs more than 2 times else : print(\"Not possible\"); return; # Sort in increasing order v1.sort(); # Print the increasing array print(\"Strictly increasing array is:\"); for it in v1: print(it, end = \" \"); # Sort in reverse order v2.sort(reverse = True); # Print the decreasing array print(\"\\nStrictly decreasing array is:\"); for it in v2 : print(it, end = \" \") # Driver codeif __name__ == \"__main__\" : a = [ 7, 2, 7, 3, 3, 1, 4 ]; n = len(a); PrintBothArrays(a, n); # This code is contributed by Ryuga",
"e": 5150,
"s": 4052,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to print both the arrays static void PrintBothArrays(int [] a, int n) { // Store both arrays List<int> v1 = new List<int>(); List<int> v2 = new List<int>(); // Used for hashing Dictionary<int, int> mpp = new Dictionary<int, int>(); // Iterate for every element for (int i = 0; i < n; i++) { // Increase the Count if(mpp.ContainsKey(a[i])) mpp[a[i]] = mpp[a[i]] + 1; else mpp[a[i]] = 1; // If first occurrence if (mpp[a[i]] == 1) v1.Add(a[i]); // If second occurrence else if (mpp[a[i]] == 2) v2.Add(a[i]); // If occurs more than 2 times else { Console.WriteLine( \"Not possible\"); return; } } // Sort in increasing order v1.Sort(); // Print the increasing array Console.WriteLine(\"Strictly increasing array is:\"); for (int i = 0; i < v1.Count; i++) Console.Write(v1[i] + \" \"); // Sort v2.Sort(); v2.Reverse(); // Print the decreasing array Console.WriteLine(\"\\nStrictly decreasing array is:\"); for (int i = 0; i < v2.Count; i++) Console.Write(v2[i] + \" \"); } // Driver code public static void Main() { int [] a = { 7, 2, 7, 3, 3, 1, 4 }; int n = a.Length; PrintBothArrays(a, n); }} // This code is contributed by ihritik",
"e": 6903,
"s": 5150,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to print both the arraysfunction PrletBothArrays(a, n){ // Store both arrays let v1 = [], v2 = []; // Used for hashing let mpp = new Map(); // Iterate for every element for (let i = 0; i < n; i++) { // Increase the count mpp.set(a[i],(mpp.get(a[i]) == null?0:mpp.get(a[i]))+1); // If first occurrence if (mpp.get(a[i]) == 1) v1.push(a[i]); // If second occurrence else if (mpp.get(a[i]) == 2) v2.push(a[i]); // If occurs more than 2 times else { document.write( \"Not possible\"); return; } } // Sort in increasing order v1.sort(); // Print the increasing array document.write(\"Strictly increasing array is:\" + \"<br/>\"); for (let i = 0; i < v1.length; i++) document.write(v1[i] + \" \"); // Sort v2.sort(); v2.reverse(); // Print the decreasing array document.write(\"<br/>\" + \"\\nStrictly decreasing array is:\" + \"<br/>\"); for (let i = 0; i < v2.length; i++) document.write(v2[i] + \" \");} // Driver code let a = [ 7, 2, 7, 3, 3, 1, 4 ]; let n = a.length; PrletBothArrays(a, n); // This code is contributed by sanjoy_62.</script>",
"e": 8240,
"s": 6903,
"text": null
},
{
"code": null,
"e": 8315,
"s": 8240,
"text": "Strictly increasing array is:\n1 2 3 4 7 \nStrictly decreasing array is:\n7 3"
},
{
"code": null,
"e": 8484,
"s": 8317,
"text": "Time Complexity: O(N*logN), as in the worst case we will be using an inbuilt sort function to sort an array of size N. Where N is the number of elements in the array."
},
{
"code": null,
"e": 8605,
"s": 8484,
"text": "Auxiliary Space: O(N), as we are using extra space for the map and array v1 and v2. Where N is the length of the string."
},
{
"code": null,
"e": 8613,
"s": 8605,
"text": "ankthon"
},
{
"code": null,
"e": 8624,
"s": 8613,
"text": "andrew1234"
},
{
"code": null,
"e": 8632,
"s": 8624,
"text": "ihritik"
},
{
"code": null,
"e": 8642,
"s": 8632,
"text": "sanjoy_62"
},
{
"code": null,
"e": 8655,
"s": 8642,
"text": "simmytarika5"
},
{
"code": null,
"e": 8668,
"s": 8655,
"text": "ankita_saini"
},
{
"code": null,
"e": 8684,
"s": 8668,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 8708,
"s": 8684,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 8715,
"s": 8708,
"text": "Arrays"
},
{
"code": null,
"e": 8720,
"s": 8715,
"text": "Hash"
},
{
"code": null,
"e": 8728,
"s": 8720,
"text": "Sorting"
},
{
"code": null,
"e": 8735,
"s": 8728,
"text": "Arrays"
},
{
"code": null,
"e": 8740,
"s": 8735,
"text": "Hash"
},
{
"code": null,
"e": 8748,
"s": 8740,
"text": "Sorting"
},
{
"code": null,
"e": 8846,
"s": 8748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8914,
"s": 8846,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8958,
"s": 8914,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 8990,
"s": 8958,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9038,
"s": 8990,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 9052,
"s": 9038,
"text": "Linear Search"
},
{
"code": null,
"e": 9090,
"s": 9052,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 9126,
"s": 9090,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 9157,
"s": 9126,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 9189,
"s": 9157,
"text": "Longest Consecutive Subsequence"
}
] |
Python | Pandas Series.to_dict() | 05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_dict() function is used to convert the given Series object to {label -> value} dict or dict-like object.
Syntax: Series.to_dict(into=)
Parameter :into : The collections.Mapping subclass to use as the return object.
Returns : value_dict : collections.Mapping
Example #1: Use Series.to_dict() function to convert the given series object to a dictionary.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)
Output :
Now we will use Series.to_dict() function to convert the given series object to a dictionary.
# convert to dictionarysr.to_dict()
Output :
As we can see in the output, the Series.to_dict() function has successfully converted the given series object to a dictionary. Example #2: Use Series.to_dict() function to convert the given series object to a dictionary.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr)
Output :
Now we will use Series.to_dict() function to convert the given series object to a dictionary.
# convert to dictionarysr.to_dict()
Output :
As we can see in the output, the Series.to_dict() function has successfully converted the given series object to a dictionary.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Introduction To PYTHON
Python | os.path.join() method
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 407,
"s": 285,
"text": "Pandas Series.to_dict() function is used to convert the given Series object to {label -> value} dict or dict-like object."
},
{
"code": null,
"e": 437,
"s": 407,
"text": "Syntax: Series.to_dict(into=)"
},
{
"code": null,
"e": 517,
"s": 437,
"text": "Parameter :into : The collections.Mapping subclass to use as the return object."
},
{
"code": null,
"e": 560,
"s": 517,
"text": "Returns : value_dict : collections.Mapping"
},
{
"code": null,
"e": 654,
"s": 560,
"text": "Example #1: Use Series.to_dict() function to convert the given series object to a dictionary."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)",
"e": 1006,
"s": 654,
"text": null
},
{
"code": null,
"e": 1015,
"s": 1006,
"text": "Output :"
},
{
"code": null,
"e": 1109,
"s": 1015,
"text": "Now we will use Series.to_dict() function to convert the given series object to a dictionary."
},
{
"code": "# convert to dictionarysr.to_dict()",
"e": 1145,
"s": 1109,
"text": null
},
{
"code": null,
"e": 1154,
"s": 1145,
"text": "Output :"
},
{
"code": null,
"e": 1375,
"s": 1154,
"text": "As we can see in the output, the Series.to_dict() function has successfully converted the given series object to a dictionary. Example #2: Use Series.to_dict() function to convert the given series object to a dictionary."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr)",
"e": 1523,
"s": 1375,
"text": null
},
{
"code": null,
"e": 1532,
"s": 1523,
"text": "Output :"
},
{
"code": null,
"e": 1626,
"s": 1532,
"text": "Now we will use Series.to_dict() function to convert the given series object to a dictionary."
},
{
"code": "# convert to dictionarysr.to_dict()",
"e": 1662,
"s": 1626,
"text": null
},
{
"code": null,
"e": 1671,
"s": 1662,
"text": "Output :"
},
{
"code": null,
"e": 1798,
"s": 1671,
"text": "As we can see in the output, the Series.to_dict() function has successfully converted the given series object to a dictionary."
},
{
"code": null,
"e": 1819,
"s": 1798,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1848,
"s": 1819,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 1862,
"s": 1848,
"text": "Python-pandas"
},
{
"code": null,
"e": 1869,
"s": 1862,
"text": "Python"
},
{
"code": null,
"e": 1967,
"s": 1869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1985,
"s": 1967,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2027,
"s": 1985,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2049,
"s": 2027,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2081,
"s": 2049,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2110,
"s": 2081,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2137,
"s": 2110,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2158,
"s": 2137,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2181,
"s": 2158,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2212,
"s": 2181,
"text": "Python | os.path.join() method"
}
] |
Subsets and Splits