title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Exposing Localhost Server over Internet Using ngrok and VS Code
|
07 Aug, 2020
We setup and build many projects but before moving them to the production server, we always test the project, and we share the project among our team to share the progress, we share our project code on GitHub as it supports version control system and, but what if we do not want to share the code, but we only need to share the outcome to the client, preferably we consider localhost to show the outcome of the project to the client, for big or ongoing projects there will be more than a client if clients are at different locations we use the screen share option in a video call to show the working.
But the drawback of screen share is, the client only sees the working demo, not the actual hands-on experience. To overcome this issue we have a tool called ‘ngrok’ to globally share the projects which are available on localhost.
Using ngrok tool we get a unique URL to share our project globally for free of cost(with some limitations).
1. Go to ngrok.com
2. SignUP & Download ngrok software from the Setup and Installation section of the website.
Dashboard image after signing in
3. Download the software package as per your Operating System. ngrok software will be downloaded in a zip format, after downloading ngrok software extract the files to the desired location and name the extracted folder as ngrok.
4. Open Visual Studio Code application.
5. Create or Open your project
6. Now, install live server extension on VS Code editor and click on “Go Live” button on the bottom bar
Install “Live Server” extension from Extensions: Marketplace in the editor itself
Go Live for running the project on localhost server
7. After clicking on Go Live, project will be hosted on the local host server.
1. Now open a new terminal on VS Code or use the shortcut key ctrl+shift+` .
2. Enter the following commands :
cd <location_to_ngrok_folder>
ngrok authtoken <your_auth_token>
3. Replace <location_to_ngrok_folder> with the address of your ngrok extracted folder and <your_auth_token> with the authentication token which is present on the ngrok dashboard or from here.
Executing the above commands will return the following output.
After giving line 1, next line is generated automatically
4. Enter the following command to expose localhost over Internet
ngrok.exe http 5500
Note: 5500 is the port number, give your port number accordingly
The above command will display the output similar to the following
Here:
Web Interface link is to get the statistics of the shared URL
Forwarding url’s with ngrok domain name are the actual links to share the localhost project
5. To stop the url from surfing online press ctrl+c key combination on the terminal .
Note: To set password to url, we must login to ngrok and connect our ngrok account using auth key.
Type this command in the terminal of the code editor:
ngrok http -auth="<username>:<password>" 5500
Replace <username> with your respective username and <password> with your respective password and 5500 with the respective port.
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
SORT command in Linux/Unix with examples
curl command in Linux with Examples
TCP Server-Client implementation in C
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 629,
"s": 28,
"text": "We setup and build many projects but before moving them to the production server, we always test the project, and we share the project among our team to share the progress, we share our project code on GitHub as it supports version control system and, but what if we do not want to share the code, but we only need to share the outcome to the client, preferably we consider localhost to show the outcome of the project to the client, for big or ongoing projects there will be more than a client if clients are at different locations we use the screen share option in a video call to show the working."
},
{
"code": null,
"e": 859,
"s": 629,
"text": "But the drawback of screen share is, the client only sees the working demo, not the actual hands-on experience. To overcome this issue we have a tool called ‘ngrok’ to globally share the projects which are available on localhost."
},
{
"code": null,
"e": 967,
"s": 859,
"text": "Using ngrok tool we get a unique URL to share our project globally for free of cost(with some limitations)."
},
{
"code": null,
"e": 986,
"s": 967,
"text": "1. Go to ngrok.com"
},
{
"code": null,
"e": 1078,
"s": 986,
"text": "2. SignUP & Download ngrok software from the Setup and Installation section of the website."
},
{
"code": null,
"e": 1111,
"s": 1078,
"text": "Dashboard image after signing in"
},
{
"code": null,
"e": 1340,
"s": 1111,
"text": "3. Download the software package as per your Operating System. ngrok software will be downloaded in a zip format, after downloading ngrok software extract the files to the desired location and name the extracted folder as ngrok."
},
{
"code": null,
"e": 1380,
"s": 1340,
"text": "4. Open Visual Studio Code application."
},
{
"code": null,
"e": 1411,
"s": 1380,
"text": "5. Create or Open your project"
},
{
"code": null,
"e": 1515,
"s": 1411,
"text": "6. Now, install live server extension on VS Code editor and click on “Go Live” button on the bottom bar"
},
{
"code": null,
"e": 1597,
"s": 1515,
"text": "Install “Live Server” extension from Extensions: Marketplace in the editor itself"
},
{
"code": null,
"e": 1649,
"s": 1597,
"text": "Go Live for running the project on localhost server"
},
{
"code": null,
"e": 1728,
"s": 1649,
"text": "7. After clicking on Go Live, project will be hosted on the local host server."
},
{
"code": null,
"e": 1805,
"s": 1728,
"text": "1. Now open a new terminal on VS Code or use the shortcut key ctrl+shift+` ."
},
{
"code": null,
"e": 1852,
"s": 1805,
"text": "2. Enter the following commands : "
},
{
"code": null,
"e": 1916,
"s": 1852,
"text": "cd <location_to_ngrok_folder>\nngrok authtoken <your_auth_token>"
},
{
"code": null,
"e": 2108,
"s": 1916,
"text": "3. Replace <location_to_ngrok_folder> with the address of your ngrok extracted folder and <your_auth_token> with the authentication token which is present on the ngrok dashboard or from here."
},
{
"code": null,
"e": 2171,
"s": 2108,
"text": "Executing the above commands will return the following output."
},
{
"code": null,
"e": 2229,
"s": 2171,
"text": "After giving line 1, next line is generated automatically"
},
{
"code": null,
"e": 2294,
"s": 2229,
"text": "4. Enter the following command to expose localhost over Internet"
},
{
"code": null,
"e": 2321,
"s": 2294,
"text": "ngrok.exe http 5500 "
},
{
"code": null,
"e": 2386,
"s": 2321,
"text": "Note: 5500 is the port number, give your port number accordingly"
},
{
"code": null,
"e": 2453,
"s": 2386,
"text": "The above command will display the output similar to the following"
},
{
"code": null,
"e": 2459,
"s": 2453,
"text": "Here:"
},
{
"code": null,
"e": 2521,
"s": 2459,
"text": "Web Interface link is to get the statistics of the shared URL"
},
{
"code": null,
"e": 2613,
"s": 2521,
"text": "Forwarding url’s with ngrok domain name are the actual links to share the localhost project"
},
{
"code": null,
"e": 2699,
"s": 2613,
"text": "5. To stop the url from surfing online press ctrl+c key combination on the terminal ."
},
{
"code": null,
"e": 2798,
"s": 2699,
"text": "Note: To set password to url, we must login to ngrok and connect our ngrok account using auth key."
},
{
"code": null,
"e": 2852,
"s": 2798,
"text": "Type this command in the terminal of the code editor:"
},
{
"code": null,
"e": 2899,
"s": 2852,
"text": "ngrok http -auth=\"<username>:<password>\" 5500\n"
},
{
"code": null,
"e": 3029,
"s": 2899,
"text": "Replace <username> with your respective username and <password> with your respective password and 5500 with the respective port."
},
{
"code": null,
"e": 3040,
"s": 3029,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3049,
"s": 3040,
"text": "TechTips"
},
{
"code": null,
"e": 3147,
"s": 3049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3182,
"s": 3147,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 3217,
"s": 3182,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3258,
"s": 3217,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 3294,
"s": 3258,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 3332,
"s": 3294,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3385,
"s": 3332,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 3411,
"s": 3385,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3446,
"s": 3411,
"text": "Setting up the environment in Java"
},
{
"code": null,
"e": 3487,
"s": 3446,
"text": "How to Run a Python Script using Docker?"
}
] |
GTest Framework
|
28 Jan, 2021
It is a test framework i.e., a software tool for writing and running unit tests.
It is a library for writing C++ tests.
It is based on xUnit architecture which is a set of “Frameworks” for programming and automated execution of test cases.
Googletest helps us to write better C++ tests.
Independent and Repeatable: Googletest isolates the tests by running each of them on a different object.
Portable and Reusable: Googletest works on different Oses (Linux, Windows, or a Mac), with different compilers.
When tests fail, it should provide as much information about the problem as possible.
TestSuite:It is used for grouping related tests.
TEST(): It exercises a particular program path with specific input values and verify the result.
Assertions:A statements that check whether a condition is true.Output: success, nonfatal failure, or fatal failure(aborts the current function).
A statements that check whether a condition is true.
Output: success, nonfatal failure, or fatal failure(aborts the current function).
Test fixture class:Collection of multiple tests in a test suite that need to share common objects and subroutines.
Collection of multiple tests in a test suite that need to share common objects and subroutines.
In below lines * represent multiple character such as EQ / NE / LT / LE / GT / GE.
ASSERT_*: Generate fatal failures when they fail, and abort the current function immediately. (possibly skipping clean-up code that comes after it, it may cause a space leak).
EXPECT_*:Generate nonfatal failures, which don’t abort the current function.
Examples:ASSERT_EQ, ASSERT_NE, ASSERT_LT, ASSERT_GT, ASSERT_GE.EXPECT_WQ, EXPECT_NE, EXPECT_LT, EXPECT_GT, EXPECT_GE.
ASSERT_EQ, ASSERT_NE, ASSERT_LT, ASSERT_GT, ASSERT_GE.
EXPECT_WQ, EXPECT_NE, EXPECT_LT, EXPECT_GT, EXPECT_GE.
A macro to define and name a test function.
Use the various Googletest assertions to check values.
If any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
TEST(TestSuiteName, TestName) {
... test body ...
}
Using the Same Data Configuration for Multiple Tests.
Derive a class from ::testing::Test. Start its body with protected:, as we will want to access fixture members from sub-classes.
If necessary, write a default constructor or SetUp().
If necessary, write a default destructor or TearDown().
Use TEST_F(), instead of TEST().
TEST_F(TestFixtureName, TestName) {
... test body ...
}
RUN_ALL_TESTS();Returns 0: All tests are successful.Returns 1: otherwise.
Returns 0: All tests are successful.
Returns 1: otherwise.
A factorial function:
int factorial(int n)
{
// If n < 1;
return -1;
// Else factorial = n!;
return factorial;
}
TEST(FactorialTest, FactorialOfZeroShouldBeOne)
{
ASSERT_EQ(1, factorial(0));
}
TEST(FactorialTest, FactorialOfPositiveNos)
{
ASSERT_EQ(1, factorial(1));
ASSERT_EQ(24, factorial(4));
ASSERT_EQ(120, factorial(5));
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Dump the output into XML format by passing:
–gtest_output=”xml:report.xml”
If want to run multiple times:
–gtest_repeat=2
Debugger invoked on failure:
–gtest_break_on_failure
Not all the tests needs to be run all the times:
–gtest_filter=<test string>
Software Testing
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - InkWell Widget
Asymptotic Notations and how to calculate them
How to use gotoxy() in codeblocks?
File globbing in Linux
Print all subsequences of a string using ArrayList
Draw a circle without floating point arithmetic
What's difference between Microcontroller (μC) and Microprocessor (μP)?
HQL | Introduction
What's difference between MMU and MPU?
Tips to Manage Docker Containers using CLI
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 134,
"s": 53,
"text": "It is a test framework i.e., a software tool for writing and running unit tests."
},
{
"code": null,
"e": 173,
"s": 134,
"text": "It is a library for writing C++ tests."
},
{
"code": null,
"e": 293,
"s": 173,
"text": "It is based on xUnit architecture which is a set of “Frameworks” for programming and automated execution of test cases."
},
{
"code": null,
"e": 340,
"s": 293,
"text": "Googletest helps us to write better C++ tests."
},
{
"code": null,
"e": 445,
"s": 340,
"text": "Independent and Repeatable: Googletest isolates the tests by running each of them on a different object."
},
{
"code": null,
"e": 557,
"s": 445,
"text": "Portable and Reusable: Googletest works on different Oses (Linux, Windows, or a Mac), with different compilers."
},
{
"code": null,
"e": 643,
"s": 557,
"text": "When tests fail, it should provide as much information about the problem as possible."
},
{
"code": null,
"e": 692,
"s": 643,
"text": "TestSuite:It is used for grouping related tests."
},
{
"code": null,
"e": 789,
"s": 692,
"text": "TEST(): It exercises a particular program path with specific input values and verify the result."
},
{
"code": null,
"e": 934,
"s": 789,
"text": "Assertions:A statements that check whether a condition is true.Output: success, nonfatal failure, or fatal failure(aborts the current function)."
},
{
"code": null,
"e": 987,
"s": 934,
"text": "A statements that check whether a condition is true."
},
{
"code": null,
"e": 1069,
"s": 987,
"text": "Output: success, nonfatal failure, or fatal failure(aborts the current function)."
},
{
"code": null,
"e": 1184,
"s": 1069,
"text": "Test fixture class:Collection of multiple tests in a test suite that need to share common objects and subroutines."
},
{
"code": null,
"e": 1280,
"s": 1184,
"text": "Collection of multiple tests in a test suite that need to share common objects and subroutines."
},
{
"code": null,
"e": 1363,
"s": 1280,
"text": "In below lines * represent multiple character such as EQ / NE / LT / LE / GT / GE."
},
{
"code": null,
"e": 1539,
"s": 1363,
"text": "ASSERT_*: Generate fatal failures when they fail, and abort the current function immediately. (possibly skipping clean-up code that comes after it, it may cause a space leak)."
},
{
"code": null,
"e": 1616,
"s": 1539,
"text": "EXPECT_*:Generate nonfatal failures, which don’t abort the current function."
},
{
"code": null,
"e": 1734,
"s": 1616,
"text": "Examples:ASSERT_EQ, ASSERT_NE, ASSERT_LT, ASSERT_GT, ASSERT_GE.EXPECT_WQ, EXPECT_NE, EXPECT_LT, EXPECT_GT, EXPECT_GE."
},
{
"code": null,
"e": 1789,
"s": 1734,
"text": "ASSERT_EQ, ASSERT_NE, ASSERT_LT, ASSERT_GT, ASSERT_GE."
},
{
"code": null,
"e": 1844,
"s": 1789,
"text": "EXPECT_WQ, EXPECT_NE, EXPECT_LT, EXPECT_GT, EXPECT_GE."
},
{
"code": null,
"e": 1888,
"s": 1844,
"text": "A macro to define and name a test function."
},
{
"code": null,
"e": 1943,
"s": 1888,
"text": "Use the various Googletest assertions to check values."
},
{
"code": null,
"e": 2082,
"s": 1943,
"text": "If any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds."
},
{
"code": null,
"e": 2146,
"s": 2082,
"text": " TEST(TestSuiteName, TestName) {\n ... test body ...\n }"
},
{
"code": null,
"e": 2200,
"s": 2146,
"text": "Using the Same Data Configuration for Multiple Tests."
},
{
"code": null,
"e": 2329,
"s": 2200,
"text": "Derive a class from ::testing::Test. Start its body with protected:, as we will want to access fixture members from sub-classes."
},
{
"code": null,
"e": 2383,
"s": 2329,
"text": "If necessary, write a default constructor or SetUp()."
},
{
"code": null,
"e": 2439,
"s": 2383,
"text": "If necessary, write a default destructor or TearDown()."
},
{
"code": null,
"e": 2472,
"s": 2439,
"text": "Use TEST_F(), instead of TEST()."
},
{
"code": null,
"e": 2531,
"s": 2472,
"text": "TEST_F(TestFixtureName, TestName) {\n ... test body ...\n}"
},
{
"code": null,
"e": 2605,
"s": 2531,
"text": "RUN_ALL_TESTS();Returns 0: All tests are successful.Returns 1: otherwise."
},
{
"code": null,
"e": 2642,
"s": 2605,
"text": "Returns 0: All tests are successful."
},
{
"code": null,
"e": 2664,
"s": 2642,
"text": "Returns 1: otherwise."
},
{
"code": null,
"e": 2686,
"s": 2664,
"text": "A factorial function:"
},
{
"code": null,
"e": 2798,
"s": 2686,
"text": "int factorial(int n)\n{\n // If n < 1;\n return -1;\n \n // Else factorial = n!;\n return factorial;\n}"
},
{
"code": null,
"e": 2882,
"s": 2798,
"text": "TEST(FactorialTest, FactorialOfZeroShouldBeOne)\n{\n ASSERT_EQ(1, factorial(0));\n}"
},
{
"code": null,
"e": 3029,
"s": 2882,
"text": "TEST(FactorialTest, FactorialOfPositiveNos)\n{\n ASSERT_EQ(1, factorial(1));\n ASSERT_EQ(24, factorial(4));\n ASSERT_EQ(120, factorial(5));\n}"
},
{
"code": null,
"e": 3135,
"s": 3029,
"text": "int main(int argc, char **argv)\n{\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}"
},
{
"code": null,
"e": 3179,
"s": 3135,
"text": "Dump the output into XML format by passing:"
},
{
"code": null,
"e": 3210,
"s": 3179,
"text": "–gtest_output=”xml:report.xml”"
},
{
"code": null,
"e": 3241,
"s": 3210,
"text": "If want to run multiple times:"
},
{
"code": null,
"e": 3257,
"s": 3241,
"text": "–gtest_repeat=2"
},
{
"code": null,
"e": 3286,
"s": 3257,
"text": "Debugger invoked on failure:"
},
{
"code": null,
"e": 3310,
"s": 3286,
"text": "–gtest_break_on_failure"
},
{
"code": null,
"e": 3359,
"s": 3310,
"text": "Not all the tests needs to be run all the times:"
},
{
"code": null,
"e": 3387,
"s": 3359,
"text": "–gtest_filter=<test string>"
},
{
"code": null,
"e": 3404,
"s": 3387,
"text": "Software Testing"
},
{
"code": null,
"e": 3413,
"s": 3404,
"text": "Articles"
},
{
"code": null,
"e": 3511,
"s": 3413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3536,
"s": 3511,
"text": "Flutter - InkWell Widget"
},
{
"code": null,
"e": 3583,
"s": 3536,
"text": "Asymptotic Notations and how to calculate them"
},
{
"code": null,
"e": 3618,
"s": 3583,
"text": "How to use gotoxy() in codeblocks?"
},
{
"code": null,
"e": 3641,
"s": 3618,
"text": "File globbing in Linux"
},
{
"code": null,
"e": 3692,
"s": 3641,
"text": "Print all subsequences of a string using ArrayList"
},
{
"code": null,
"e": 3740,
"s": 3692,
"text": "Draw a circle without floating point arithmetic"
},
{
"code": null,
"e": 3812,
"s": 3740,
"text": "What's difference between Microcontroller (μC) and Microprocessor (μP)?"
},
{
"code": null,
"e": 3831,
"s": 3812,
"text": "HQL | Introduction"
},
{
"code": null,
"e": 3870,
"s": 3831,
"text": "What's difference between MMU and MPU?"
}
] |
How to remove extension from string in PHP?
|
16 Feb, 2019
There are three ways of removing an extension from string. They are as follows
Using an inbuilt function pathinfo
Using an inbuilt function basename
Using an string functions substr and strrpos
Using pathinfo() Function: The pathinfo() function returns an array containing the directory name, basename, extension and filename.
Syntax:
pathinfo ( $path, $options = PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME )
Alternatively, if only one PATHINFO_ constants is passed as a parameter it returns only that part of the full filename.
Example:
<?php // Initializing a variable with filename$file = 'filename.html'; // Extracting only filename using constants$x = pathinfo($file, PATHINFO_FILENAME); // Printing the resultecho $x; ?>
filename
Note: If the filename contains a full path, then only the filename without the extension is returned.
Using basename() Function: The basename() function is used to return trailing name component of path in the form of string. The basename() operates naively on the input string, and is not aware of the actual file-system, or path components such as “..”Syntax:
basename ( $path, $suffix )
When an extension of file is known it can be passed as a parameter to basename function to tell it to remove that extension from the filename.
Example:
<?php // Initializing a variable// with filename$file = 'filename.txt'; // Suffix is passed as second// parameter$x = basename($file, '.txt'); // Printing the resultecho $x; ?>
filename
Using substr()and strrpos() function: Another way of removing an extension from a filename is using the string functions substr and strrpos. The substr() function returns the part of string whereas strrpos() finds the position of last occurrence of substring in a string.
Syntax:
substr ( $string, $start, $length )
Example:
<?php // Initializing a variable// with filename$file = 'filename.txt'; // Using substr $x = substr($file, 0, strrpos($file, '.')); // Display the filenameecho $x; ?>
filename
Note: If the filename contains a full path, then the full path and filename without the extension is returned.
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Feb, 2019"
},
{
"code": null,
"e": 107,
"s": 28,
"text": "There are three ways of removing an extension from string. They are as follows"
},
{
"code": null,
"e": 142,
"s": 107,
"text": "Using an inbuilt function pathinfo"
},
{
"code": null,
"e": 177,
"s": 142,
"text": "Using an inbuilt function basename"
},
{
"code": null,
"e": 222,
"s": 177,
"text": "Using an string functions substr and strrpos"
},
{
"code": null,
"e": 355,
"s": 222,
"text": "Using pathinfo() Function: The pathinfo() function returns an array containing the directory name, basename, extension and filename."
},
{
"code": null,
"e": 363,
"s": 355,
"text": "Syntax:"
},
{
"code": null,
"e": 466,
"s": 363,
"text": "pathinfo ( $path, $options = PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME )"
},
{
"code": null,
"e": 586,
"s": 466,
"text": "Alternatively, if only one PATHINFO_ constants is passed as a parameter it returns only that part of the full filename."
},
{
"code": null,
"e": 595,
"s": 586,
"text": "Example:"
},
{
"code": "<?php // Initializing a variable with filename$file = 'filename.html'; // Extracting only filename using constants$x = pathinfo($file, PATHINFO_FILENAME); // Printing the resultecho $x; ?>",
"e": 788,
"s": 595,
"text": null
},
{
"code": null,
"e": 798,
"s": 788,
"text": "filename\n"
},
{
"code": null,
"e": 900,
"s": 798,
"text": "Note: If the filename contains a full path, then only the filename without the extension is returned."
},
{
"code": null,
"e": 1160,
"s": 900,
"text": "Using basename() Function: The basename() function is used to return trailing name component of path in the form of string. The basename() operates naively on the input string, and is not aware of the actual file-system, or path components such as “..”Syntax:"
},
{
"code": null,
"e": 1188,
"s": 1160,
"text": "basename ( $path, $suffix )"
},
{
"code": null,
"e": 1331,
"s": 1188,
"text": "When an extension of file is known it can be passed as a parameter to basename function to tell it to remove that extension from the filename."
},
{
"code": null,
"e": 1340,
"s": 1331,
"text": "Example:"
},
{
"code": "<?php // Initializing a variable// with filename$file = 'filename.txt'; // Suffix is passed as second// parameter$x = basename($file, '.txt'); // Printing the resultecho $x; ?>",
"e": 1521,
"s": 1340,
"text": null
},
{
"code": null,
"e": 1531,
"s": 1521,
"text": "filename\n"
},
{
"code": null,
"e": 1803,
"s": 1531,
"text": "Using substr()and strrpos() function: Another way of removing an extension from a filename is using the string functions substr and strrpos. The substr() function returns the part of string whereas strrpos() finds the position of last occurrence of substring in a string."
},
{
"code": null,
"e": 1811,
"s": 1803,
"text": "Syntax:"
},
{
"code": null,
"e": 1847,
"s": 1811,
"text": "substr ( $string, $start, $length )"
},
{
"code": null,
"e": 1856,
"s": 1847,
"text": "Example:"
},
{
"code": "<?php // Initializing a variable// with filename$file = 'filename.txt'; // Using substr $x = substr($file, 0, strrpos($file, '.')); // Display the filenameecho $x; ?>",
"e": 2027,
"s": 1856,
"text": null
},
{
"code": null,
"e": 2037,
"s": 2027,
"text": "filename\n"
},
{
"code": null,
"e": 2148,
"s": 2037,
"text": "Note: If the filename contains a full path, then the full path and filename without the extension is returned."
},
{
"code": null,
"e": 2155,
"s": 2148,
"text": "Picked"
},
{
"code": null,
"e": 2159,
"s": 2155,
"text": "PHP"
},
{
"code": null,
"e": 2172,
"s": 2159,
"text": "PHP Programs"
},
{
"code": null,
"e": 2189,
"s": 2172,
"text": "Web Technologies"
},
{
"code": null,
"e": 2193,
"s": 2189,
"text": "PHP"
},
{
"code": null,
"e": 2291,
"s": 2193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2341,
"s": 2291,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2381,
"s": 2341,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2431,
"s": 2381,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2476,
"s": 2431,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2503,
"s": 2476,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 2553,
"s": 2503,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2593,
"s": 2553,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2643,
"s": 2593,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2695,
"s": 2643,
"text": "How to call PHP function on the click of a Button ?"
}
] |
How to create a table with clickable hyperlink to a local file in Pandas?
|
15 Mar, 2021
If you are familiar with Data Science or Machine Learning field then we can definitely say that we are going to learn something new from this article, So let’s begin. Here in this article, we will learn how to create a clickable hyperlink of the local file path using pandas. It is not a very complicated task, we can easily do it in only 4 to 5 steps. Let’s dig deeper into it and talk about required libraries.
Pandas: It is one of the most favorite and popular libraries in python for data wrangling and analysis. Pandas is the backbone of all Data Science and Machine Learning projects. It is one of the most important tools for Data Scientists and Analysts. Some features of pandas are: Data Handling, Alignment and indexing, Handling missing data, Cleaning data, Merging and joining of datasets, and much more. Here as well we will use pandas to create a dataset.
OS library: The OS module present in python also plays a very important role in various projects. It provides lots of functions for interacting with the operating system. It includes many functions to interact with the file system as well. Here we have to work with local files that’s why we need an os module to handle them.
Steps Needed
Step 1: Import required libraries.
Python3
# Importing required librariesimport pandas as pdimport os as o
Step 2: Creating a dataset using a dictionary and list.
Python3
# Creating dataset of location of files.dataset = [dict(Images = 'img1', location = r'New/gfg.png'), dict(Images = 'img2', location = r'New/1.png'), dict(Images = 'img3', location = r'New/gfg2.png'), dict(Images = 'img4', location = r'New/oled.png'), dict(Images = 'img5', location = r'New/oled2.png')]
Here in the above code snippet, we are creating a small dataset of the local file’s paths present in our local system. First, we are creating a dictionary where the image name acts as a unique key and the path of an image is acts as the value of a unique key here. Finally, converting the dictionary into a list so further we can easily convert the list into pandas dataframe.
Step 3: Converting list into Dataframe and printing it.
Python3
# Converting list into pandas dataframe df = pd.DataFrame(dataset) # printing the dataframedf
Output :
Till Step 2 our dataframe was in list form so in Step 3 we are converting it into pandas dataframe so we can easily apply dozens of operations on it for better analysis. Currently, the path of images is not in clickable form, we have to perform some tricky operation on it to convert in into clickable hyperlink form.
Step 4: Creating a function to convert the path into Clickable form.
Python3
# Function to convert file path into clickable form.def fun(path): # returns the final component of a url f_url = o.path.basename(path) # convert the url into link return '<a href="{}">{}</a>'.format(path, f_url)
In the above code snippet, we have created a function that will convert the file path(location of file) into a clickable hyperlink form.
Step 5: Applying the function on column “location” which will convert path into clickable hyperlink form. Now, whenever we will print the dataframe we will get our required to be output.
Python3
# applying function "fun" on column "location".df = df.style.format({'location' : fun})
Output:
Finally, we have successfully converted our local file path into a clickable hyperlink form. Let’s check out some examples.
Example 1: Creating a Dataframe that contains the clickable hyperlink path of images present in our local system.
Python3
# Step 1 : Importing required modulesimport pandas as pdimport os # Step 2 : Creating dataset of local path imagesdataset = [dict(Images='img1', location=r'New/gfg.png'), dict(Images='img2', location=r'New/1.png'), dict(Images='img3', location=r'New/gfg2.png'), dict(Images='img4', location=r'New/oled.png'), dict(Images='img5', location=r'New/oled2.png')] # Step 3 : Converting list into dataframedf = pd.DataFrame(dataset) # Function to convert file path into clickable form. def fun(path): # returns the final component of a path f_url = os.path.basename(path) # convert the path into clickable link return '<a href="{}">{}</a>'.format(path, f_url) # applying function "fun" on column "location".df = df.style.format({'location': fun}) # Step 5 : Finally printing Dataframedf
Output :
Example 2: Creating a Dataframe containing a clickable hyperlink path of files present in our local system.
Python3
# Step 1 : Importing required modulesimport pandas as pdimport os # Step 2 : Creating dataset of filesdataset = [dict( file_names='Crop File', location=r'ML/Crop File prep.ipynb'), dict( file_names='Final Dataset', location=r'ML/FinalData csv creation.ipynb'), dict( file_names='EDA', location=r'ML/EDA on FinalData csv.ipynb'), dict( file_names='Model Training', location=r'ML/Model Training.ipynb'), dict( file_names='Yield Prediction', location=r'ML/yield prediction.ipynb')] # Step 3 : Converting list into dataframedf = pd.DataFrame(data) # Function to convert file path into # clickable hyperlink form.def fun(path): # returns the final component of a path f_url = os.path.basename(path) # convert the path into clickable hyperlink return '<a href="{}">{}</a>'.format(path, f_url) # Step 4 : applying make_clikable function # on column path.df = df.style.format({'location': fun}) # Step 5 : Finally printing Dataframedf
Output:
Note: Whenever we are trying to load local files from the browser we are continuously getting an error ‘Not allowed to load local resources’ in our browser. If we Google this problem and came to know that it is happening due to some security issue of our system. But there is a way we can solve this problem without disturbing our system security, put the required files in the same working directory in which we are working. In the above examples, we created a folder and put all required files in it, and finally easily load them without any issue. In Example 1 we created a folder named “New” in my working directory and put all the required files in it similarly in Example 2 as well.
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 441,
"s": 28,
"text": "If you are familiar with Data Science or Machine Learning field then we can definitely say that we are going to learn something new from this article, So let’s begin. Here in this article, we will learn how to create a clickable hyperlink of the local file path using pandas. It is not a very complicated task, we can easily do it in only 4 to 5 steps. Let’s dig deeper into it and talk about required libraries."
},
{
"code": null,
"e": 898,
"s": 441,
"text": "Pandas: It is one of the most favorite and popular libraries in python for data wrangling and analysis. Pandas is the backbone of all Data Science and Machine Learning projects. It is one of the most important tools for Data Scientists and Analysts. Some features of pandas are: Data Handling, Alignment and indexing, Handling missing data, Cleaning data, Merging and joining of datasets, and much more. Here as well we will use pandas to create a dataset."
},
{
"code": null,
"e": 1224,
"s": 898,
"text": "OS library: The OS module present in python also plays a very important role in various projects. It provides lots of functions for interacting with the operating system. It includes many functions to interact with the file system as well. Here we have to work with local files that’s why we need an os module to handle them."
},
{
"code": null,
"e": 1237,
"s": 1224,
"text": "Steps Needed"
},
{
"code": null,
"e": 1272,
"s": 1237,
"text": "Step 1: Import required libraries."
},
{
"code": null,
"e": 1280,
"s": 1272,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pdimport os as o",
"e": 1344,
"s": 1280,
"text": null
},
{
"code": null,
"e": 1400,
"s": 1344,
"text": "Step 2: Creating a dataset using a dictionary and list."
},
{
"code": null,
"e": 1408,
"s": 1400,
"text": "Python3"
},
{
"code": "# Creating dataset of location of files.dataset = [dict(Images = 'img1', location = r'New/gfg.png'), dict(Images = 'img2', location = r'New/1.png'), dict(Images = 'img3', location = r'New/gfg2.png'), dict(Images = 'img4', location = r'New/oled.png'), dict(Images = 'img5', location = r'New/oled2.png')]",
"e": 1751,
"s": 1408,
"text": null
},
{
"code": null,
"e": 2128,
"s": 1751,
"text": "Here in the above code snippet, we are creating a small dataset of the local file’s paths present in our local system. First, we are creating a dictionary where the image name acts as a unique key and the path of an image is acts as the value of a unique key here. Finally, converting the dictionary into a list so further we can easily convert the list into pandas dataframe."
},
{
"code": null,
"e": 2184,
"s": 2128,
"text": "Step 3: Converting list into Dataframe and printing it."
},
{
"code": null,
"e": 2192,
"s": 2184,
"text": "Python3"
},
{
"code": "# Converting list into pandas dataframe df = pd.DataFrame(dataset) # printing the dataframedf",
"e": 2287,
"s": 2192,
"text": null
},
{
"code": null,
"e": 2297,
"s": 2287,
"text": "Output : "
},
{
"code": null,
"e": 2615,
"s": 2297,
"text": "Till Step 2 our dataframe was in list form so in Step 3 we are converting it into pandas dataframe so we can easily apply dozens of operations on it for better analysis. Currently, the path of images is not in clickable form, we have to perform some tricky operation on it to convert in into clickable hyperlink form."
},
{
"code": null,
"e": 2684,
"s": 2615,
"text": "Step 4: Creating a function to convert the path into Clickable form."
},
{
"code": null,
"e": 2692,
"s": 2684,
"text": "Python3"
},
{
"code": "# Function to convert file path into clickable form.def fun(path): # returns the final component of a url f_url = o.path.basename(path) # convert the url into link return '<a href=\"{}\">{}</a>'.format(path, f_url)",
"e": 2927,
"s": 2692,
"text": null
},
{
"code": null,
"e": 3064,
"s": 2927,
"text": "In the above code snippet, we have created a function that will convert the file path(location of file) into a clickable hyperlink form."
},
{
"code": null,
"e": 3261,
"s": 3064,
"text": "Step 5: Applying the function on column “location” which will convert path into clickable hyperlink form. Now, whenever we will print the dataframe we will get our required to be output. "
},
{
"code": null,
"e": 3269,
"s": 3261,
"text": "Python3"
},
{
"code": "# applying function \"fun\" on column \"location\".df = df.style.format({'location' : fun})",
"e": 3357,
"s": 3269,
"text": null
},
{
"code": null,
"e": 3366,
"s": 3357,
"text": "Output: "
},
{
"code": null,
"e": 3490,
"s": 3366,
"text": "Finally, we have successfully converted our local file path into a clickable hyperlink form. Let’s check out some examples."
},
{
"code": null,
"e": 3604,
"s": 3490,
"text": "Example 1: Creating a Dataframe that contains the clickable hyperlink path of images present in our local system."
},
{
"code": null,
"e": 3612,
"s": 3604,
"text": "Python3"
},
{
"code": "# Step 1 : Importing required modulesimport pandas as pdimport os # Step 2 : Creating dataset of local path imagesdataset = [dict(Images='img1', location=r'New/gfg.png'), dict(Images='img2', location=r'New/1.png'), dict(Images='img3', location=r'New/gfg2.png'), dict(Images='img4', location=r'New/oled.png'), dict(Images='img5', location=r'New/oled2.png')] # Step 3 : Converting list into dataframedf = pd.DataFrame(dataset) # Function to convert file path into clickable form. def fun(path): # returns the final component of a path f_url = os.path.basename(path) # convert the path into clickable link return '<a href=\"{}\">{}</a>'.format(path, f_url) # applying function \"fun\" on column \"location\".df = df.style.format({'location': fun}) # Step 5 : Finally printing Dataframedf",
"e": 4463,
"s": 3612,
"text": null
},
{
"code": null,
"e": 4472,
"s": 4463,
"text": "Output :"
},
{
"code": null,
"e": 4581,
"s": 4472,
"text": "Example 2: Creating a Dataframe containing a clickable hyperlink path of files present in our local system. "
},
{
"code": null,
"e": 4589,
"s": 4581,
"text": "Python3"
},
{
"code": "# Step 1 : Importing required modulesimport pandas as pdimport os # Step 2 : Creating dataset of filesdataset = [dict( file_names='Crop File', location=r'ML/Crop File prep.ipynb'), dict( file_names='Final Dataset', location=r'ML/FinalData csv creation.ipynb'), dict( file_names='EDA', location=r'ML/EDA on FinalData csv.ipynb'), dict( file_names='Model Training', location=r'ML/Model Training.ipynb'), dict( file_names='Yield Prediction', location=r'ML/yield prediction.ipynb')] # Step 3 : Converting list into dataframedf = pd.DataFrame(data) # Function to convert file path into # clickable hyperlink form.def fun(path): # returns the final component of a path f_url = os.path.basename(path) # convert the path into clickable hyperlink return '<a href=\"{}\">{}</a>'.format(path, f_url) # Step 4 : applying make_clikable function # on column path.df = df.style.format({'location': fun}) # Step 5 : Finally printing Dataframedf",
"e": 5642,
"s": 4589,
"text": null
},
{
"code": null,
"e": 5651,
"s": 5642,
"text": "Output: "
},
{
"code": null,
"e": 6340,
"s": 5651,
"text": "Note: Whenever we are trying to load local files from the browser we are continuously getting an error ‘Not allowed to load local resources’ in our browser. If we Google this problem and came to know that it is happening due to some security issue of our system. But there is a way we can solve this problem without disturbing our system security, put the required files in the same working directory in which we are working. In the above examples, we created a folder and put all required files in it, and finally easily load them without any issue. In Example 1 we created a folder named “New” in my working directory and put all the required files in it similarly in Example 2 as well."
},
{
"code": null,
"e": 6347,
"s": 6340,
"text": "Picked"
},
{
"code": null,
"e": 6361,
"s": 6347,
"text": "Python-pandas"
},
{
"code": null,
"e": 6368,
"s": 6361,
"text": "Python"
},
{
"code": null,
"e": 6466,
"s": 6368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6498,
"s": 6466,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6525,
"s": 6498,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6546,
"s": 6525,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 6569,
"s": 6546,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 6625,
"s": 6569,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 6656,
"s": 6625,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 6698,
"s": 6656,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6740,
"s": 6698,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6779,
"s": 6740,
"text": "Python | datetime.timedelta() function"
}
] |
NaN in C++ – What is it and How to Check For it?
|
06 Jan, 2022
NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can’t be represented. It is used for floating-point operations. For example:
The square root of negative numbers
Division by zero
Taking the log of zero or a negative number etc.
CPP
// C++ code to demonstrate NaN exception#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ float a = 2, b = -2; // Prints the number (1.41421) cout << sqrt(a) << endl; // Prints "nan" exception // sqrt(-2) is complex number cout << sqrt(b) << endl; return 0;}
1.41421
-nan
Method 1: Using compare (“==”) operator.
In this method, we check if a number is complex by comparing it with itself. If the result is true, then the number is not complex i.e., real. But if the result is false, then “nan” is returned, i.e. the number is complex.
CPP
// C++ code to check for NaN exception// using "==" operator#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ float a = sqrt(2); float b = sqrt(-2); // Returns true, a is real number // prints "Its a real number" a == a ? cout << "Its a real number" << endl : cout << "Its NaN" << endl; // Returns false, b is complex number // prints "Its nan" b == b ? cout << "Its a real number" << endl : cout << "Its NaN" << endl; return 0;}
Its a real number
Its NaN
Method 2: Using inbuilt function “isnan()”
Another way to check for NaN is by using “isnan()” function, this function returns true if a number is complex else it returns false. This C library function is present in <cmath> header file.
CPP
// C++ code to check for NaN exception// using "isnan()"#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ float a = sqrt(2); float b = sqrt(-2); // Returns false as a // is real number isnan(a) ? cout << "Its NaN" << endl : cout << "Its a real number" << endl; // Returns true as b is NaN isnan(b) ? cout << "Its NaN" << endl : cout << "Its a real number" << endl; return 0;}
Its a real number
Its NaN
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
anshikajain26
cpp-data-types
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 271,
"s": 52,
"text": "NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can’t be represented. It is used for floating-point operations. For example:"
},
{
"code": null,
"e": 307,
"s": 271,
"text": "The square root of negative numbers"
},
{
"code": null,
"e": 324,
"s": 307,
"text": "Division by zero"
},
{
"code": null,
"e": 373,
"s": 324,
"text": "Taking the log of zero or a negative number etc."
},
{
"code": null,
"e": 377,
"s": 373,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate NaN exception#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ float a = 2, b = -2; // Prints the number (1.41421) cout << sqrt(a) << endl; // Prints \"nan\" exception // sqrt(-2) is complex number cout << sqrt(b) << endl; return 0;}",
"e": 692,
"s": 377,
"text": null
},
{
"code": null,
"e": 705,
"s": 692,
"text": "1.41421\n-nan"
},
{
"code": null,
"e": 747,
"s": 705,
"text": "Method 1: Using compare (“==”) operator. "
},
{
"code": null,
"e": 970,
"s": 747,
"text": "In this method, we check if a number is complex by comparing it with itself. If the result is true, then the number is not complex i.e., real. But if the result is false, then “nan” is returned, i.e. the number is complex."
},
{
"code": null,
"e": 974,
"s": 970,
"text": "CPP"
},
{
"code": "// C++ code to check for NaN exception// using \"==\" operator#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ float a = sqrt(2); float b = sqrt(-2); // Returns true, a is real number // prints \"Its a real number\" a == a ? cout << \"Its a real number\" << endl : cout << \"Its NaN\" << endl; // Returns false, b is complex number // prints \"Its nan\" b == b ? cout << \"Its a real number\" << endl : cout << \"Its NaN\" << endl; return 0;}",
"e": 1486,
"s": 974,
"text": null
},
{
"code": null,
"e": 1512,
"s": 1486,
"text": "Its a real number\nIts NaN"
},
{
"code": null,
"e": 1555,
"s": 1512,
"text": "Method 2: Using inbuilt function “isnan()”"
},
{
"code": null,
"e": 1748,
"s": 1555,
"text": "Another way to check for NaN is by using “isnan()” function, this function returns true if a number is complex else it returns false. This C library function is present in <cmath> header file."
},
{
"code": null,
"e": 1752,
"s": 1748,
"text": "CPP"
},
{
"code": "// C++ code to check for NaN exception// using \"isnan()\"#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ float a = sqrt(2); float b = sqrt(-2); // Returns false as a // is real number isnan(a) ? cout << \"Its NaN\" << endl : cout << \"Its a real number\" << endl; // Returns true as b is NaN isnan(b) ? cout << \"Its NaN\" << endl : cout << \"Its a real number\" << endl; return 0;}",
"e": 2211,
"s": 1752,
"text": null
},
{
"code": null,
"e": 2237,
"s": 2211,
"text": "Its a real number\nIts NaN"
},
{
"code": null,
"e": 2659,
"s": 2237,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 2673,
"s": 2659,
"text": "anshikajain26"
},
{
"code": null,
"e": 2688,
"s": 2673,
"text": "cpp-data-types"
},
{
"code": null,
"e": 2699,
"s": 2688,
"text": "C Language"
},
{
"code": null,
"e": 2703,
"s": 2699,
"text": "C++"
},
{
"code": null,
"e": 2707,
"s": 2703,
"text": "CPP"
},
{
"code": null,
"e": 2805,
"s": 2707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2853,
"s": 2805,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2874,
"s": 2853,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 2900,
"s": 2874,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 2945,
"s": 2900,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 2983,
"s": 2945,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3001,
"s": 2983,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3044,
"s": 3001,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3090,
"s": 3044,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 3133,
"s": 3090,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Check whether an array can be made strictly increasing by modifying atmost one element - GeeksforGeeks
|
29 Apr, 2021
Given an array arr[] of positive integers, the task is to find whether it is possible to make this array strictly increasing by modifying atmost one element.Examples:
Input: arr[] = {2, 4, 8, 6, 9, 12} Output: Yes By modifying 8 to 5, array will become strictly increasing. i.e. {2, 4, 5, 6, 9, 12}Input: arr[] = {10, 5, 2} Output: No
Approach: For every element arr[i], if it is greater than both arr[i – 1] and arr[i + 1] or it is smaller than both arr[i – 1] and arr[i + 1] then arr[i] needs to be modified. i.e. arr[i] = (arr[i – 1] + arr[i + 1]) / 2. If after modification, arr[i] = arr[i – 1] or arr[i] = arr[i + 1] then the array cannot be made strictly increasing without affecting more than a single element. Else count all such modifications, if the count of modifications in the end is less than or equal to 1 then print “Yes” else print “No”.Below is the implementation of the above approach:
C++
Java
C#
Python 3
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if arr[]// can be made strictly increasing after// modifying at most one elementbool check(int arr[], int n){ // To store the number of modifications // required to make the array // strictly increasing int modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (int i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true;} // Driver codeint main(){ int arr[] = { 2, 4, 8, 6, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); if (check(arr, n)) cout << "Yes" << endl; else cout << "No" << endl; return 0;}
// Java implementation of the approachclass GFG { // Function that returns true if arr[] // can be made strictly increasing after // modifying at most one element static boolean check(int arr[], int n) { // To store the number of modifications // required to make the array // strictly increasing int modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (int i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code public static void main(String[] args) { int[] arr = { 2, 4, 8, 6, 9, 12 }; int n = arr.length; if (check(arr, n)) System.out.print("Yes"); else System.out.print("No"); }}
// C# implementation of the approachusing System; class GFG{ // Function that returns true if arr[] // can be made strictly increasing after // modifying at most one element static bool check(int []arr, int n) { // To store the number of modifications // required to make the array // strictly increasing int modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (int i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code public static void Main() { int[] arr = { 2, 4, 8, 6, 9, 12 }; int n = arr.Length; if (check(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by AnkitRai01
# Python 3 implementation of above approach # Function that returns true if arr[]# can be made strictly increasing after# modifying at most one elementdef check( arr, n): # To store the number of modifications # required to make the array # strictly increasing modify = 0 # Check whether the first element needs # to be modify or not if (arr[0] > arr[1]) : arr[0] = arr[1] // 2 modify+=1 # Loop from 2nd element to the 2nd last element for i in range ( 1, n - 1): # Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] and arr[i + 1] < arr[i]) or (arr[i - 1] > arr[i] and arr[i + 1] > arr[i])): # Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) // 2 # Check if arr[i] is equal to any of # arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] or arr[i] == arr[i + 1]): return False modify+=1 # Check whether the last element needs # to be modify or not if (arr[n - 1] < arr[n - 2]): modify+=1 # If more than 1 modification is required if (modify > 1): return False return True # Driver codeif __name__ == "__main__": arr = [ 2, 4, 8, 6, 9, 12 ] n = len(arr) if (check(arr, n)): print ( "Yes") else: print ("No") # This code is contributed by ChitraNayal
<script> // Javascript implementation of the approach // Function that returns true if arr[]// can be made strictly increasing after// modifying at most one elementfunction check(arr, n){ // To store the number of modifications // required to make the array // strictly increasing var modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (var i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true;} // Driver codevar arr = [ 2, 4, 8, 6, 9, 12 ];var n = arr.length;if (check(arr, n)) document.write( "Yes" );else document.write( "No" ); // This code is contributed by noob2000.</script>
Yes
ankthon
ukasp
noob2000
Constructive Algorithms
Arrays
Sorting
Arrays
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
Multidimensional Arrays in Java
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Linked List vs Array
|
[
{
"code": null,
"e": 25224,
"s": 25196,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 25393,
"s": 25224,
"text": "Given an array arr[] of positive integers, the task is to find whether it is possible to make this array strictly increasing by modifying atmost one element.Examples: "
},
{
"code": null,
"e": 25563,
"s": 25393,
"text": "Input: arr[] = {2, 4, 8, 6, 9, 12} Output: Yes By modifying 8 to 5, array will become strictly increasing. i.e. {2, 4, 5, 6, 9, 12}Input: arr[] = {10, 5, 2} Output: No "
},
{
"code": null,
"e": 26136,
"s": 25565,
"text": "Approach: For every element arr[i], if it is greater than both arr[i – 1] and arr[i + 1] or it is smaller than both arr[i – 1] and arr[i + 1] then arr[i] needs to be modified. i.e. arr[i] = (arr[i – 1] + arr[i + 1]) / 2. If after modification, arr[i] = arr[i – 1] or arr[i] = arr[i + 1] then the array cannot be made strictly increasing without affecting more than a single element. Else count all such modifications, if the count of modifications in the end is less than or equal to 1 then print “Yes” else print “No”.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26140,
"s": 26136,
"text": "C++"
},
{
"code": null,
"e": 26145,
"s": 26140,
"text": "Java"
},
{
"code": null,
"e": 26148,
"s": 26145,
"text": "C#"
},
{
"code": null,
"e": 26157,
"s": 26148,
"text": "Python 3"
},
{
"code": null,
"e": 26168,
"s": 26157,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if arr[]// can be made strictly increasing after// modifying at most one elementbool check(int arr[], int n){ // To store the number of modifications // required to make the array // strictly increasing int modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (int i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true;} // Driver codeint main(){ int arr[] = { 2, 4, 8, 6, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); if (check(arr, n)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}",
"e": 27642,
"s": 26168,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function that returns true if arr[] // can be made strictly increasing after // modifying at most one element static boolean check(int arr[], int n) { // To store the number of modifications // required to make the array // strictly increasing int modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (int i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code public static void main(String[] args) { int[] arr = { 2, 4, 8, 6, 9, 12 }; int n = arr.length; if (check(arr, n)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}",
"e": 29293,
"s": 27642,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if arr[] // can be made strictly increasing after // modifying at most one element static bool check(int []arr, int n) { // To store the number of modifications // required to make the array // strictly increasing int modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (int i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code public static void Main() { int[] arr = { 2, 4, 8, 6, 9, 12 }; int n = arr.Length; if (check(arr, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by AnkitRai01",
"e": 31008,
"s": 29293,
"text": null
},
{
"code": "# Python 3 implementation of above approach # Function that returns true if arr[]# can be made strictly increasing after# modifying at most one elementdef check( arr, n): # To store the number of modifications # required to make the array # strictly increasing modify = 0 # Check whether the first element needs # to be modify or not if (arr[0] > arr[1]) : arr[0] = arr[1] // 2 modify+=1 # Loop from 2nd element to the 2nd last element for i in range ( 1, n - 1): # Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] and arr[i + 1] < arr[i]) or (arr[i - 1] > arr[i] and arr[i + 1] > arr[i])): # Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) // 2 # Check if arr[i] is equal to any of # arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] or arr[i] == arr[i + 1]): return False modify+=1 # Check whether the last element needs # to be modify or not if (arr[n - 1] < arr[n - 2]): modify+=1 # If more than 1 modification is required if (modify > 1): return False return True # Driver codeif __name__ == \"__main__\": arr = [ 2, 4, 8, 6, 9, 12 ] n = len(arr) if (check(arr, n)): print ( \"Yes\") else: print (\"No\") # This code is contributed by ChitraNayal ",
"e": 32405,
"s": 31008,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that returns true if arr[]// can be made strictly increasing after// modifying at most one elementfunction check(arr, n){ // To store the number of modifications // required to make the array // strictly increasing var modify = 0; // Check whether the first element needs // to be modify or not if (arr[0] > arr[1]) { arr[0] = arr[1] / 2; modify++; } // Loop from 2nd element to the 2nd last element for (var i = 1; i < n - 1; i++) { // Check whether arr[i] needs to be modified if ((arr[i - 1] < arr[i] && arr[i + 1] < arr[i]) || (arr[i - 1] > arr[i] && arr[i + 1] > arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; modify++; } } // Check whether the last element needs // to be modify or not if (arr[n - 1] < arr[n - 2]) modify++; // If more than 1 modification is required if (modify > 1) return false; return true;} // Driver codevar arr = [ 2, 4, 8, 6, 9, 12 ];var n = arr.length;if (check(arr, n)) document.write( \"Yes\" );else document.write( \"No\" ); // This code is contributed by noob2000.</script>",
"e": 33834,
"s": 32405,
"text": null
},
{
"code": null,
"e": 33838,
"s": 33834,
"text": "Yes"
},
{
"code": null,
"e": 33848,
"s": 33840,
"text": "ankthon"
},
{
"code": null,
"e": 33854,
"s": 33848,
"text": "ukasp"
},
{
"code": null,
"e": 33863,
"s": 33854,
"text": "noob2000"
},
{
"code": null,
"e": 33887,
"s": 33863,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 33894,
"s": 33887,
"text": "Arrays"
},
{
"code": null,
"e": 33902,
"s": 33894,
"text": "Sorting"
},
{
"code": null,
"e": 33909,
"s": 33902,
"text": "Arrays"
},
{
"code": null,
"e": 33917,
"s": 33909,
"text": "Sorting"
},
{
"code": null,
"e": 34015,
"s": 33917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34083,
"s": 34015,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34115,
"s": 34083,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34138,
"s": 34115,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34183,
"s": 34138,
"text": "Python | Using 2D arrays/lists the right way"
}
] |
Product of middle row and column in an odd square matrix in C
|
Given a square matrix, mat[row][column] where row and column are equal and are of odd length means the number of row and column must me odd, i.e, not divisible by 2, the task is to find the product of middle row and middle column of that matrix.
Like in the given figure below −
Matrix must be a square matrix.
Matrix must be a square matrix.
Column and rows must be of odd length.
Column and rows must be of odd length.
Input
mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output
Product of middle row = 120
Product of middle column = 80
Explanation
Product of middle row = 4 * 5 * 6 = 120
Product of middle column = 2 * 5 * 8 = 80
Input
mat[][] = {{3, 5, 0},
{1, 2, 7},
{9, 0, 5}}
Output
Product of middle row = 14
Product of middle column = 0
Explanation
Product of middle row = 1 * 2 * 7 = 120
Product of middle column = 5 * 2 * 0 = 0
Take a matrix mat[][] as an input.
Take a matrix mat[][] as an input.
Traverse the matrix as from the middle row and middle column
Traverse the matrix as from the middle row and middle column
Calculate the product of the middle row and middle column and return the result.
Calculate the product of the middle row and middle column and return the result.
Start
In function int product(int mat[][MAX], int n)
Step 1→ Declare and initialize rproduct = 1, cproduct = 1
Step 2→ Loop For i = 0 and i < n and i++
Set rproduct = rproduct * mat[n / 2][i]
Set cproduct = cproduct * mat[i][n / 2]
Step 3→ Print "Product of middle row: rproduct “
Step 4→ Print "Product of middle column: cproduct”
In function int main()
Step 1→ Declare and initialize mat[][MAX] {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } }
Step 2→ Call product(mat, MAX)
Stop
Live Demo
#include <stdio.h>
#define MAX 3
int product(int mat[][MAX], int n){
int rproduct = 1, cproduct = 1;
//We will only check the middle elements and
//find their products
for (int i = 0; i < n; i++) {
rproduct *= mat[n / 2][i];
cproduct *= mat[i][n / 2];
}
// Printing the result
printf("Product of middle row: %d\n", rproduct);
printf("Product of middle column: %d\n", cproduct);
return 0;
}
// Driver code
int main(){
int mat[][MAX] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
product(mat, MAX);
return 0;
}
If run the above code it will generate the following output −
Product of middle row: 120
Product of middle column: 80
|
[
{
"code": null,
"e": 1308,
"s": 1062,
"text": "Given a square matrix, mat[row][column] where row and column are equal and are of odd length means the number of row and column must me odd, i.e, not divisible by 2, the task is to find the product of middle row and middle column of that matrix."
},
{
"code": null,
"e": 1341,
"s": 1308,
"text": "Like in the given figure below −"
},
{
"code": null,
"e": 1373,
"s": 1341,
"text": "Matrix must be a square matrix."
},
{
"code": null,
"e": 1405,
"s": 1373,
"text": "Matrix must be a square matrix."
},
{
"code": null,
"e": 1444,
"s": 1405,
"text": "Column and rows must be of odd length."
},
{
"code": null,
"e": 1483,
"s": 1444,
"text": "Column and rows must be of odd length."
},
{
"code": null,
"e": 1490,
"s": 1483,
"text": "Input "
},
{
"code": null,
"e": 1534,
"s": 1490,
"text": "mat[][] = {{1, 2, 3},\n{4, 5, 6},\n{7, 8, 9}}"
},
{
"code": null,
"e": 1542,
"s": 1534,
"text": "Output "
},
{
"code": null,
"e": 1600,
"s": 1542,
"text": "Product of middle row = 120\nProduct of middle column = 80"
},
{
"code": null,
"e": 1613,
"s": 1600,
"text": "Explanation "
},
{
"code": null,
"e": 1695,
"s": 1613,
"text": "Product of middle row = 4 * 5 * 6 = 120\nProduct of middle column = 2 * 5 * 8 = 80"
},
{
"code": null,
"e": 1702,
"s": 1695,
"text": "Input "
},
{
"code": null,
"e": 1746,
"s": 1702,
"text": "mat[][] = {{3, 5, 0},\n{1, 2, 7},\n{9, 0, 5}}"
},
{
"code": null,
"e": 1754,
"s": 1746,
"text": "Output "
},
{
"code": null,
"e": 1810,
"s": 1754,
"text": "Product of middle row = 14\nProduct of middle column = 0"
},
{
"code": null,
"e": 1823,
"s": 1810,
"text": "Explanation "
},
{
"code": null,
"e": 1904,
"s": 1823,
"text": "Product of middle row = 1 * 2 * 7 = 120\nProduct of middle column = 5 * 2 * 0 = 0"
},
{
"code": null,
"e": 1939,
"s": 1904,
"text": "Take a matrix mat[][] as an input."
},
{
"code": null,
"e": 1974,
"s": 1939,
"text": "Take a matrix mat[][] as an input."
},
{
"code": null,
"e": 2035,
"s": 1974,
"text": "Traverse the matrix as from the middle row and middle column"
},
{
"code": null,
"e": 2096,
"s": 2035,
"text": "Traverse the matrix as from the middle row and middle column"
},
{
"code": null,
"e": 2177,
"s": 2096,
"text": "Calculate the product of the middle row and middle column and return the result."
},
{
"code": null,
"e": 2258,
"s": 2177,
"text": "Calculate the product of the middle row and middle column and return the result."
},
{
"code": null,
"e": 2781,
"s": 2258,
"text": "Start\nIn function int product(int mat[][MAX], int n)\n Step 1→ Declare and initialize rproduct = 1, cproduct = 1\n Step 2→ Loop For i = 0 and i < n and i++\n Set rproduct = rproduct * mat[n / 2][i]\n Set cproduct = cproduct * mat[i][n / 2]\n Step 3→ Print \"Product of middle row: rproduct “\n Step 4→ Print \"Product of middle column: cproduct”\nIn function int main()\n Step 1→ Declare and initialize mat[][MAX] {\n { 1, 2, 3 },\n { 4, 5, 6 },\n { 7, 8, 9 } }\n Step 2→ Call product(mat, MAX)\nStop"
},
{
"code": null,
"e": 2792,
"s": 2781,
"text": " Live Demo"
},
{
"code": null,
"e": 3366,
"s": 2792,
"text": "#include <stdio.h>\n#define MAX 3\nint product(int mat[][MAX], int n){\n int rproduct = 1, cproduct = 1;\n //We will only check the middle elements and\n //find their products\n for (int i = 0; i < n; i++) {\n rproduct *= mat[n / 2][i];\n cproduct *= mat[i][n / 2];\n }\n // Printing the result\n printf(\"Product of middle row: %d\\n\", rproduct);\n printf(\"Product of middle column: %d\\n\", cproduct);\n return 0;\n}\n// Driver code\nint main(){\n int mat[][MAX] = {\n { 1, 2, 3 },\n { 4, 5, 6 },\n { 7, 8, 9 } };\n product(mat, MAX);\n return 0;\n}"
},
{
"code": null,
"e": 3428,
"s": 3366,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 3484,
"s": 3428,
"text": "Product of middle row: 120\nProduct of middle column: 80"
}
] |
Ext.js - First Program
|
This chapter lists down the steps to write the first Hello World program in Ext JS.
Create an index.htm page in the editor of our choice. Include the required library files in the head section of html page as follows.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Panel', {
renderTo: 'helloWorldPanel',
height: 200,
width: 600,
title: 'Hello world',
html: 'First Ext JS Hello World Program'
});
});
</script>
</head>
<body>
<div id = "helloWorldPanel" />
</body>
</html>
Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements.
Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements.
Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel.
Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel.
Ext.Panel is the predefined class in Ext JS for creating a panel.
Ext.Panel is the predefined class in Ext JS for creating a panel.
Every Ext JS class has different properties to perform some basic functionalities.
Every Ext JS class has different properties to perform some basic functionalities.
Ext.Panel class has various properties such as −
renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file.
renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file.
Height and width properties are for customizing the size of the panel.
Height and width properties are for customizing the size of the panel.
Title property is to provide the title to the panel.
Title property is to provide the title to the panel.
Html property is the html content to be shown in the panel.
Html property is the html content to be shown in the panel.
Open the index.htm file in a standard browser and you will get the following output on the browser.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2107,
"s": 2023,
"text": "This chapter lists down the steps to write the first Hello World program in Ext JS."
},
{
"code": null,
"e": 2241,
"s": 2107,
"text": "Create an index.htm page in the editor of our choice. Include the required library files in the head section of html page as follows."
},
{
"code": null,
"e": 2998,
"s": 2241,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Panel', {\n renderTo: 'helloWorldPanel',\n height: 200,\n width: 600,\n title: 'Hello world',\n html: 'First Ext JS Hello World Program'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"helloWorldPanel\" />\n </body>\n</html>"
},
{
"code": null,
"e": 3090,
"s": 2998,
"text": "Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements."
},
{
"code": null,
"e": 3182,
"s": 3090,
"text": "Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements."
},
{
"code": null,
"e": 3305,
"s": 3182,
"text": "Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel."
},
{
"code": null,
"e": 3428,
"s": 3305,
"text": "Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel."
},
{
"code": null,
"e": 3494,
"s": 3428,
"text": "Ext.Panel is the predefined class in Ext JS for creating a panel."
},
{
"code": null,
"e": 3560,
"s": 3494,
"text": "Ext.Panel is the predefined class in Ext JS for creating a panel."
},
{
"code": null,
"e": 3643,
"s": 3560,
"text": "Every Ext JS class has different properties to perform some basic functionalities."
},
{
"code": null,
"e": 3726,
"s": 3643,
"text": "Every Ext JS class has different properties to perform some basic functionalities."
},
{
"code": null,
"e": 3775,
"s": 3726,
"text": "Ext.Panel class has various properties such as −"
},
{
"code": null,
"e": 3883,
"s": 3775,
"text": "renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file."
},
{
"code": null,
"e": 3991,
"s": 3883,
"text": "renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file."
},
{
"code": null,
"e": 4062,
"s": 3991,
"text": "Height and width properties are for customizing the size of the panel."
},
{
"code": null,
"e": 4133,
"s": 4062,
"text": "Height and width properties are for customizing the size of the panel."
},
{
"code": null,
"e": 4186,
"s": 4133,
"text": "Title property is to provide the title to the panel."
},
{
"code": null,
"e": 4239,
"s": 4186,
"text": "Title property is to provide the title to the panel."
},
{
"code": null,
"e": 4299,
"s": 4239,
"text": "Html property is the html content to be shown in the panel."
},
{
"code": null,
"e": 4359,
"s": 4299,
"text": "Html property is the html content to be shown in the panel."
},
{
"code": null,
"e": 4459,
"s": 4359,
"text": "Open the index.htm file in a standard browser and you will get the following output on the browser."
},
{
"code": null,
"e": 4466,
"s": 4459,
"text": " Print"
},
{
"code": null,
"e": 4477,
"s": 4466,
"text": " Add Notes"
}
] |
Plotly - Slider Control
|
Plotly has a convenient Slider that can be used to change the view of data/style of a plot by sliding a knob on the control which is placed at the bottom of rendered plot.
Slider control is made up of different properties which are as follows −
steps property is required for defining sliding positions of knob over the control.
steps property is required for defining sliding positions of knob over the control.
method property is having possible values as restyle | relayout | animate | update | skip, default is restyle.
method property is having possible values as restyle | relayout | animate | update | skip, default is restyle.
args property sets the arguments values to be passed to the Plotly method set in method on slide.
args property sets the arguments values to be passed to the Plotly method set in method on slide.
We now deploy a simple slider control on a scatter plot which will vary the frequency of sine wave as the knob slides along the control. The slider is configured to have 50 steps. First add 50 traces of sine wave curve with incrementing frequency, all but 10th trace set to visible.
Then, we configure each step with restyle method. For each step, all other step objects have visibility set to false. Finally, update Figure object’s layout by initializing sliders property.
# Add traces, one for each slider step
for step in np.arange(0, 5, 0.1):
fig.add_trace(
go.Scatter(
visible = False,
line = dict(color = "blue", width = 2),
name = "ν = " + str(step),
x = np.arange(0, 10, 0.01),
y = np.sin(step * np.arange(0, 10, 0.01))
)
)
fig.data[10].visible=True
# Create and add slider
steps = []
for i in range(len(fig.data)):
step = dict(
method = "restyle",
args = ["visible", [False] * len(fig.data)],
)
step["args"][1][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(active = 10, steps = steps)]
fig.layout.update(sliders=sliders)
iplot(fig)
To begin with, 10th sine wave trace will be visible. Try sliding the knob across the horizontal control at the bottom. You will see the frequency changing as shown below.
12 Lectures
53 mins
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2532,
"s": 2360,
"text": "Plotly has a convenient Slider that can be used to change the view of data/style of a plot by sliding a knob on the control which is placed at the bottom of rendered plot."
},
{
"code": null,
"e": 2605,
"s": 2532,
"text": "Slider control is made up of different properties which are as follows −"
},
{
"code": null,
"e": 2689,
"s": 2605,
"text": "steps property is required for defining sliding positions of knob over the control."
},
{
"code": null,
"e": 2773,
"s": 2689,
"text": "steps property is required for defining sliding positions of knob over the control."
},
{
"code": null,
"e": 2884,
"s": 2773,
"text": "method property is having possible values as restyle | relayout | animate | update | skip, default is restyle."
},
{
"code": null,
"e": 2995,
"s": 2884,
"text": "method property is having possible values as restyle | relayout | animate | update | skip, default is restyle."
},
{
"code": null,
"e": 3093,
"s": 2995,
"text": "args property sets the arguments values to be passed to the Plotly method set in method on slide."
},
{
"code": null,
"e": 3191,
"s": 3093,
"text": "args property sets the arguments values to be passed to the Plotly method set in method on slide."
},
{
"code": null,
"e": 3474,
"s": 3191,
"text": "We now deploy a simple slider control on a scatter plot which will vary the frequency of sine wave as the knob slides along the control. The slider is configured to have 50 steps. First add 50 traces of sine wave curve with incrementing frequency, all but 10th trace set to visible."
},
{
"code": null,
"e": 3665,
"s": 3474,
"text": "Then, we configure each step with restyle method. For each step, all other step objects have visibility set to false. Finally, update Figure object’s layout by initializing sliders property."
},
{
"code": null,
"e": 4307,
"s": 3665,
"text": "# Add traces, one for each slider step\nfor step in np.arange(0, 5, 0.1):\nfig.add_trace(\n go.Scatter(\n visible = False,\n line = dict(color = \"blue\", width = 2),\n name = \"ν = \" + str(step),\n x = np.arange(0, 10, 0.01),\n y = np.sin(step * np.arange(0, 10, 0.01))\n )\n)\nfig.data[10].visible=True\n\n# Create and add slider\nsteps = []\nfor i in range(len(fig.data)):\nstep = dict(\n method = \"restyle\",\n args = [\"visible\", [False] * len(fig.data)],\n)\nstep[\"args\"][1][i] = True # Toggle i'th trace to \"visible\"\nsteps.append(step)\nsliders = [dict(active = 10, steps = steps)]\nfig.layout.update(sliders=sliders)\niplot(fig)"
},
{
"code": null,
"e": 4478,
"s": 4307,
"text": "To begin with, 10th sine wave trace will be visible. Try sliding the knob across the horizontal control at the bottom. You will see the frequency changing as shown below."
},
{
"code": null,
"e": 4510,
"s": 4478,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4530,
"s": 4510,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4537,
"s": 4530,
"text": " Print"
},
{
"code": null,
"e": 4548,
"s": 4537,
"text": " Add Notes"
}
] |
How to print current date and time in a JSP page?
|
With JSP program, it is very easy to get the current date and the time. You can use a simple Date object with the toString() method to print the current date and the time as follows −
Live Demo
<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<html>
<head>
<title>Display Current Date & Time</title>
</head>
<body>
<center>
<h1>Display Current Date & Time</h1>
</center>
<%
Date date = new Date();
out.print( "<h2 align = \"center\">" +date.toString()+"</h2>");
%>
</body>
</html>
Let us now keep the code in CurrentDate.jsp and then call this JSP using the URL http://localhost:8080/CurrentDate.jsp. You will receive the following result −
Display Current Date & Time
Mon Jun 21 21:46:49 GMT+04:00 2010
Refresh the page with the URL http://localhost:8080/CurrentDate.jsp. You will find a difference in seconds every time you would refresh.
|
[
{
"code": null,
"e": 1246,
"s": 1062,
"text": "With JSP program, it is very easy to get the current date and the time. You can use a simple Date object with the toString() method to print the current date and the time as follows −"
},
{
"code": null,
"e": 1257,
"s": 1246,
"text": " Live Demo"
},
{
"code": null,
"e": 1626,
"s": 1257,
"text": "<%@ page import = \"java.io.*,java.util.*, javax.servlet.*\" %>\n<html>\n <head>\n <title>Display Current Date & Time</title>\n </head>\n <body>\n <center>\n <h1>Display Current Date & Time</h1>\n </center>\n <%\n Date date = new Date();\n out.print( \"<h2 align = \\\"center\\\">\" +date.toString()+\"</h2>\");\n %>\n </body>\n</html>"
},
{
"code": null,
"e": 1786,
"s": 1626,
"text": "Let us now keep the code in CurrentDate.jsp and then call this JSP using the URL http://localhost:8080/CurrentDate.jsp. You will receive the following result −"
},
{
"code": null,
"e": 1849,
"s": 1786,
"text": "Display Current Date & Time\nMon Jun 21 21:46:49 GMT+04:00 2010"
},
{
"code": null,
"e": 1986,
"s": 1849,
"text": "Refresh the page with the URL http://localhost:8080/CurrentDate.jsp. You will find a difference in seconds every time you would refresh."
}
] |
ML | Log Loss and Mean Squared Error - GeeksforGeeks
|
20 Jun, 2019
It is the evaluation measure to check the performance of the classification model. It measures the amount of divergence of predicted probability with the actual label. So lesser the log loss value, more the perfectness of model. For a perfect model, log loss value = 0. For instance, as accuracy is the count of correct predictions i.e. the prediction that matches the actual label, Log Loss value is the measure of uncertainty of our predicted labels based on how it varies from the actual label.
where,
N : no. of samples.
M : no. of attributes.
yij : indicates whether ith sample belongs to jth class or not.
pij : indicates probability of ith sample belonging to jth class.
from sklearn.metrics import log_loss: LogLoss = log_loss(y_true, y_pred, eps = 1e-15, normalize = True, sample_weight = None, labels = None)
It is simply the average of the square of the difference between the original values and the predicted values.
Implementation of Mean Squared Error using sklearn
from sklearn.metrics import mean_squared_error MSE = mean_squared_error(y_true, y_pred)
data mining
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Search Algorithms in AI
Python | Decision tree implementation
Elbow Method for optimal value of k in KMeans
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24600,
"s": 24572,
"text": "\n20 Jun, 2019"
},
{
"code": null,
"e": 25098,
"s": 24600,
"text": "It is the evaluation measure to check the performance of the classification model. It measures the amount of divergence of predicted probability with the actual label. So lesser the log loss value, more the perfectness of model. For a perfect model, log loss value = 0. For instance, as accuracy is the count of correct predictions i.e. the prediction that matches the actual label, Log Loss value is the measure of uncertainty of our predicted labels based on how it varies from the actual label."
},
{
"code": null,
"e": 25282,
"s": 25098,
"text": "where, \nN : no. of samples.\nM : no. of attributes.\nyij : indicates whether ith sample belongs to jth class or not.\npij : indicates probability of ith sample belonging to jth class.\n"
},
{
"code": "from sklearn.metrics import log_loss: LogLoss = log_loss(y_true, y_pred, eps = 1e-15, normalize = True, sample_weight = None, labels = None)",
"e": 25427,
"s": 25282,
"text": null
},
{
"code": null,
"e": 25538,
"s": 25427,
"text": "It is simply the average of the square of the difference between the original values and the predicted values."
},
{
"code": null,
"e": 25589,
"s": 25538,
"text": "Implementation of Mean Squared Error using sklearn"
},
{
"code": "from sklearn.metrics import mean_squared_error MSE = mean_squared_error(y_true, y_pred)",
"e": 25678,
"s": 25589,
"text": null
},
{
"code": null,
"e": 25690,
"s": 25678,
"text": "data mining"
},
{
"code": null,
"e": 25707,
"s": 25690,
"text": "Machine Learning"
},
{
"code": null,
"e": 25714,
"s": 25707,
"text": "Python"
},
{
"code": null,
"e": 25731,
"s": 25714,
"text": "Machine Learning"
},
{
"code": null,
"e": 25829,
"s": 25731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25838,
"s": 25829,
"text": "Comments"
},
{
"code": null,
"e": 25851,
"s": 25838,
"text": "Old Comments"
},
{
"code": null,
"e": 25875,
"s": 25851,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 25913,
"s": 25875,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 25959,
"s": 25913,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 25992,
"s": 25959,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 26026,
"s": 25992,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 26054,
"s": 26026,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26104,
"s": 26054,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26126,
"s": 26104,
"text": "Python map() function"
}
] |
Understanding the ROC Curve and AUC | by Doug Steen | Towards Data Science
|
The receiver operating characteristic (ROC) curve is frequently used for evaluating the performance of binary classification algorithms. It provides a graphical representation of a classifier’s performance, rather than a single value like most other metrics.
First, let’s establish that in binary classification, there are four possible outcomes for a test prediction: true positive, false positive, true negative, and false negative.
The ROC curve is produced by calculating and plotting the true positive rate against the false positive rate for a single classifier at a variety of thresholds. For example, in logistic regression, the threshold would be the predicted probability of an observation belonging to the positive class. Normally in logistic regression, if an observation is predicted to be positive at > 0.5 probability, it is labeled as positive. However, we could really choose any threshold between 0 and 1 (0.1, 0.3, 0.6, 0.99, etc.) — and ROC curves help us visualize how these choices affect classifier performance.
The true positive rate, or sensitivity, can be represented as:
where TP is the number of true positives and FN is the number of false negatives. The true positive rate is a measure of the probability that an actual positive instance will be classified as positive.
The false positive rate, or 1 — specificity, can be written as:
where FP is the number of false positives and TN is the number of true negatives. The false positive rate is essentially a measure of how often a “false alarm” will occur — or, how often an actual negative instance will be classified as positive.
Figure 1 demonstrates how some theoretical classifiers would plot on an ROC curve. The gray dotted line represents a classifier that is no better than random guessing — this will plot as a diagonal line. The purple line represents a perfect classifier — one with a true positive rate of 100% and a false positive rate of 0%. Nearly all real-world examples will fall somewhere between these two lines — not perfect, but providing more predictive power than random guessing. Typically, what we’re looking for is a classifier that maintains a high true positive rate while also having a low false positive rate — this ideal classifier would “hug” the upper left corner of Figure 1, much like the purple line.
While it is useful to visualize a classifier’s ROC curve, in many cases we can boil this information down to a single metric — the AUC.
AUC stands for area under the (ROC) curve. Generally, the higher the AUC score, the better a classifier performs for the given task.
Figure 2 shows that for a classifier with no predictive power (i.e., random guessing), AUC = 0.5, and for a perfect classifier, AUC = 1.0. Most classifiers will fall between 0.5 and 1.0, with the rare exception being a classifier performs worse than random guessing (AUC < 0.5).
One advantage presented by ROC curves is that they aid us in finding a classification threshold that suits our specific problem.
For example, if we were evaluating an email spam classifier, we would want the false positive rate to be really, really low. We wouldn’t want someone to lose an important email to the spam filter just because our algorithm was too aggressive. We would probably even allow a fair amount of actual spam emails (true positives) through the filter just to make sure that no important emails were lost.
On the other hand, if our classifier is predicting whether someone has a terminal illness, we might be ok with a higher number of false positives (incorrectly diagnosing the illness), just to make sure that we don’t miss any true positives (people who actually have the illness).
Additionally, ROC curves and AUC scores also allow us to compare the performance of different classifiers for the same problem.
To demonstrate how the ROC curve is constructed in practice, I’m going to work with the Heart Disease UCI data set in Python. The data set has 14 attributes, 303 observations, and is typically used to predict whether a patient has heart disease based on the other 13 attributes, which include age, sex, cholesterol level, and other measurements.
Imports & Loading Data
Train-Test Split
For this analysis, I’ll use a standard 75% — 25% train-test split.
Logistic Regression Classifier
Before I write a function to calculate false positive and true positive rate, I’ll fit a vanilla Logistic Regression classifier on the training data, and make predictions on the test set.
Calculating True Positive Rate and False Positive Rate
Now that I have test predictions, I can write a function to calculate the true positive rate and false positive rate. This is a critical step, as these are the two variables needed to produce the ROC curve.
(0.6923076923076923, 0.1891891891891892)
The test shows that the function appears to be working — a true positive rate of 69% and a false positive rate of 19% are perfectly reasonable results.
Exploring varying thresholds
To obtain the ROC curve, I need more than one pair of true positive/false positive rates. I need to vary the threshold probability that the Logistic Regression classifier uses to predict whether a patient has heart disease (target=1) or doesn’t (target=0). Remember, while Logistic Regression is used to assign a class label, what it’s actually doing is determining the probability that an observation belongs to a specific class. In a typical binary classification problem, an observation must have a probability of > 0.5 to be assigned to the positive class. However, in this case, I will vary that threshold probability value incrementally from 0 to 1. This will result in the ranges of true positive rates and false positive rates that allow me to build the ROC curve.
In the code blocks below, I obtain these true positive rates and false positive rates across a range of threshold probability values. For comparison, I use logistic regression with (1) no regularization and (2) L2 regularization.
Plotting the ROC Curves
Both versions of the logistic regression classifier seem to do a pretty good job, but the L2 regularized version appears to perform slightly better.
Calculating AUC scores
sklearn has an auc() function, which I’ll make use of here to calculate the AUC scores for both versions of the classifier. auc() takes in the true positive and false positive rates we previously calculated, and returns the AUC score.
Logistic Regression (No reg.) AUC 0.902979902979903Logistic Regression (L2 reg.) AUC 0.9116424116424116
As expected, the classifiers both have similar AUC scores, with the L2 regularized version performing slightly better.
Now that we’ve had fun plotting these ROC curves from scratch, you’ll be relieved to know that there is a much, much easier way. sklearn’s plot_roc_curve() function can efficiently plot ROC curves using only a fitted classifier and test data as input. These plots conveniently include the AUC score as well.
Closing
If you’ve made it this far, thanks for reading! I found it a valuable exercise to inefficiently create my own ROC curves in Python, and I hope you gained something from following along.
Some helpful references on ROC and AUC:
|
[
{
"code": null,
"e": 431,
"s": 172,
"text": "The receiver operating characteristic (ROC) curve is frequently used for evaluating the performance of binary classification algorithms. It provides a graphical representation of a classifier’s performance, rather than a single value like most other metrics."
},
{
"code": null,
"e": 607,
"s": 431,
"text": "First, let’s establish that in binary classification, there are four possible outcomes for a test prediction: true positive, false positive, true negative, and false negative."
},
{
"code": null,
"e": 1207,
"s": 607,
"text": "The ROC curve is produced by calculating and plotting the true positive rate against the false positive rate for a single classifier at a variety of thresholds. For example, in logistic regression, the threshold would be the predicted probability of an observation belonging to the positive class. Normally in logistic regression, if an observation is predicted to be positive at > 0.5 probability, it is labeled as positive. However, we could really choose any threshold between 0 and 1 (0.1, 0.3, 0.6, 0.99, etc.) — and ROC curves help us visualize how these choices affect classifier performance."
},
{
"code": null,
"e": 1270,
"s": 1207,
"text": "The true positive rate, or sensitivity, can be represented as:"
},
{
"code": null,
"e": 1472,
"s": 1270,
"text": "where TP is the number of true positives and FN is the number of false negatives. The true positive rate is a measure of the probability that an actual positive instance will be classified as positive."
},
{
"code": null,
"e": 1536,
"s": 1472,
"text": "The false positive rate, or 1 — specificity, can be written as:"
},
{
"code": null,
"e": 1783,
"s": 1536,
"text": "where FP is the number of false positives and TN is the number of true negatives. The false positive rate is essentially a measure of how often a “false alarm” will occur — or, how often an actual negative instance will be classified as positive."
},
{
"code": null,
"e": 2489,
"s": 1783,
"text": "Figure 1 demonstrates how some theoretical classifiers would plot on an ROC curve. The gray dotted line represents a classifier that is no better than random guessing — this will plot as a diagonal line. The purple line represents a perfect classifier — one with a true positive rate of 100% and a false positive rate of 0%. Nearly all real-world examples will fall somewhere between these two lines — not perfect, but providing more predictive power than random guessing. Typically, what we’re looking for is a classifier that maintains a high true positive rate while also having a low false positive rate — this ideal classifier would “hug” the upper left corner of Figure 1, much like the purple line."
},
{
"code": null,
"e": 2625,
"s": 2489,
"text": "While it is useful to visualize a classifier’s ROC curve, in many cases we can boil this information down to a single metric — the AUC."
},
{
"code": null,
"e": 2758,
"s": 2625,
"text": "AUC stands for area under the (ROC) curve. Generally, the higher the AUC score, the better a classifier performs for the given task."
},
{
"code": null,
"e": 3037,
"s": 2758,
"text": "Figure 2 shows that for a classifier with no predictive power (i.e., random guessing), AUC = 0.5, and for a perfect classifier, AUC = 1.0. Most classifiers will fall between 0.5 and 1.0, with the rare exception being a classifier performs worse than random guessing (AUC < 0.5)."
},
{
"code": null,
"e": 3166,
"s": 3037,
"text": "One advantage presented by ROC curves is that they aid us in finding a classification threshold that suits our specific problem."
},
{
"code": null,
"e": 3564,
"s": 3166,
"text": "For example, if we were evaluating an email spam classifier, we would want the false positive rate to be really, really low. We wouldn’t want someone to lose an important email to the spam filter just because our algorithm was too aggressive. We would probably even allow a fair amount of actual spam emails (true positives) through the filter just to make sure that no important emails were lost."
},
{
"code": null,
"e": 3844,
"s": 3564,
"text": "On the other hand, if our classifier is predicting whether someone has a terminal illness, we might be ok with a higher number of false positives (incorrectly diagnosing the illness), just to make sure that we don’t miss any true positives (people who actually have the illness)."
},
{
"code": null,
"e": 3972,
"s": 3844,
"text": "Additionally, ROC curves and AUC scores also allow us to compare the performance of different classifiers for the same problem."
},
{
"code": null,
"e": 4318,
"s": 3972,
"text": "To demonstrate how the ROC curve is constructed in practice, I’m going to work with the Heart Disease UCI data set in Python. The data set has 14 attributes, 303 observations, and is typically used to predict whether a patient has heart disease based on the other 13 attributes, which include age, sex, cholesterol level, and other measurements."
},
{
"code": null,
"e": 4341,
"s": 4318,
"text": "Imports & Loading Data"
},
{
"code": null,
"e": 4358,
"s": 4341,
"text": "Train-Test Split"
},
{
"code": null,
"e": 4425,
"s": 4358,
"text": "For this analysis, I’ll use a standard 75% — 25% train-test split."
},
{
"code": null,
"e": 4456,
"s": 4425,
"text": "Logistic Regression Classifier"
},
{
"code": null,
"e": 4644,
"s": 4456,
"text": "Before I write a function to calculate false positive and true positive rate, I’ll fit a vanilla Logistic Regression classifier on the training data, and make predictions on the test set."
},
{
"code": null,
"e": 4699,
"s": 4644,
"text": "Calculating True Positive Rate and False Positive Rate"
},
{
"code": null,
"e": 4906,
"s": 4699,
"text": "Now that I have test predictions, I can write a function to calculate the true positive rate and false positive rate. This is a critical step, as these are the two variables needed to produce the ROC curve."
},
{
"code": null,
"e": 4947,
"s": 4906,
"text": "(0.6923076923076923, 0.1891891891891892)"
},
{
"code": null,
"e": 5099,
"s": 4947,
"text": "The test shows that the function appears to be working — a true positive rate of 69% and a false positive rate of 19% are perfectly reasonable results."
},
{
"code": null,
"e": 5128,
"s": 5099,
"text": "Exploring varying thresholds"
},
{
"code": null,
"e": 5901,
"s": 5128,
"text": "To obtain the ROC curve, I need more than one pair of true positive/false positive rates. I need to vary the threshold probability that the Logistic Regression classifier uses to predict whether a patient has heart disease (target=1) or doesn’t (target=0). Remember, while Logistic Regression is used to assign a class label, what it’s actually doing is determining the probability that an observation belongs to a specific class. In a typical binary classification problem, an observation must have a probability of > 0.5 to be assigned to the positive class. However, in this case, I will vary that threshold probability value incrementally from 0 to 1. This will result in the ranges of true positive rates and false positive rates that allow me to build the ROC curve."
},
{
"code": null,
"e": 6131,
"s": 5901,
"text": "In the code blocks below, I obtain these true positive rates and false positive rates across a range of threshold probability values. For comparison, I use logistic regression with (1) no regularization and (2) L2 regularization."
},
{
"code": null,
"e": 6155,
"s": 6131,
"text": "Plotting the ROC Curves"
},
{
"code": null,
"e": 6304,
"s": 6155,
"text": "Both versions of the logistic regression classifier seem to do a pretty good job, but the L2 regularized version appears to perform slightly better."
},
{
"code": null,
"e": 6327,
"s": 6304,
"text": "Calculating AUC scores"
},
{
"code": null,
"e": 6562,
"s": 6327,
"text": "sklearn has an auc() function, which I’ll make use of here to calculate the AUC scores for both versions of the classifier. auc() takes in the true positive and false positive rates we previously calculated, and returns the AUC score."
},
{
"code": null,
"e": 6666,
"s": 6562,
"text": "Logistic Regression (No reg.) AUC 0.902979902979903Logistic Regression (L2 reg.) AUC 0.9116424116424116"
},
{
"code": null,
"e": 6785,
"s": 6666,
"text": "As expected, the classifiers both have similar AUC scores, with the L2 regularized version performing slightly better."
},
{
"code": null,
"e": 7093,
"s": 6785,
"text": "Now that we’ve had fun plotting these ROC curves from scratch, you’ll be relieved to know that there is a much, much easier way. sklearn’s plot_roc_curve() function can efficiently plot ROC curves using only a fitted classifier and test data as input. These plots conveniently include the AUC score as well."
},
{
"code": null,
"e": 7101,
"s": 7093,
"text": "Closing"
},
{
"code": null,
"e": 7287,
"s": 7101,
"text": "If you’ve made it this far, thanks for reading! I found it a valuable exercise to inefficiently create my own ROC curves in Python, and I hope you gained something from following along."
}
] |
Decision Tree: build, prune and visualize it using Python | by Gustavo Hideo | Towards Data Science
|
Binary Tree is one of the most common and powerful data structures of the computing world. The main reason machine learning engineers like decision trees so much is that it has a low cost to process and it’s really easy to understand (it’s transparent, in opposition to the “black box” from the neural network). It uses a branching method to go over every feature and its different outcomes finding patterns for the target values. For a more detailed explanation of decision trees and different methods of branching, check out this article from Thomas Plapinger.
Let’s get started!
We will be using the Titanic data set from a Kaggle to predict survivors. We will import the data and select some features to work with. ‘Survived’ is our target value.
data = pd.read_csv(‘path_or_link/train.csv’)data = data.loc[:,(‘Survived’,’Pclass’,’Sex’,’Age’,’SibSp’,’Parch’,’Fare’)]
Missing valuesWe have some missing values for ‘age’. To fix it, we could run some predictive analysis and fill up these spots, but that’s not the goal for this article, so we will let it for a future story. For now, let’s just drop those rows with missing values.
Encoding categorical featuresTo keep all the features in numeric format, we will encode the ‘Sex’, that means to transform the values from ‘female’ and ‘male’ to 0 and 1.
data.dropna(inplace=True)#'inplace=True' applies the code to the 'data' object.from sklearn.preprocessing import LabelEncoderle = LabelEncoder()data.Sex = le.fit_transform(data.Sex)
Splitting data set into train and test sets
x = data.iloc[:,1:] # Second column until the last columny = data.iloc[:,0] # First column (Survived) is our targetfrom sklearn.model_selection import train_test_split#this function randomly split the data into train and test setsx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.3)#test_size=.3 means that our test set will be 30% of the train set.
Building the decision tree classifierDecisionTreeClassifier() from sklearn is a good off the shelf machine learning model available to us. It has fit() and predict() methods. The fit() method is the “training” part of the modeling process. It finds the coefficients for the algorithm. Then, the predict() method will use the trained model to make predictions on a new set of data (test set).
dtree = DecisionTreeClassifier()dtree.fit(x_train, y_train) #train parameters: features and targetpred = dtree.predict(x_test) #parameter: new data to predict
AccuracyTo determine how good our model is, we use another package from sklearn to give it a measure:
from sklearn.metrics import accuracy_scoreaccuracy_score(y_test, pred)#parameters: targets to be predicted and predictions from new data used before
Accuracy: 0.75It means that we have 75% accuracy in our predictions.
We can plot the tree to see its root, branches, and nodes. We will use a set of new libraries to do so.
from sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIOfrom IPython.display import Image import pydotplusdot_data = StringIO()export_graphviz(dtree, out_file=dot_data)graph = pydotplus.graph_from_dot_data(dot_data.getvalue())graph.write_png('/tree.png')Image(graph.create_png())
StringIO(): creates an object (empty in this case) to receive a string buffer (the tree will be created first as a string before as an image) in DOT (graph description language) format.export_graphviz(): this function exports the tree in DOT format, generating a representation of the decision tree, which is written into the ‘out_file’.graph_from_dot_data(): will use the DOT object to create the graph.Image(): uses raw data to return an image (png, jpeg, gif).
This tree seems pretty long. Let’s change a couple of parameters to see if there is any effect on the accuracy and also to make the tree shorter.
Criterion: defines what function will be used to measure the quality of a split. The options are “gini” and “entropy”.
Max_depth: defines the maximum depth of the tree. If it’s “none”, the tree will be as long as possible, when all the leaves are pure (risk of overfitting the model).
dtree = DecisionTreeClassifier(criterion='gini')dtree.fit(x_train, y_train)pred = dtree.predict(x_test)print('Criterion=gini', accuracy_score(y_test, pred))dtree = DecisionTreeClassifier(criterion='entropy')dtree.fit(x_train, y_train)pred = dtree.predict(x_test)print('Criterion=entropy', accuracy_score(y_test, pred))
Accuracy results:Criterion=gini: 0.735Criterion=entropy: 0.716
The gini method has a slight improvement over the entropy. Now, let’s check if pruning the tree using max_depth can give us any better results. In the code chunk below, I create a simple function to run our model using different values for max_depth (from 1 to 30) and visualize its results to see how the accuracy differs for each value.
max_depth = []acc_gini = []acc_entropy = []for i in range(1,30): dtree = DecisionTreeClassifier(criterion=’gini’, max_depth=i) dtree.fit(x_train, y_train) pred = dtree.predict(x_test) acc_gini.append(accuracy_score(y_test, pred)) #### dtree = DecisionTreeClassifier(criterion=’entropy’, max_depth=i) dtree.fit(x_train, y_train) pred = dtree.predict(x_test) acc_entropy.append(accuracy_score(y_test, pred)) #### max_depth.append(i)d = pd.DataFrame({‘acc_gini’:pd.Series(acc_gini), ‘acc_entropy’:pd.Series(acc_entropy), ‘max_depth’:pd.Series(max_depth)})# visualizing changes in parametersplt.plot(‘max_depth’,’acc_gini’, data=d, label=’gini’)plt.plot(‘max_depth’,’acc_entropy’, data=d, label=’entropy’)plt.xlabel(‘max_depth’)plt.ylabel(‘accuracy’)plt.legend()
It seems like in this scenario gini works best for longer trees (as we saw in the previous accuracies), but entropy does a better job for shorter trees and it’s more accurate (near 0.82). So let’s draw the tree with max_depth=7 and criterion=entropy to see how it looks like.
dtree = DecisionTreeClassifier(criterion=’entropy’, max_depth=7)dtree.fit(x_train, y_train)pred = dtree.predict(x_test)accuracy_score(y_test, pred)#Accuracy: 0.814
We went from 0.75 of accuracy to 0.81 just by changing the function to create the branches and limiting the tree to avoid overfitting. Each case is different and it’s a good practice to test different parameters to find the best for your scenario. As you learn new functions and machine learning models, don’t hesitate in reading the documentation. It will give you a broader set of options to customize the model to your needs.
Now, go ahead, use your new set of skills and save the planet by planting a tree.
|
[
{
"code": null,
"e": 734,
"s": 171,
"text": "Binary Tree is one of the most common and powerful data structures of the computing world. The main reason machine learning engineers like decision trees so much is that it has a low cost to process and it’s really easy to understand (it’s transparent, in opposition to the “black box” from the neural network). It uses a branching method to go over every feature and its different outcomes finding patterns for the target values. For a more detailed explanation of decision trees and different methods of branching, check out this article from Thomas Plapinger."
},
{
"code": null,
"e": 753,
"s": 734,
"text": "Let’s get started!"
},
{
"code": null,
"e": 922,
"s": 753,
"text": "We will be using the Titanic data set from a Kaggle to predict survivors. We will import the data and select some features to work with. ‘Survived’ is our target value."
},
{
"code": null,
"e": 1042,
"s": 922,
"text": "data = pd.read_csv(‘path_or_link/train.csv’)data = data.loc[:,(‘Survived’,’Pclass’,’Sex’,’Age’,’SibSp’,’Parch’,’Fare’)]"
},
{
"code": null,
"e": 1306,
"s": 1042,
"text": "Missing valuesWe have some missing values for ‘age’. To fix it, we could run some predictive analysis and fill up these spots, but that’s not the goal for this article, so we will let it for a future story. For now, let’s just drop those rows with missing values."
},
{
"code": null,
"e": 1477,
"s": 1306,
"text": "Encoding categorical featuresTo keep all the features in numeric format, we will encode the ‘Sex’, that means to transform the values from ‘female’ and ‘male’ to 0 and 1."
},
{
"code": null,
"e": 1659,
"s": 1477,
"text": "data.dropna(inplace=True)#'inplace=True' applies the code to the 'data' object.from sklearn.preprocessing import LabelEncoderle = LabelEncoder()data.Sex = le.fit_transform(data.Sex)"
},
{
"code": null,
"e": 1703,
"s": 1659,
"text": "Splitting data set into train and test sets"
},
{
"code": null,
"e": 2077,
"s": 1703,
"text": "x = data.iloc[:,1:] # Second column until the last columny = data.iloc[:,0] # First column (Survived) is our targetfrom sklearn.model_selection import train_test_split#this function randomly split the data into train and test setsx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.3)#test_size=.3 means that our test set will be 30% of the train set."
},
{
"code": null,
"e": 2469,
"s": 2077,
"text": "Building the decision tree classifierDecisionTreeClassifier() from sklearn is a good off the shelf machine learning model available to us. It has fit() and predict() methods. The fit() method is the “training” part of the modeling process. It finds the coefficients for the algorithm. Then, the predict() method will use the trained model to make predictions on a new set of data (test set)."
},
{
"code": null,
"e": 2630,
"s": 2469,
"text": "dtree = DecisionTreeClassifier()dtree.fit(x_train, y_train) #train parameters: features and targetpred = dtree.predict(x_test) #parameter: new data to predict"
},
{
"code": null,
"e": 2732,
"s": 2630,
"text": "AccuracyTo determine how good our model is, we use another package from sklearn to give it a measure:"
},
{
"code": null,
"e": 2881,
"s": 2732,
"text": "from sklearn.metrics import accuracy_scoreaccuracy_score(y_test, pred)#parameters: targets to be predicted and predictions from new data used before"
},
{
"code": null,
"e": 2950,
"s": 2881,
"text": "Accuracy: 0.75It means that we have 75% accuracy in our predictions."
},
{
"code": null,
"e": 3054,
"s": 2950,
"text": "We can plot the tree to see its root, branches, and nodes. We will use a set of new libraries to do so."
},
{
"code": null,
"e": 3361,
"s": 3054,
"text": "from sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIOfrom IPython.display import Image import pydotplusdot_data = StringIO()export_graphviz(dtree, out_file=dot_data)graph = pydotplus.graph_from_dot_data(dot_data.getvalue())graph.write_png('/tree.png')Image(graph.create_png())"
},
{
"code": null,
"e": 3825,
"s": 3361,
"text": "StringIO(): creates an object (empty in this case) to receive a string buffer (the tree will be created first as a string before as an image) in DOT (graph description language) format.export_graphviz(): this function exports the tree in DOT format, generating a representation of the decision tree, which is written into the ‘out_file’.graph_from_dot_data(): will use the DOT object to create the graph.Image(): uses raw data to return an image (png, jpeg, gif)."
},
{
"code": null,
"e": 3971,
"s": 3825,
"text": "This tree seems pretty long. Let’s change a couple of parameters to see if there is any effect on the accuracy and also to make the tree shorter."
},
{
"code": null,
"e": 4090,
"s": 3971,
"text": "Criterion: defines what function will be used to measure the quality of a split. The options are “gini” and “entropy”."
},
{
"code": null,
"e": 4256,
"s": 4090,
"text": "Max_depth: defines the maximum depth of the tree. If it’s “none”, the tree will be as long as possible, when all the leaves are pure (risk of overfitting the model)."
},
{
"code": null,
"e": 4575,
"s": 4256,
"text": "dtree = DecisionTreeClassifier(criterion='gini')dtree.fit(x_train, y_train)pred = dtree.predict(x_test)print('Criterion=gini', accuracy_score(y_test, pred))dtree = DecisionTreeClassifier(criterion='entropy')dtree.fit(x_train, y_train)pred = dtree.predict(x_test)print('Criterion=entropy', accuracy_score(y_test, pred))"
},
{
"code": null,
"e": 4638,
"s": 4575,
"text": "Accuracy results:Criterion=gini: 0.735Criterion=entropy: 0.716"
},
{
"code": null,
"e": 4977,
"s": 4638,
"text": "The gini method has a slight improvement over the entropy. Now, let’s check if pruning the tree using max_depth can give us any better results. In the code chunk below, I create a simple function to run our model using different values for max_depth (from 1 to 30) and visualize its results to see how the accuracy differs for each value."
},
{
"code": null,
"e": 5737,
"s": 4977,
"text": "max_depth = []acc_gini = []acc_entropy = []for i in range(1,30): dtree = DecisionTreeClassifier(criterion=’gini’, max_depth=i) dtree.fit(x_train, y_train) pred = dtree.predict(x_test) acc_gini.append(accuracy_score(y_test, pred)) #### dtree = DecisionTreeClassifier(criterion=’entropy’, max_depth=i) dtree.fit(x_train, y_train) pred = dtree.predict(x_test) acc_entropy.append(accuracy_score(y_test, pred)) #### max_depth.append(i)d = pd.DataFrame({‘acc_gini’:pd.Series(acc_gini), ‘acc_entropy’:pd.Series(acc_entropy), ‘max_depth’:pd.Series(max_depth)})# visualizing changes in parametersplt.plot(‘max_depth’,’acc_gini’, data=d, label=’gini’)plt.plot(‘max_depth’,’acc_entropy’, data=d, label=’entropy’)plt.xlabel(‘max_depth’)plt.ylabel(‘accuracy’)plt.legend()"
},
{
"code": null,
"e": 6013,
"s": 5737,
"text": "It seems like in this scenario gini works best for longer trees (as we saw in the previous accuracies), but entropy does a better job for shorter trees and it’s more accurate (near 0.82). So let’s draw the tree with max_depth=7 and criterion=entropy to see how it looks like."
},
{
"code": null,
"e": 6177,
"s": 6013,
"text": "dtree = DecisionTreeClassifier(criterion=’entropy’, max_depth=7)dtree.fit(x_train, y_train)pred = dtree.predict(x_test)accuracy_score(y_test, pred)#Accuracy: 0.814"
},
{
"code": null,
"e": 6606,
"s": 6177,
"text": "We went from 0.75 of accuracy to 0.81 just by changing the function to create the branches and limiting the tree to avoid overfitting. Each case is different and it’s a good practice to test different parameters to find the best for your scenario. As you learn new functions and machine learning models, don’t hesitate in reading the documentation. It will give you a broader set of options to customize the model to your needs."
}
] |
VB.Net - Classes & Objects
|
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
Objects are instances of a class. The methods and variables that constitute a class are called members of the class.
A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End Class statement. Following is the general form of a class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
attributelist is a list of attributes that apply to the class. Optional.
attributelist is a list of attributes that apply to the class. Optional.
accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional.
MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional.
NotInheritable specifies that the class cannot be used as a base class.
NotInheritable specifies that the class cannot be used as a base class.
Partial indicates a partial definition of the class.
Partial indicates a partial definition of the class.
Inherits specifies the base class it is inheriting from.
Inherits specifies the base class it is inheriting from.
Implements specifies the interfaces the class is inheriting from.
Implements specifies the interfaces the class is inheriting from.
The following example demonstrates a Box class, with three data members, length, breadth and height −
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class −
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Sub setBreadth(ByVal bre As Double)
breadth = bre
End Sub
Public Sub setHeight(ByVal hei As Double)
height = hei
End Sub
Public Function getVolume() As Double
Return length * breadth * height
End Function
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
' volume of box 1
volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
A class constructor is a special member Sub of a class that is executed whenever we create new objects of that class. A constructor has the name New and it does not have any return type.
Following program explains the concept of constructor −
Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
A default constructor does not have any parameter, but if you need, a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example −
Class Line
Private length As Double ' Length of a line
Public Sub New(ByVal len As Double) 'parameterised constructor
Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line(10.0)
Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
A destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories, etc.
Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor −
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
Protected Overrides Sub Finalize() ' destructor
Console.WriteLine("Object is being deleted")
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
Object is being deleted
We can define class members as static using the Shared keyword. When we declare a member of a class as Shared, it means no matter how many objects of the class are created, there is only one copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can also initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared variables. The Shared functions exist even before the object is created.
The following example demonstrates the use of shared members −
Class StaticVar
Public Shared num As Integer
Public Sub count()
num = num + 1
End Sub
Public Shared Function getNum() As Integer
Return num
End Function
Shared Sub Main()
Dim s As StaticVar = New StaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Value of variable num: 3
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle −
' Base class
Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Total area: 35
The derived class inherits the base class member variables and member methods. Therefore, the super class object should be created before the subclass is created. The super class or the base class is implicitly known as MyBase in VB.Net
The following program demonstrates this −
' Base class
Class Rectangle
Protected width As Double
Protected length As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
length = l
width = w
End Sub
Public Function GetArea() As Double
Return (width * length)
End Function
Public Overridable Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
'end class Rectangle
End Class
'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
VB.Net supports multiple inheritance.
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2559,
"s": 2300,
"text": "When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object."
},
{
"code": null,
"e": 2676,
"s": 2559,
"text": "Objects are instances of a class. The methods and variables that constitute a class are called members of the class."
},
{
"code": null,
"e": 2861,
"s": 2676,
"text": "A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End Class statement. Following is the general form of a class definition −"
},
{
"code": null,
"e": 3077,
"s": 2861,
"text": "[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _\nClass name [ ( Of typelist ) ]\n [ Inherits classname ]\n [ Implements interfacenames ]\n [ statements ]\nEnd Class"
},
{
"code": null,
"e": 3084,
"s": 3077,
"text": "Where,"
},
{
"code": null,
"e": 3157,
"s": 3084,
"text": "attributelist is a list of attributes that apply to the class. Optional."
},
{
"code": null,
"e": 3230,
"s": 3157,
"text": "attributelist is a list of attributes that apply to the class. Optional."
},
{
"code": null,
"e": 3371,
"s": 3230,
"text": "accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional."
},
{
"code": null,
"e": 3512,
"s": 3371,
"text": "accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional."
},
{
"code": null,
"e": 3657,
"s": 3512,
"text": "Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional."
},
{
"code": null,
"e": 3802,
"s": 3657,
"text": "Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional."
},
{
"code": null,
"e": 3962,
"s": 3802,
"text": "MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional."
},
{
"code": null,
"e": 4122,
"s": 3962,
"text": "MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional."
},
{
"code": null,
"e": 4194,
"s": 4122,
"text": "NotInheritable specifies that the class cannot be used as a base class."
},
{
"code": null,
"e": 4266,
"s": 4194,
"text": "NotInheritable specifies that the class cannot be used as a base class."
},
{
"code": null,
"e": 4319,
"s": 4266,
"text": "Partial indicates a partial definition of the class."
},
{
"code": null,
"e": 4372,
"s": 4319,
"text": "Partial indicates a partial definition of the class."
},
{
"code": null,
"e": 4429,
"s": 4372,
"text": "Inherits specifies the base class it is inheriting from."
},
{
"code": null,
"e": 4486,
"s": 4429,
"text": "Inherits specifies the base class it is inheriting from."
},
{
"code": null,
"e": 4552,
"s": 4486,
"text": "Implements specifies the interfaces the class is inheriting from."
},
{
"code": null,
"e": 4618,
"s": 4552,
"text": "Implements specifies the interfaces the class is inheriting from."
},
{
"code": null,
"e": 4720,
"s": 4618,
"text": "The following example demonstrates a Box class, with three data members, length, breadth and height −"
},
{
"code": null,
"e": 5684,
"s": 4720,
"text": "Module mybox\n Class Box\n Public length As Double ' Length of a box\n Public breadth As Double ' Breadth of a box\n Public height As Double ' Height of a box\n End Class\n Sub Main()\n Dim Box1 As Box = New Box() ' Declare Box1 of type Box\n Dim Box2 As Box = New Box() ' Declare Box2 of type Box\n Dim volume As Double = 0.0 ' Store the volume of a box here\n \n ' box 1 specification\n Box1.height = 5.0\n Box1.length = 6.0\n Box1.breadth = 7.0\n \n ' box 2 specification\n Box2.height = 10.0\n Box2.length = 12.0\t\n Box2.breadth = 13.0\n \n 'volume of box 1\n volume = Box1.height * Box1.length * Box1.breadth\n Console.WriteLine(\"Volume of Box1 : {0}\", volume)\n \n 'volume of box 2\n volume = Box2.height * Box2.length * Box2.breadth\n Console.WriteLine(\"Volume of Box2 : {0}\", volume)\n Console.ReadKey()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 5765,
"s": 5684,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5809,
"s": 5765,
"text": "Volume of Box1 : 210\nVolume of Box2 : 1560\n"
},
{
"code": null,
"e": 6071,
"s": 5809,
"text": "A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member and has access to all the members of a class for that object."
},
{
"code": null,
"e": 6268,
"s": 6071,
"text": "Member variables are attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions."
},
{
"code": null,
"e": 6359,
"s": 6268,
"text": "Let us put above concepts to set and get the value of different class members in a class −"
},
{
"code": null,
"e": 7657,
"s": 6359,
"text": "Module mybox\n Class Box\n Public length As Double ' Length of a box\n Public breadth As Double ' Breadth of a box\n Public height As Double ' Height of a box\n Public Sub setLength(ByVal len As Double)\n length = len\n End Sub\n \n Public Sub setBreadth(ByVal bre As Double)\n breadth = bre\n End Sub\n \n Public Sub setHeight(ByVal hei As Double)\n height = hei\n End Sub\n \n Public Function getVolume() As Double\n Return length * breadth * height\n End Function\n End Class\n Sub Main()\n Dim Box1 As Box = New Box() ' Declare Box1 of type Box\n Dim Box2 As Box = New Box() ' Declare Box2 of type Box\n Dim volume As Double = 0.0 ' Store the volume of a box here\n\n ' box 1 specification\n Box1.setLength(6.0)\n Box1.setBreadth(7.0)\n Box1.setHeight(5.0)\n \n 'box 2 specification\n Box2.setLength(12.0)\n Box2.setBreadth(13.0)\n Box2.setHeight(10.0)\n \n ' volume of box 1\n volume = Box1.getVolume()\n Console.WriteLine(\"Volume of Box1 : {0}\", volume)\n\n 'volume of box 2\n volume = Box2.getVolume()\n Console.WriteLine(\"Volume of Box2 : {0}\", volume)\n Console.ReadKey()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 7738,
"s": 7657,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7782,
"s": 7738,
"text": "Volume of Box1 : 210\nVolume of Box2 : 1560\n"
},
{
"code": null,
"e": 7969,
"s": 7782,
"text": "A class constructor is a special member Sub of a class that is executed whenever we create new objects of that class. A constructor has the name New and it does not have any return type."
},
{
"code": null,
"e": 8025,
"s": 7969,
"text": "Following program explains the concept of constructor −"
},
{
"code": null,
"e": 8562,
"s": 8025,
"text": "Class Line\n Private length As Double ' Length of a line\n Public Sub New() 'constructor\n Console.WriteLine(\"Object is being created\")\n End Sub\n \n Public Sub setLength(ByVal len As Double)\n length = len\n End Sub\n \n Public Function getLength() As Double\n Return length\n End Function\n Shared Sub Main()\n Dim line As Line = New Line()\n 'set line length\n line.setLength(6.0)\n Console.WriteLine(\"Length of line : {0}\", line.getLength())\n Console.ReadKey()\n End Sub\nEnd Class"
},
{
"code": null,
"e": 8643,
"s": 8562,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8687,
"s": 8643,
"text": "Object is being created\nLength of line : 6\n"
},
{
"code": null,
"e": 8973,
"s": 8687,
"text": "A default constructor does not have any parameter, but if you need, a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example −"
},
{
"code": null,
"e": 9685,
"s": 8973,
"text": "Class Line\n Private length As Double ' Length of a line\n Public Sub New(ByVal len As Double) 'parameterised constructor\n Console.WriteLine(\"Object is being created, length = {0}\", len)\n length = len\n End Sub\n Public Sub setLength(ByVal len As Double)\n length = len\n End Sub\n \n Public Function getLength() As Double\n Return length\n End Function\n Shared Sub Main()\n Dim line As Line = New Line(10.0)\n Console.WriteLine(\"Length of line set by constructor : {0}\", line.getLength())\n 'set line length\n line.setLength(6.0)\n Console.WriteLine(\"Length of line set by setLength : {0}\", line.getLength())\n Console.ReadKey()\n End Sub\nEnd Class"
},
{
"code": null,
"e": 9766,
"s": 9685,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 9879,
"s": 9766,
"text": "Object is being created, length = 10\nLength of line set by constructor : 10\nLength of line set by setLength : 6\n"
},
{
"code": null,
"e": 9995,
"s": 9879,
"text": "A destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope."
},
{
"code": null,
"e": 10228,
"s": 9995,
"text": "A destructor has the name Finalize and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories, etc."
},
{
"code": null,
"e": 10275,
"s": 10228,
"text": "Destructors cannot be inherited or overloaded."
},
{
"code": null,
"e": 10330,
"s": 10275,
"text": "Following example explains the concept of destructor −"
},
{
"code": null,
"e": 11001,
"s": 10330,
"text": "Class Line\n Private length As Double ' Length of a line\n Public Sub New() 'parameterised constructor\n Console.WriteLine(\"Object is being created\")\n End Sub\n \n Protected Overrides Sub Finalize() ' destructor\n Console.WriteLine(\"Object is being deleted\")\n End Sub\n \n Public Sub setLength(ByVal len As Double)\n length = len\n End Sub\n \n Public Function getLength() As Double\n Return length\n End Function\n \n Shared Sub Main()\n Dim line As Line = New Line()\n 'set line length\n line.setLength(6.0)\n Console.WriteLine(\"Length of line : {0}\", line.getLength())\n Console.ReadKey()\n End Sub\nEnd Class"
},
{
"code": null,
"e": 11082,
"s": 11001,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 11150,
"s": 11082,
"text": "Object is being created\nLength of line : 6\nObject is being deleted\n"
},
{
"code": null,
"e": 11361,
"s": 11150,
"text": "We can define class members as static using the Shared keyword. When we declare a member of a class as Shared, it means no matter how many objects of the class are created, there is only one copy of the member."
},
{
"code": null,
"e": 11590,
"s": 11361,
"text": "The keyword Shared implies that only one instance of the member exists for a class. Shared variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it."
},
{
"code": null,
"e": 11745,
"s": 11590,
"text": "Shared variables can be initialized outside the member function or class definition. You can also initialize Shared variables inside the class definition."
},
{
"code": null,
"e": 11906,
"s": 11745,
"text": "You can also declare a member function as Shared. Such functions can access only Shared variables. The Shared functions exist even before the object is created."
},
{
"code": null,
"e": 11969,
"s": 11906,
"text": "The following example demonstrates the use of shared members −"
},
{
"code": null,
"e": 12380,
"s": 11969,
"text": "Class StaticVar\n Public Shared num As Integer\n Public Sub count()\n num = num + 1\n End Sub\n Public Shared Function getNum() As Integer\n Return num\n End Function\n Shared Sub Main()\n Dim s As StaticVar = New StaticVar()\n s.count()\n s.count()\n s.count()\n Console.WriteLine(\"Value of variable num: {0}\", StaticVar.getNum())\n Console.ReadKey()\n End Sub\nEnd Class"
},
{
"code": null,
"e": 12461,
"s": 12380,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 12487,
"s": 12461,
"text": "Value of variable num: 3\n"
},
{
"code": null,
"e": 12800,
"s": 12487,
"text": "One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time."
},
{
"code": null,
"e": 13090,
"s": 12800,
"text": "When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class."
},
{
"code": null,
"e": 13245,
"s": 13090,
"text": "A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces."
},
{
"code": null,
"e": 13316,
"s": 13245,
"text": "The syntax used in VB.Net for creating derived classes is as follows −"
},
{
"code": null,
"e": 13428,
"s": 13316,
"text": "<access-specifier> Class <base_class>\n...\nEnd Class\nClass <derived_class>: Inherits <base_class>\n...\nEnd Class\n"
},
{
"code": null,
"e": 13490,
"s": 13428,
"text": "Consider a base class Shape and its derived class Rectangle −"
},
{
"code": null,
"e": 14152,
"s": 13490,
"text": "' Base class\nClass Shape\n Protected width As Integer\n Protected height As Integer\n Public Sub setWidth(ByVal w As Integer)\n width = w\n End Sub\n Public Sub setHeight(ByVal h As Integer)\n height = h\n End Sub\nEnd Class\n' Derived class\nClass Rectangle : Inherits Shape\n Public Function getArea() As Integer\n Return (width * height)\n End Function\nEnd Class\nClass RectangleTester\n Shared Sub Main()\n Dim rect As Rectangle = New Rectangle()\n rect.setWidth(5)\n rect.setHeight(7)\n ' Print the area of the object.\n Console.WriteLine(\"Total area: {0}\", rect.getArea())\n Console.ReadKey()\n End Sub\t\nEnd Class"
},
{
"code": null,
"e": 14233,
"s": 14152,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 14249,
"s": 14233,
"text": "Total area: 35\n"
},
{
"code": null,
"e": 14486,
"s": 14249,
"text": "The derived class inherits the base class member variables and member methods. Therefore, the super class object should be created before the subclass is created. The super class or the base class is implicitly known as MyBase in VB.Net"
},
{
"code": null,
"e": 14528,
"s": 14486,
"text": "The following program demonstrates this −"
},
{
"code": null,
"e": 15623,
"s": 14528,
"text": "' Base class\nClass Rectangle\n Protected width As Double\n Protected length As Double\n Public Sub New(ByVal l As Double, ByVal w As Double)\n length = l\n width = w\n End Sub\n Public Function GetArea() As Double\n Return (width * length)\n End Function\n Public Overridable Sub Display()\n Console.WriteLine(\"Length: {0}\", length)\n Console.WriteLine(\"Width: {0}\", width)\n Console.WriteLine(\"Area: {0}\", GetArea())\n End Sub\n 'end class Rectangle \nEnd Class\n\n'Derived class\nClass Tabletop : Inherits Rectangle\n Private cost As Double\n Public Sub New(ByVal l As Double, ByVal w As Double)\n MyBase.New(l, w)\n End Sub\n Public Function GetCost() As Double\n Dim cost As Double\n cost = GetArea() * 70\n Return cost\n End Function\n Public Overrides Sub Display()\n MyBase.Display()\n Console.WriteLine(\"Cost: {0}\", GetCost())\n End Sub\n 'end class Tabletop\nEnd Class\nClass RectangleTester\n Shared Sub Main()\n Dim t As Tabletop = New Tabletop(4.5, 7.5)\n t.Display()\n Console.ReadKey()\n End Sub\nEnd Class"
},
{
"code": null,
"e": 15704,
"s": 15623,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 15753,
"s": 15704,
"text": "Length: 4.5\nWidth: 7.5\nArea: 33.75\nCost: 2362.5\n"
},
{
"code": null,
"e": 15791,
"s": 15753,
"text": "VB.Net supports multiple inheritance."
},
{
"code": null,
"e": 15824,
"s": 15791,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15841,
"s": 15824,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 15876,
"s": 15841,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 15891,
"s": 15876,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 15926,
"s": 15891,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 15941,
"s": 15926,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 15974,
"s": 15941,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 15989,
"s": 15974,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 15996,
"s": 15989,
"text": " Print"
},
{
"code": null,
"e": 16007,
"s": 15996,
"text": " Add Notes"
}
] |
How to install a Python package into a different directory using pip?
|
You can specify the install-option CLI argument to set the prefix path of the installation directory while installing a new module. For example, if you want to install your package to /tmp, then run the following command −
pip install --install-option="--prefix=/tmp" package_name
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "You can specify the install-option CLI argument to set the prefix path of the installation directory while installing a new module. For example, if you want to install your package to /tmp, then run the following command −"
},
{
"code": null,
"e": 1343,
"s": 1285,
"text": "pip install --install-option=\"--prefix=/tmp\" package_name"
}
] |
Exposed Drop-Down Menu in Android - GeeksforGeeks
|
23 Jun, 2021
The Exposed Drop-Down menu is the replacement for Spinner in Android because Spinner is not that customizable like the new exposed Drop-Down menu. Below is the sample GIF to give an idea of what we are going to build. Note that we are going to implement this project using the Kotlin language.
Step 1: Create a new Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. 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"> <!--Create a TextInputLayout and choose the style, for now we are choosing the OutlinedBox ExposedDropdownMenu --> <com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"> <!-- Inside text input layout add an auto complete text view and make its input type to none--> <AutoCompleteTextView android:id="@+id/autoCompleteTextView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:inputType="none" android:text="Choose Programming language" /> </com.google.android.material.textfield.TextInputLayout> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Add string array items to the string.xml file. We will use this data to inflate the drop-down items
XML
<string-array name="programming_languages"> <item>Java</item> <item>Kotlin</item> <item>Python</item> <item>CPP</item></string-array>
Step 4: Create a new layout file and name it a dropdown_item.xml file
Go to the dropdown_item.xml file and refer to the following code. Below is the code for the dropdown_item.xml file. It is the single-text view which we will use as a single item of the dropdown.
XML
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textView" android:layout_width="match_parent" android:textColor="@color/black" android:textStyle="bold" android:padding="14dp" android:layout_height="wrap_content" android:text="TextView" />
Step 5: Working with MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.ArrayAdapterimport android.widget.AutoCompleteTextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get reference to the string array that we just created val languages = resources.getStringArray(R.array.programming_languages) // create an array adapter and pass the required parameter // in our case pass the context, drop down layout , and array. val arrayAdapter = ArrayAdapter(this, R.layout.dropdown_menu, languages) // get reference to the autocomplete text view val autocompleteTV = findViewById<AutoCompleteTextView>(R.id.autoCompleteTextView) // set adapter to the autocomplete tv to the arrayAdapter autocompleteTV.setAdapter(arrayAdapter) }}
Output:
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Flutter - Custom Bottom Navigation Bar
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Android UI Layouts
|
[
{
"code": null,
"e": 25070,
"s": 25042,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25364,
"s": 25070,
"text": "The Exposed Drop-Down menu is the replacement for Spinner in Android because Spinner is not that customizable like the new exposed Drop-Down menu. Below is the sample GIF to give an idea of what we are going to build. Note that we are going to implement this project using the Kotlin language."
},
{
"code": null,
"e": 25393,
"s": 25364,
"text": "Step 1: Create a new Project"
},
{
"code": null,
"e": 25557,
"s": 25393,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 25605,
"s": 25557,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 25721,
"s": 25605,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 25725,
"s": 25721,
"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\"> <!--Create a TextInputLayout and choose the style, for now we are choosing the OutlinedBox ExposedDropdownMenu --> <com.google.android.material.textfield.TextInputLayout style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <!-- Inside text input layout add an auto complete text view and make its input type to none--> <AutoCompleteTextView android:id=\"@+id/autoCompleteTextView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:inputType=\"none\" android:text=\"Choose Programming language\" /> </com.google.android.material.textfield.TextInputLayout> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 27227,
"s": 25725,
"text": null
},
{
"code": null,
"e": 27335,
"s": 27227,
"text": "Step 3: Add string array items to the string.xml file. We will use this data to inflate the drop-down items"
},
{
"code": null,
"e": 27339,
"s": 27335,
"text": "XML"
},
{
"code": "<string-array name=\"programming_languages\"> <item>Java</item> <item>Kotlin</item> <item>Python</item> <item>CPP</item></string-array>",
"e": 27493,
"s": 27339,
"text": null
},
{
"code": null,
"e": 27563,
"s": 27493,
"text": "Step 4: Create a new layout file and name it a dropdown_item.xml file"
},
{
"code": null,
"e": 27758,
"s": 27563,
"text": "Go to the dropdown_item.xml file and refer to the following code. Below is the code for the dropdown_item.xml file. It is the single-text view which we will use as a single item of the dropdown."
},
{
"code": null,
"e": 27762,
"s": 27758,
"text": "XML"
},
{
"code": "<TextView xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:textColor=\"@color/black\" android:textStyle=\"bold\" android:padding=\"14dp\" android:layout_height=\"wrap_content\" android:text=\"TextView\" />",
"e": 28064,
"s": 27762,
"text": null
},
{
"code": null,
"e": 28101,
"s": 28064,
"text": "Step 5: Working with MainActivity.kt"
},
{
"code": null,
"e": 28287,
"s": 28101,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 28294,
"s": 28287,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.ArrayAdapterimport android.widget.AutoCompleteTextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get reference to the string array that we just created val languages = resources.getStringArray(R.array.programming_languages) // create an array adapter and pass the required parameter // in our case pass the context, drop down layout , and array. val arrayAdapter = ArrayAdapter(this, R.layout.dropdown_menu, languages) // get reference to the autocomplete text view val autocompleteTV = findViewById<AutoCompleteTextView>(R.id.autoCompleteTextView) // set adapter to the autocomplete tv to the arrayAdapter autocompleteTV.setAdapter(arrayAdapter) }}",
"e": 29254,
"s": 28294,
"text": null
},
{
"code": null,
"e": 29262,
"s": 29254,
"text": "Output:"
},
{
"code": null,
"e": 29270,
"s": 29262,
"text": "Android"
},
{
"code": null,
"e": 29277,
"s": 29270,
"text": "Kotlin"
},
{
"code": null,
"e": 29285,
"s": 29277,
"text": "Android"
},
{
"code": null,
"e": 29383,
"s": 29285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29441,
"s": 29383,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 29484,
"s": 29441,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29526,
"s": 29484,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29557,
"s": 29526,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 29596,
"s": 29557,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29639,
"s": 29596,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29681,
"s": 29639,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29712,
"s": 29681,
"text": "Android RecyclerView in Kotlin"
}
] |
How to convert a String to an InputStream object in Java?
|
A ByteArrayInputStream is a subclass of InputStream class and it contains an internal buffer that contains bytes that may be read from the stream. We can convert a String to an InputStream object by using the ByteArrayInputStream class. This class constructor takes the string byte array which can be done by calling the getBytes() method of a String class.
import java.io.*;
public class StringToInputStreamTest {
public static void main(String []args) throws Exception {
String str = "Welcome to TutorialsPoint";
InputStream input = getInputStream(str, "UTF-8");
int i;
while ((i = input.read()) > -1) {
System.out.print((char) i);
}
System.out.println();
}
public static InputStream getInputStream(String str, String encoding) throws UnsupportedEncodingException {
return new ByteArrayInputStream(str.getBytes(encoding));
}
}
Welcome to TutorialsPoint
|
[
{
"code": null,
"e": 1420,
"s": 1062,
"text": "A ByteArrayInputStream is a subclass of InputStream class and it contains an internal buffer that contains bytes that may be read from the stream. We can convert a String to an InputStream object by using the ByteArrayInputStream class. This class constructor takes the string byte array which can be done by calling the getBytes() method of a String class."
},
{
"code": null,
"e": 1963,
"s": 1420,
"text": "import java.io.*;\npublic class StringToInputStreamTest {\n public static void main(String []args) throws Exception {\n String str = \"Welcome to TutorialsPoint\";\n InputStream input = getInputStream(str, \"UTF-8\");\n int i;\n while ((i = input.read()) > -1) {\n System.out.print((char) i);\n }\n System.out.println();\n }\n public static InputStream getInputStream(String str, String encoding) throws UnsupportedEncodingException {\n return new ByteArrayInputStream(str.getBytes(encoding));\n }\n}"
},
{
"code": null,
"e": 1989,
"s": 1963,
"text": "Welcome to TutorialsPoint"
}
] |
Solidity - Deploy a Smart Contract for Marks Management System - GeeksforGeeks
|
22 Sep, 2021
Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol.
What are Smart Contracts?
Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum.
Example: In the below example, the aim is to deploy a Smart Contract for Marks Management System by using Solidity. In this contract, the details of every student like student ID, Name, Marks, etc can be added and if one wants to give some bonus marks to students then they can also be added. After building the contract all the details of every student can be retrieved.
Approach:
The first step is to deploy the smart contract using the Remix IDE. After writing the code compile the code. When it is successfully compiled then deploy it. After deploying the contract a deployed Contract is obtained and then add the student details one by one.If bonus marks need to be added then add in the bonusMarks section after that click on stdCount and fetch the student details to call the stdRecords.Add one or more new student details in this Smart Contract by the increment of stdCount.
The first step is to deploy the smart contract using the Remix IDE. After writing the code compile the code. When it is successfully compiled then deploy it. After deploying the contract a deployed Contract is obtained and then add the student details one by one.
If bonus marks need to be added then add in the bonusMarks section after that click on stdCount and fetch the student details to call the stdRecords.
Add one or more new student details in this Smart Contract by the increment of stdCount.
Step 1: Open Remix IDE.
Step 2: Click on File Explorers and select Solidity in the environment and create a new file StudentMarksMangmtSys.sol by clicking on New File section.
Step 3: Build a smart contract that contains all the details of the student with the help of Remix IDE by clicking on the file name.
Solidity
// Solidity program to implement// the above approachpragma solidity >= 0.7.0<0.8.0; // Build the Contractcontract MarksManagmtSys{ // Create a structure for // student details struct Student { int ID; string fName; string lName; int marks; } address owner; int public stdCount = 0; mapping(int => Student) public stdRecords; modifier onlyOwner { require(owner == msg.sender); _; } constructor() { owner=msg.sender; } // Create a function to add // the new records function addNewRecords(int _ID, string memory _fName, string memory _lName, int _marks) public onlyOwner { // Increase the count by 1 stdCount = stdCount + 1; // Fetch the student details // with the help of stdCount stdRecords[stdCount] = Student(_ID, _fName, _lName, _marks); } // Create a function to add bonus marks function bonusMarks(int _bonus) public onlyOwner { stdRecords[stdCount].marks = stdRecords[stdCount].marks + _bonus; }}
Step 4: After building the contract compile it. Select the compiler version before clicking on Compile button.
Step 5: After successful compilation, to deploy the contract, select the Environment JavaScript VM (Berlin) before clicking on the Deploy button.
Step 6: If the contract is successfully deployed then deployed contract is obtained. Open the deployed contract and add the student details and transact it.
Step 7: Add the bonus marks if you want to give them to the student and transact it after that click on the stdCount. One can see the student details after calling the stdRecords by entering the stdCount.
Solidity OOPs-Concepts
Blockchain
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect ReactJS with MetaMask ?
Difference between Public and Private blockchain
Advantages and Disadvantages of Blockchain
How to Set up Ganche with Metamask?
Solidity - While, Do-While, and For Loop
Blockchain Merkle Trees
Hyperledger Fabric in Blockchain
How to Setup Your Own Private Ethereum Network?
Components of Ethereum Network
Solidity - Types
|
[
{
"code": null,
"e": 25931,
"s": 25903,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 26127,
"s": 25931,
"text": "Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol. "
},
{
"code": null,
"e": 26153,
"s": 26127,
"text": "What are Smart Contracts?"
},
{
"code": null,
"e": 26432,
"s": 26153,
"text": "Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum. "
},
{
"code": null,
"e": 26804,
"s": 26432,
"text": "Example: In the below example, the aim is to deploy a Smart Contract for Marks Management System by using Solidity. In this contract, the details of every student like student ID, Name, Marks, etc can be added and if one wants to give some bonus marks to students then they can also be added. After building the contract all the details of every student can be retrieved."
},
{
"code": null,
"e": 26814,
"s": 26804,
"text": "Approach:"
},
{
"code": null,
"e": 27315,
"s": 26814,
"text": "The first step is to deploy the smart contract using the Remix IDE. After writing the code compile the code. When it is successfully compiled then deploy it. After deploying the contract a deployed Contract is obtained and then add the student details one by one.If bonus marks need to be added then add in the bonusMarks section after that click on stdCount and fetch the student details to call the stdRecords.Add one or more new student details in this Smart Contract by the increment of stdCount."
},
{
"code": null,
"e": 27579,
"s": 27315,
"text": "The first step is to deploy the smart contract using the Remix IDE. After writing the code compile the code. When it is successfully compiled then deploy it. After deploying the contract a deployed Contract is obtained and then add the student details one by one."
},
{
"code": null,
"e": 27729,
"s": 27579,
"text": "If bonus marks need to be added then add in the bonusMarks section after that click on stdCount and fetch the student details to call the stdRecords."
},
{
"code": null,
"e": 27818,
"s": 27729,
"text": "Add one or more new student details in this Smart Contract by the increment of stdCount."
},
{
"code": null,
"e": 27842,
"s": 27818,
"text": "Step 1: Open Remix IDE."
},
{
"code": null,
"e": 27994,
"s": 27842,
"text": "Step 2: Click on File Explorers and select Solidity in the environment and create a new file StudentMarksMangmtSys.sol by clicking on New File section."
},
{
"code": null,
"e": 28127,
"s": 27994,
"text": "Step 3: Build a smart contract that contains all the details of the student with the help of Remix IDE by clicking on the file name."
},
{
"code": null,
"e": 28136,
"s": 28127,
"text": "Solidity"
},
{
"code": "// Solidity program to implement// the above approachpragma solidity >= 0.7.0<0.8.0; // Build the Contractcontract MarksManagmtSys{ // Create a structure for // student details struct Student { int ID; string fName; string lName; int marks; } address owner; int public stdCount = 0; mapping(int => Student) public stdRecords; modifier onlyOwner { require(owner == msg.sender); _; } constructor() { owner=msg.sender; } // Create a function to add // the new records function addNewRecords(int _ID, string memory _fName, string memory _lName, int _marks) public onlyOwner { // Increase the count by 1 stdCount = stdCount + 1; // Fetch the student details // with the help of stdCount stdRecords[stdCount] = Student(_ID, _fName, _lName, _marks); } // Create a function to add bonus marks function bonusMarks(int _bonus) public onlyOwner { stdRecords[stdCount].marks = stdRecords[stdCount].marks + _bonus; }}",
"e": 29355,
"s": 28136,
"text": null
},
{
"code": null,
"e": 29467,
"s": 29355,
"text": "Step 4: After building the contract compile it. Select the compiler version before clicking on Compile button. "
},
{
"code": null,
"e": 29613,
"s": 29467,
"text": "Step 5: After successful compilation, to deploy the contract, select the Environment JavaScript VM (Berlin) before clicking on the Deploy button."
},
{
"code": null,
"e": 29770,
"s": 29613,
"text": "Step 6: If the contract is successfully deployed then deployed contract is obtained. Open the deployed contract and add the student details and transact it."
},
{
"code": null,
"e": 29975,
"s": 29770,
"text": "Step 7: Add the bonus marks if you want to give them to the student and transact it after that click on the stdCount. One can see the student details after calling the stdRecords by entering the stdCount."
},
{
"code": null,
"e": 29998,
"s": 29975,
"text": "Solidity OOPs-Concepts"
},
{
"code": null,
"e": 30009,
"s": 29998,
"text": "Blockchain"
},
{
"code": null,
"e": 30107,
"s": 30009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30146,
"s": 30107,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 30195,
"s": 30146,
"text": "Difference between Public and Private blockchain"
},
{
"code": null,
"e": 30238,
"s": 30195,
"text": "Advantages and Disadvantages of Blockchain"
},
{
"code": null,
"e": 30274,
"s": 30238,
"text": "How to Set up Ganche with Metamask?"
},
{
"code": null,
"e": 30315,
"s": 30274,
"text": "Solidity - While, Do-While, and For Loop"
},
{
"code": null,
"e": 30339,
"s": 30315,
"text": "Blockchain Merkle Trees"
},
{
"code": null,
"e": 30372,
"s": 30339,
"text": "Hyperledger Fabric in Blockchain"
},
{
"code": null,
"e": 30420,
"s": 30372,
"text": "How to Setup Your Own Private Ethereum Network?"
},
{
"code": null,
"e": 30451,
"s": 30420,
"text": "Components of Ethereum Network"
}
] |
Remove Axis Labels using ggplot2 in R - GeeksforGeeks
|
06 Jun, 2021
In this article, we are going to see how to remove axis labels of the ggplot2 plot in the R programming language.
We will use theme() function from ggplot2 package. In this approach to remove the ggplot2 plot labels, the user first has to import and load the ggplot2 package in the R console, which is a prerequisite for this approach, then the user has to call the theme() function which is the function of the ggplot2 package and further needs to pass the element_blank() as its parameters, which will be helping to remove the ggplot2 plots labels as blank in R programming language.
theme() function: Use of this function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look.
In this example, we will be showing that how the plot looks without removing its labels.
R
library("ggplot2") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(5,4,3,2,1))gfg_plot <- ggplot(gfg_data, aes(x,y)) + geom_point()gfg_plot
Output:
Example 1: In this example, we will be removing the label of the ggplot2 scatter plot of five data point using the theme() function of the ggplot2 package in the R programming language.
R
library("ggplot2") gfg_data<-data.frame(x = c(1,2,3,4,5), y = c(5,4,3,2,1))gfg_plot <- ggplot(gfg_data, aes(x,y)) + geom_point()gfg_plot + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())
Output:
Example 2: In this example, we will be removing the labels of the ggplot2 bar plot using the theme() function from the ggplot2 package in the R programming language.
R
library("ggplot2") gfg_data<-data.frame(x = c(1,2,3,4,5), y = c(5,4,3,2,1))p<-ggplot(data=gfg_data, aes(x, y)) + geom_bar(stat="identity")p+ theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 26601,
"s": 26487,
"text": "In this article, we are going to see how to remove axis labels of the ggplot2 plot in the R programming language."
},
{
"code": null,
"e": 27073,
"s": 26601,
"text": "We will use theme() function from ggplot2 package. In this approach to remove the ggplot2 plot labels, the user first has to import and load the ggplot2 package in the R console, which is a prerequisite for this approach, then the user has to call the theme() function which is the function of the ggplot2 package and further needs to pass the element_blank() as its parameters, which will be helping to remove the ggplot2 plots labels as blank in R programming language."
},
{
"code": null,
"e": 27321,
"s": 27073,
"text": "theme() function: Use of this function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look."
},
{
"code": null,
"e": 27410,
"s": 27321,
"text": "In this example, we will be showing that how the plot looks without removing its labels."
},
{
"code": null,
"e": 27412,
"s": 27410,
"text": "R"
},
{
"code": "library(\"ggplot2\") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(5,4,3,2,1))gfg_plot <- ggplot(gfg_data, aes(x,y)) + geom_point()gfg_plot",
"e": 27578,
"s": 27412,
"text": null
},
{
"code": null,
"e": 27586,
"s": 27578,
"text": "Output:"
},
{
"code": null,
"e": 27773,
"s": 27586,
"text": "Example 1: In this example, we will be removing the label of the ggplot2 scatter plot of five data point using the theme() function of the ggplot2 package in the R programming language."
},
{
"code": null,
"e": 27775,
"s": 27773,
"text": "R"
},
{
"code": "library(\"ggplot2\") gfg_data<-data.frame(x = c(1,2,3,4,5), y = c(5,4,3,2,1))gfg_plot <- ggplot(gfg_data, aes(x,y)) + geom_point()gfg_plot + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())",
"e": 28093,
"s": 27775,
"text": null
},
{
"code": null,
"e": 28101,
"s": 28093,
"text": "Output:"
},
{
"code": null,
"e": 28267,
"s": 28101,
"text": "Example 2: In this example, we will be removing the labels of the ggplot2 bar plot using the theme() function from the ggplot2 package in the R programming language."
},
{
"code": null,
"e": 28269,
"s": 28267,
"text": "R"
},
{
"code": "library(\"ggplot2\") gfg_data<-data.frame(x = c(1,2,3,4,5), y = c(5,4,3,2,1))p<-ggplot(data=gfg_data, aes(x, y)) + geom_bar(stat=\"identity\")p+ theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())",
"e": 28587,
"s": 28269,
"text": null
},
{
"code": null,
"e": 28595,
"s": 28587,
"text": "Output:"
},
{
"code": null,
"e": 28602,
"s": 28595,
"text": "Picked"
},
{
"code": null,
"e": 28611,
"s": 28602,
"text": "R-ggplot"
},
{
"code": null,
"e": 28622,
"s": 28611,
"text": "R Language"
},
{
"code": null,
"e": 28720,
"s": 28622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28772,
"s": 28720,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28807,
"s": 28772,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28845,
"s": 28807,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28903,
"s": 28845,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28946,
"s": 28903,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28995,
"s": 28946,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29032,
"s": 28995,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29058,
"s": 29032,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 29075,
"s": 29058,
"text": "R - if statement"
}
] |
Carpet Plots using Plotly in Python - GeeksforGeeks
|
01 Oct, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library.
A carpet plot is any of a few different specific types of plot. A carpet plot is one that shows the interaction between two or more independent variables and one or more dependent variables in a two-dimensional plot. The carpet plot distinguishes itself from other plots as carpet plot can be used to more accurately interpolate data points. It can be created using the Carpet() method of graph_objects class.
Syntax: plotly.graph_objects.Carpet(a=None,b=None,carpet=None, x=None, y=None)
Parameters:
a: An array containing values of the first parameter value
b: An array containing values of the first parameter value
x: A two dimensional array of x coordinates at each carpet point. If ommitted, the plot is a cheater plot and the xaxis is hidden by default.
y: A two dimensional array of y coordinates at each carpet point.
carpet: An identifier for this carpet, so that scattercarpet and contourcarpet traces can specify a carpet plot on which they lie
Example:
Python3
import plotly.graph_objects as go fig = go.Figure(go.Carpet( y = [1, 2, 3, 4, 5, 6])) fig.show()
Output:
A and B attributes should be used to save the parameter values.
Example:
Python3
import plotly.graph_objects as go fig = go.Figure(go.Carpet( a = [1, 2, 3, 1, 2, 3], b = [4, 5, 6, 4, 5, 6], y = [1, 2, 3, 4, 5, 6])) fig.show()
Output:
aaxis and baxis lists are used to set A and B axis respectively.
Example 1:
Python3
import plotly.graph_objects as go fig = go.Figure(go.Carpet( a=[1, 2, 3, 4, 5, 6], b=[6, 5, 4, 3, 2, 1], y=[1, 2, 3, 4, 5, 6], aaxis=dict( tickprefix='F = ', ticksuffix='N', smoothing=0.2, minorgridcount=10, ), baxis=dict( tickprefix='P = ', ticksuffix='pa', smoothing=0.4, minorgridcount=9, ))) fig.show()
Output:
Example 2: Styling A and B axis
Python3
import plotly.graph_objects as go fig = go.Figure(go.Carpet( a=[1, 2, 3, 4, 5, 6], b=[6, 5, 4, 3, 2, 1], y=[1, 2, 3, 4, 5, 6], aaxis=dict( tickprefix='F = ', ticksuffix='N', smoothing=0.2, minorgridcount=10, ), baxis=dict( tickprefix='P = ', ticksuffix='pa', smoothing=0.4, minorgridcount=9, ))) fig.update_layout( plot_bgcolor='black', paper_bgcolor='black', xaxis=dict( showgrid=False, showticklabels=False ), yaxis=dict( showgrid=False, showticklabels=False )) fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25841,
"s": 25537,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library."
},
{
"code": null,
"e": 26251,
"s": 25841,
"text": "A carpet plot is any of a few different specific types of plot. A carpet plot is one that shows the interaction between two or more independent variables and one or more dependent variables in a two-dimensional plot. The carpet plot distinguishes itself from other plots as carpet plot can be used to more accurately interpolate data points. It can be created using the Carpet() method of graph_objects class."
},
{
"code": null,
"e": 26330,
"s": 26251,
"text": "Syntax: plotly.graph_objects.Carpet(a=None,b=None,carpet=None, x=None, y=None)"
},
{
"code": null,
"e": 26342,
"s": 26330,
"text": "Parameters:"
},
{
"code": null,
"e": 26401,
"s": 26342,
"text": "a: An array containing values of the first parameter value"
},
{
"code": null,
"e": 26460,
"s": 26401,
"text": "b: An array containing values of the first parameter value"
},
{
"code": null,
"e": 26602,
"s": 26460,
"text": "x: A two dimensional array of x coordinates at each carpet point. If ommitted, the plot is a cheater plot and the xaxis is hidden by default."
},
{
"code": null,
"e": 26668,
"s": 26602,
"text": "y: A two dimensional array of y coordinates at each carpet point."
},
{
"code": null,
"e": 26798,
"s": 26668,
"text": "carpet: An identifier for this carpet, so that scattercarpet and contourcarpet traces can specify a carpet plot on which they lie"
},
{
"code": null,
"e": 26807,
"s": 26798,
"text": "Example:"
},
{
"code": null,
"e": 26815,
"s": 26807,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure(go.Carpet( y = [1, 2, 3, 4, 5, 6])) fig.show()",
"e": 26917,
"s": 26815,
"text": null
},
{
"code": null,
"e": 26925,
"s": 26917,
"text": "Output:"
},
{
"code": null,
"e": 26989,
"s": 26925,
"text": "A and B attributes should be used to save the parameter values."
},
{
"code": null,
"e": 26998,
"s": 26989,
"text": "Example:"
},
{
"code": null,
"e": 27006,
"s": 26998,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure(go.Carpet( a = [1, 2, 3, 1, 2, 3], b = [4, 5, 6, 4, 5, 6], y = [1, 2, 3, 4, 5, 6])) fig.show()",
"e": 27162,
"s": 27006,
"text": null
},
{
"code": null,
"e": 27170,
"s": 27162,
"text": "Output:"
},
{
"code": null,
"e": 27235,
"s": 27170,
"text": "aaxis and baxis lists are used to set A and B axis respectively."
},
{
"code": null,
"e": 27246,
"s": 27235,
"text": "Example 1:"
},
{
"code": null,
"e": 27254,
"s": 27246,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure(go.Carpet( a=[1, 2, 3, 4, 5, 6], b=[6, 5, 4, 3, 2, 1], y=[1, 2, 3, 4, 5, 6], aaxis=dict( tickprefix='F = ', ticksuffix='N', smoothing=0.2, minorgridcount=10, ), baxis=dict( tickprefix='P = ', ticksuffix='pa', smoothing=0.4, minorgridcount=9, ))) fig.show()",
"e": 27642,
"s": 27254,
"text": null
},
{
"code": null,
"e": 27650,
"s": 27642,
"text": "Output:"
},
{
"code": null,
"e": 27682,
"s": 27650,
"text": "Example 2: Styling A and B axis"
},
{
"code": null,
"e": 27690,
"s": 27682,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure(go.Carpet( a=[1, 2, 3, 4, 5, 6], b=[6, 5, 4, 3, 2, 1], y=[1, 2, 3, 4, 5, 6], aaxis=dict( tickprefix='F = ', ticksuffix='N', smoothing=0.2, minorgridcount=10, ), baxis=dict( tickprefix='P = ', ticksuffix='pa', smoothing=0.4, minorgridcount=9, ))) fig.update_layout( plot_bgcolor='black', paper_bgcolor='black', xaxis=dict( showgrid=False, showticklabels=False ), yaxis=dict( showgrid=False, showticklabels=False )) fig.show()",
"e": 28293,
"s": 27690,
"text": null
},
{
"code": null,
"e": 28301,
"s": 28293,
"text": "Output:"
},
{
"code": null,
"e": 28315,
"s": 28301,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28322,
"s": 28315,
"text": "Python"
},
{
"code": null,
"e": 28420,
"s": 28322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28452,
"s": 28420,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28494,
"s": 28452,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28536,
"s": 28494,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28563,
"s": 28536,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28619,
"s": 28563,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28641,
"s": 28619,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28680,
"s": 28641,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28711,
"s": 28680,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28740,
"s": 28711,
"text": "Create a directory in Python"
}
] |
Julia Constructors - GeeksforGeeks
|
26 Mar, 2020
Constructors in Julia are functions that are used to create objects. They are specifically used to create instances of objects of Composite Types. A composite type is a collection of named fields, which can also be treated as single values. Julia allows creating type objects as constructors when they are assigned to a set of argument values passed in the form of a function. A constructor works on the basic data structure known as structure or Types in Julia. A type is created with the use of a predefined keyword ‘struct‘.
struct Structure_name
Field1
Field2
end
constructor1 = Structure_name(value1, value2)
constructor1.Field1
constructor1.Field2
Example:
# Creating a structurestruct Geeks # Defining Fields x yend # Creating a constructorGeek_constructor = Geeks(10, 20) # Creating constructor objectsGeek_constructor.xGeek_constructor.y
In the above code, when the constructor is created with a function by passing argument values, those values are automatically instantiated to the Fields of the structure individually at the time of object creation.
Julia allows creating two types of constructors based on their behavior. These are:
Outer constructor
Inner constructor
Outer Constructor –Outer constructor methods are defined outside of the block of type declaration. An outer constructor is just like any other function in Julia, its functionality depends on all the methods that are defined inside of it. A new functionality can be added to a constructor by simply defining a new method.Example:
# Creating a structurestruct Geeks x yend # Creating a constructor with# same value for both fieldsGeek_constructor(x) = Geeks(x, x) # Passing single argumentGeek_constructor(10)
As in the above code, the constructor is created with one value and that single value is assigned to both the fields.Hence, the constructor methods created like normal methods are called outer constructors. An outer constructor method can only create new instances by calling other constructors.
Inner Constructor –Unlike the outer constructor method in which the constructor can be defined anywhere in the source code just like any normal function, inner constructors can only be defined inside of the block of the type declaration. It is just like the outer constructor method except that it can also access a special pre-defined function termed as ‘new‘. Defining a constructor within the type block will restrict the object creation to be bound as per the condition defined during the constructor creation.
Example:
# Defining typestruct Geeks # Field x::Real # Creating Inner Constructor Geeks(x) = typeof(x) != Int64 ? error("Integer value not found") : new(x)end # Object CreationGeeks(10)Geeks(10.5)
A parametric constructor type is one in which the datatype of the Structure is pre-defined at the time of Type declaration. The fields of this structure are implied with a datatype at the time of Type declaration. In a parametric constructor, the constructor calls in which the parameter type is explicitly defined are converted to the implied field types. Hence, the type implied to the parameters at the time of function call must agree otherwise an error will be raised, but any pair of values with matching types can be passed to the constructor.
Example:
# Defining typestruct Geeks{T <: Real} # Fields x::T y::Tend # Creating Outer constructorGeeks(x::T, y::T) where {T<:Real} = Geeks{T}(x, y); # Constructor callingGeeks(10, 20)Geeks(10, 20.5)
Julia-functions
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
Reshaping array dimensions in Julia | Array reshape() Method
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method
|
[
{
"code": null,
"e": 25521,
"s": 25493,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 26049,
"s": 25521,
"text": "Constructors in Julia are functions that are used to create objects. They are specifically used to create instances of objects of Composite Types. A composite type is a collection of named fields, which can also be treated as single values. Julia allows creating type objects as constructors when they are assigned to a set of argument values passed in the form of a function. A constructor works on the basic data structure known as structure or Types in Julia. A type is created with the use of a predefined keyword ‘struct‘."
},
{
"code": null,
"e": 26186,
"s": 26049,
"text": "struct Structure_name\n Field1\n Field2\nend\n\nconstructor1 = Structure_name(value1, value2)\n\nconstructor1.Field1\nconstructor1.Field2\n"
},
{
"code": null,
"e": 26195,
"s": 26186,
"text": "Example:"
},
{
"code": "# Creating a structurestruct Geeks # Defining Fields x yend # Creating a constructorGeek_constructor = Geeks(10, 20) # Creating constructor objectsGeek_constructor.xGeek_constructor.y",
"e": 26396,
"s": 26195,
"text": null
},
{
"code": null,
"e": 26611,
"s": 26396,
"text": "In the above code, when the constructor is created with a function by passing argument values, those values are automatically instantiated to the Fields of the structure individually at the time of object creation."
},
{
"code": null,
"e": 26695,
"s": 26611,
"text": "Julia allows creating two types of constructors based on their behavior. These are:"
},
{
"code": null,
"e": 26713,
"s": 26695,
"text": "Outer constructor"
},
{
"code": null,
"e": 26731,
"s": 26713,
"text": "Inner constructor"
},
{
"code": null,
"e": 27060,
"s": 26731,
"text": "Outer Constructor –Outer constructor methods are defined outside of the block of type declaration. An outer constructor is just like any other function in Julia, its functionality depends on all the methods that are defined inside of it. A new functionality can be added to a constructor by simply defining a new method.Example:"
},
{
"code": "# Creating a structurestruct Geeks x yend # Creating a constructor with# same value for both fieldsGeek_constructor(x) = Geeks(x, x) # Passing single argumentGeek_constructor(10)",
"e": 27247,
"s": 27060,
"text": null
},
{
"code": null,
"e": 27543,
"s": 27247,
"text": "As in the above code, the constructor is created with one value and that single value is assigned to both the fields.Hence, the constructor methods created like normal methods are called outer constructors. An outer constructor method can only create new instances by calling other constructors."
},
{
"code": null,
"e": 28058,
"s": 27543,
"text": "Inner Constructor –Unlike the outer constructor method in which the constructor can be defined anywhere in the source code just like any normal function, inner constructors can only be defined inside of the block of the type declaration. It is just like the outer constructor method except that it can also access a special pre-defined function termed as ‘new‘. Defining a constructor within the type block will restrict the object creation to be bound as per the condition defined during the constructor creation."
},
{
"code": null,
"e": 28067,
"s": 28058,
"text": "Example:"
},
{
"code": "# Defining typestruct Geeks # Field x::Real # Creating Inner Constructor Geeks(x) = typeof(x) != Int64 ? error(\"Integer value not found\") : new(x)end # Object CreationGeeks(10)Geeks(10.5)",
"e": 28276,
"s": 28067,
"text": null
},
{
"code": null,
"e": 28827,
"s": 28276,
"text": "A parametric constructor type is one in which the datatype of the Structure is pre-defined at the time of Type declaration. The fields of this structure are implied with a datatype at the time of Type declaration. In a parametric constructor, the constructor calls in which the parameter type is explicitly defined are converted to the implied field types. Hence, the type implied to the parameters at the time of function call must agree otherwise an error will be raised, but any pair of values with matching types can be passed to the constructor."
},
{
"code": null,
"e": 28836,
"s": 28827,
"text": "Example:"
},
{
"code": "# Defining typestruct Geeks{T <: Real} # Fields x::T y::Tend # Creating Outer constructorGeeks(x::T, y::T) where {T<:Real} = Geeks{T}(x, y); # Constructor callingGeeks(10, 20)Geeks(10, 20.5)",
"e": 29040,
"s": 28836,
"text": null
},
{
"code": null,
"e": 29056,
"s": 29040,
"text": "Julia-functions"
},
{
"code": null,
"e": 29062,
"s": 29056,
"text": "Julia"
},
{
"code": null,
"e": 29160,
"s": 29062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29177,
"s": 29160,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 29237,
"s": 29177,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 29310,
"s": 29237,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 29344,
"s": 29310,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 29375,
"s": 29344,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 29406,
"s": 29375,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 29471,
"s": 29406,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 29532,
"s": 29471,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 29552,
"s": 29532,
"text": "while loop in Julia"
}
] |
JavaScript Course | Interaction With User - GeeksforGeeks
|
29 Apr, 2019
Previous article: JavaScript Course | Practice Quiz-1Javascript allows us the privilege with which we can interact with the user and respond accordingly. It includes several user-interface functions which help in the interaction. Let’s take a look at them one by one.
alertsimply creates an alert box which may or may not have specified content inside it, but it always comes with the ‘OK’ button. It simply shows a message and pauses the execution of the script until you press the ‘OK’ button. The mini-window that pops-up is called the ‘modal window’.alert('text');
Example:// alert example<script> alert('HI there'); // with specified content alert(); // without any specified content</script>Output:It can be used for debugging or simply for popping something to the user.
alert('text');
Example:
// alert example<script> alert('HI there'); // with specified content alert(); // without any specified content</script>
Output:It can be used for debugging or simply for popping something to the user.
promptPrompt is another user-interface function which normally contains two arguments.prompt('text', default value);
The text is basically what you want to show the user and the default value argument is optional though it acts like a placeholder inside a text field. It is the most used interface as with it you can ask the user to input something and then use that input to build something.Example:(with default parameter)<script>// prompt examplelet age = prompt('How old are you?', 50); alert(`You are ${age} years old!`); </script>Output:You can enter anything and it will print that, it doesn’t necessarily have to be a number. Without the default value, you have to enter something in the text-field otherwise it will print a blank space simply.Example:<script>// prompt examplelet age = prompt('How old are you?'); alert(`You are ${age} years old!`); </script>Output:
prompt('text', default value);
The text is basically what you want to show the user and the default value argument is optional though it acts like a placeholder inside a text field. It is the most used interface as with it you can ask the user to input something and then use that input to build something.Example:(with default parameter)
<script>// prompt examplelet age = prompt('How old are you?', 50); alert(`You are ${age} years old!`); </script>
Output:You can enter anything and it will print that, it doesn’t necessarily have to be a number. Without the default value, you have to enter something in the text-field otherwise it will print a blank space simply.Example:
<script>// prompt examplelet age = prompt('How old are you?'); alert(`You are ${age} years old!`); </script>
Output:
confirmThe confirm function basically outputs a modal window with a question and two button ‘OK’ and ‘CANCEL’.confirm('question');
Example:<script>// confirm example let isHappy = confirm('Are you Happy?');alert(`You are ${isHappy}`); </script>Output:It will print true or false based on your choice of clicking the ‘OK’ button or ‘CANCEL’ button respectively.
confirm('question');
Example:
<script>// confirm example let isHappy = confirm('Are you Happy?');alert(`You are ${isHappy}`); </script>
Output:It will print true or false based on your choice of clicking the ‘OK’ button or ‘CANCEL’ button respectively.
Next article: JavaScript Course | Logical Operators in JavaScript
JavaScript-Course
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n29 Apr, 2019"
},
{
"code": null,
"e": 26813,
"s": 26545,
"text": "Previous article: JavaScript Course | Practice Quiz-1Javascript allows us the privilege with which we can interact with the user and respond accordingly. It includes several user-interface functions which help in the interaction. Let’s take a look at them one by one."
},
{
"code": null,
"e": 27323,
"s": 26813,
"text": "alertsimply creates an alert box which may or may not have specified content inside it, but it always comes with the ‘OK’ button. It simply shows a message and pauses the execution of the script until you press the ‘OK’ button. The mini-window that pops-up is called the ‘modal window’.alert('text');\nExample:// alert example<script> alert('HI there'); // with specified content alert(); // without any specified content</script>Output:It can be used for debugging or simply for popping something to the user."
},
{
"code": null,
"e": 27339,
"s": 27323,
"text": "alert('text');\n"
},
{
"code": null,
"e": 27348,
"s": 27339,
"text": "Example:"
},
{
"code": "// alert example<script> alert('HI there'); // with specified content alert(); // without any specified content</script>",
"e": 27469,
"s": 27348,
"text": null
},
{
"code": null,
"e": 27550,
"s": 27469,
"text": "Output:It can be used for debugging or simply for popping something to the user."
},
{
"code": null,
"e": 28428,
"s": 27550,
"text": "promptPrompt is another user-interface function which normally contains two arguments.prompt('text', default value);\nThe text is basically what you want to show the user and the default value argument is optional though it acts like a placeholder inside a text field. It is the most used interface as with it you can ask the user to input something and then use that input to build something.Example:(with default parameter)<script>// prompt examplelet age = prompt('How old are you?', 50); alert(`You are ${age} years old!`); </script>Output:You can enter anything and it will print that, it doesn’t necessarily have to be a number. Without the default value, you have to enter something in the text-field otherwise it will print a blank space simply.Example:<script>// prompt examplelet age = prompt('How old are you?'); alert(`You are ${age} years old!`); </script>Output:"
},
{
"code": null,
"e": 28460,
"s": 28428,
"text": "prompt('text', default value);\n"
},
{
"code": null,
"e": 28768,
"s": 28460,
"text": "The text is basically what you want to show the user and the default value argument is optional though it acts like a placeholder inside a text field. It is the most used interface as with it you can ask the user to input something and then use that input to build something.Example:(with default parameter)"
},
{
"code": "<script>// prompt examplelet age = prompt('How old are you?', 50); alert(`You are ${age} years old!`); </script>",
"e": 28882,
"s": 28768,
"text": null
},
{
"code": null,
"e": 29107,
"s": 28882,
"text": "Output:You can enter anything and it will print that, it doesn’t necessarily have to be a number. Without the default value, you have to enter something in the text-field otherwise it will print a blank space simply.Example:"
},
{
"code": "<script>// prompt examplelet age = prompt('How old are you?'); alert(`You are ${age} years old!`); </script>",
"e": 29217,
"s": 29107,
"text": null
},
{
"code": null,
"e": 29225,
"s": 29217,
"text": "Output:"
},
{
"code": null,
"e": 29587,
"s": 29225,
"text": "confirmThe confirm function basically outputs a modal window with a question and two button ‘OK’ and ‘CANCEL’.confirm('question');\nExample:<script>// confirm example let isHappy = confirm('Are you Happy?');alert(`You are ${isHappy}`); </script>Output:It will print true or false based on your choice of clicking the ‘OK’ button or ‘CANCEL’ button respectively."
},
{
"code": null,
"e": 29609,
"s": 29587,
"text": "confirm('question');\n"
},
{
"code": null,
"e": 29618,
"s": 29609,
"text": "Example:"
},
{
"code": "<script>// confirm example let isHappy = confirm('Are you Happy?');alert(`You are ${isHappy}`); </script>",
"e": 29725,
"s": 29618,
"text": null
},
{
"code": null,
"e": 29842,
"s": 29725,
"text": "Output:It will print true or false based on your choice of clicking the ‘OK’ button or ‘CANCEL’ button respectively."
},
{
"code": null,
"e": 29908,
"s": 29842,
"text": "Next article: JavaScript Course | Logical Operators in JavaScript"
},
{
"code": null,
"e": 29926,
"s": 29908,
"text": "JavaScript-Course"
},
{
"code": null,
"e": 29937,
"s": 29926,
"text": "JavaScript"
},
{
"code": null,
"e": 29954,
"s": 29937,
"text": "Web Technologies"
},
{
"code": null,
"e": 30052,
"s": 29954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30092,
"s": 30052,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30153,
"s": 30092,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30194,
"s": 30153,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30216,
"s": 30194,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30270,
"s": 30216,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30310,
"s": 30270,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30343,
"s": 30310,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30386,
"s": 30343,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30436,
"s": 30386,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Reversing a Queue using another Queue - GeeksforGeeks
|
28 Dec, 2021
Given a queue. The task is to reverse the queue using another another empty queue.
Examples:
Input: queue[] = {1, 2, 3, 4, 5}
Output: 5 4 3 2 1
Input: queue[] = {10, 20, 30, 40}
Output: 40 30 20 10
Approach:
Given a queue and an empty queue.
The last element of the queue should be the first element of the new queue.
To get the last element there is a need to pop the queue one by one and add it to the end of the queue, size – 1 times.
So after that, we will get the last element in front of the queue. Now pop that element out and add it to the new queue. Repeat the steps s – 1 times where s is the original size of the queue.
Below is the implementation of the approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the reversed queuequeue<int> reverse(queue<int> q){ // Size of queue int s = q.size(); // Second queue queue<int> ans; for (int i = 0; i < s; i++) { // Get the last element to the // front of queue for (int j = 0; j < q.size() - 1; j++) { int x = q.front(); q.pop(); q.push(x); } // Get the last element and // add it to the new queue ans.push(q.front()); q.pop(); } return ans;} // Driver Codeint main(){ queue<int> q; // Insert elements q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); q = reverse(q); // Print the queue while (!q.empty()) { cout << q.front() << " "; q.pop(); } return 0;}
// Java implementation of the above approachimport java.util.*;class GFG{ // Function to return the reversed queuestatic Queue<Integer> reverse(Queue<Integer> q){ // Size of queue int s = q.size(); // Second queue Queue<Integer> ans = new LinkedList<>(); for (int i = 0; i < s; i++) { // Get the last element to the // front of queue for (int j = 0; j < q.size() - 1; j++) { int x = q.peek(); q.remove(); q.add(x); } // Get the last element and // add it to the new queue ans.add(q.peek()); q.remove(); } return ans;} // Driver Codepublic static void main(String[] args){ Queue<Integer> q = new LinkedList<>(); // Insert elements q.add(1); q.add(2); q.add(3); q.add(4); q.add(5); q = reverse(q); // Print the queue while (!q.isEmpty()) { System.out.print(q.peek() + " "); q.remove(); } }} // This code is contributed by Princi Singh
# Python3 implementation of the above approachfrom collections import deque # Function to return the reversed queuedef reverse(q): # Size of queue s = len(q) # Second queue ans = deque() for i in range(s): # Get the last element to the # front of queue for j in range(s - 1): x = q.popleft() q.appendleft(x) # Get the last element and # add it to the new queue ans.appendleft(q.popleft()) return ans # Driver Codeq = deque() # Insert elementsq.append(1)q.append(2)q.append(3)q.append(4)q.append(5) q = reverse(q) # Print the queuewhile (len(q) > 0): print(q.popleft(), end = " ") # This code is contributed by Mohit Kumar
// C# Program to print the given patternusing System;using System.Collections.Generic; class GFG{ // Function to return the reversed queuestatic Queue<int> reverse(Queue<int> q){ // Size of queue int s = q.Count; // Second queue Queue<int> ans = new Queue<int>(); for (int i = 0; i < s; i++) { // Get the last element to the // front of queue for (int j = 0; j < q.Count - 1; j++) { int x = q.Peek(); q.Dequeue(); q.Enqueue(x); } // Get the last element and // add it to the new queue ans.Enqueue(q.Peek()); q.Dequeue(); } return ans;} // Driver Codepublic static void Main(String[] args){ Queue<int> q = new Queue<int>(); // Insert elements q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(4); q.Enqueue(5); q = reverse(q); // Print the queue while (q.Count!=0) { Console.Write(q.Peek() + " "); q.Dequeue(); } }} // This code is contributed by Princi Singh
<script> // Javascript implementation of the above approach // Function to return the reversed queuefunction reverse(q){ // Size of queue let s = q.length; // Second queue let ans = []; for(let i = 0; i < s; i++) { // Get the last element to the // front of queue for(let j = 0; j < q.length - 1; j++) { let x = q.shift(); q.push(x); } // Get the last element and // add it to the new queue ans.push(q[0]); q.shift(); } return ans;} // Driver Codelet q = []; // Insert elementsq.push(1);q.push(2);q.push(3);q.push(4);q.push(5); q = reverse(q); // Print the queuewhile (q.length != 0){ document.write(q[0] + " "); q.shift();} // This code is contributed by patel2127 </script>
5 4 3 2 1
princi singh
mohit kumar 29
patel2127
rkbhola5
germanshephered48
Data Structures
Java-Queue-Programs
Competitive Programming
Queue
Data Structures
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
5 Best Books for Competitive Programming
5 Best Languages for Competitive Programming
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 26357,
"s": 26329,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 26440,
"s": 26357,
"text": "Given a queue. The task is to reverse the queue using another another empty queue."
},
{
"code": null,
"e": 26451,
"s": 26440,
"text": "Examples: "
},
{
"code": null,
"e": 26557,
"s": 26451,
"text": "Input: queue[] = {1, 2, 3, 4, 5}\nOutput: 5 4 3 2 1\n\nInput: queue[] = {10, 20, 30, 40}\nOutput: 40 30 20 10"
},
{
"code": null,
"e": 26569,
"s": 26557,
"text": "Approach: "
},
{
"code": null,
"e": 26603,
"s": 26569,
"text": "Given a queue and an empty queue."
},
{
"code": null,
"e": 26679,
"s": 26603,
"text": "The last element of the queue should be the first element of the new queue."
},
{
"code": null,
"e": 26799,
"s": 26679,
"text": "To get the last element there is a need to pop the queue one by one and add it to the end of the queue, size – 1 times."
},
{
"code": null,
"e": 26992,
"s": 26799,
"text": "So after that, we will get the last element in front of the queue. Now pop that element out and add it to the new queue. Repeat the steps s – 1 times where s is the original size of the queue."
},
{
"code": null,
"e": 27038,
"s": 26992,
"text": "Below is the implementation of the approach: "
},
{
"code": null,
"e": 27042,
"s": 27038,
"text": "C++"
},
{
"code": null,
"e": 27047,
"s": 27042,
"text": "Java"
},
{
"code": null,
"e": 27055,
"s": 27047,
"text": "Python3"
},
{
"code": null,
"e": 27058,
"s": 27055,
"text": "C#"
},
{
"code": null,
"e": 27069,
"s": 27058,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the reversed queuequeue<int> reverse(queue<int> q){ // Size of queue int s = q.size(); // Second queue queue<int> ans; for (int i = 0; i < s; i++) { // Get the last element to the // front of queue for (int j = 0; j < q.size() - 1; j++) { int x = q.front(); q.pop(); q.push(x); } // Get the last element and // add it to the new queue ans.push(q.front()); q.pop(); } return ans;} // Driver Codeint main(){ queue<int> q; // Insert elements q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); q = reverse(q); // Print the queue while (!q.empty()) { cout << q.front() << \" \"; q.pop(); } return 0;}",
"e": 27945,
"s": 27069,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*;class GFG{ // Function to return the reversed queuestatic Queue<Integer> reverse(Queue<Integer> q){ // Size of queue int s = q.size(); // Second queue Queue<Integer> ans = new LinkedList<>(); for (int i = 0; i < s; i++) { // Get the last element to the // front of queue for (int j = 0; j < q.size() - 1; j++) { int x = q.peek(); q.remove(); q.add(x); } // Get the last element and // add it to the new queue ans.add(q.peek()); q.remove(); } return ans;} // Driver Codepublic static void main(String[] args){ Queue<Integer> q = new LinkedList<>(); // Insert elements q.add(1); q.add(2); q.add(3); q.add(4); q.add(5); q = reverse(q); // Print the queue while (!q.isEmpty()) { System.out.print(q.peek() + \" \"); q.remove(); } }} // This code is contributed by Princi Singh",
"e": 28958,
"s": 27945,
"text": null
},
{
"code": "# Python3 implementation of the above approachfrom collections import deque # Function to return the reversed queuedef reverse(q): # Size of queue s = len(q) # Second queue ans = deque() for i in range(s): # Get the last element to the # front of queue for j in range(s - 1): x = q.popleft() q.appendleft(x) # Get the last element and # add it to the new queue ans.appendleft(q.popleft()) return ans # Driver Codeq = deque() # Insert elementsq.append(1)q.append(2)q.append(3)q.append(4)q.append(5) q = reverse(q) # Print the queuewhile (len(q) > 0): print(q.popleft(), end = \" \") # This code is contributed by Mohit Kumar",
"e": 29674,
"s": 28958,
"text": null
},
{
"code": "// C# Program to print the given patternusing System;using System.Collections.Generic; class GFG{ // Function to return the reversed queuestatic Queue<int> reverse(Queue<int> q){ // Size of queue int s = q.Count; // Second queue Queue<int> ans = new Queue<int>(); for (int i = 0; i < s; i++) { // Get the last element to the // front of queue for (int j = 0; j < q.Count - 1; j++) { int x = q.Peek(); q.Dequeue(); q.Enqueue(x); } // Get the last element and // add it to the new queue ans.Enqueue(q.Peek()); q.Dequeue(); } return ans;} // Driver Codepublic static void Main(String[] args){ Queue<int> q = new Queue<int>(); // Insert elements q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(4); q.Enqueue(5); q = reverse(q); // Print the queue while (q.Count!=0) { Console.Write(q.Peek() + \" \"); q.Dequeue(); } }} // This code is contributed by Princi Singh",
"e": 30719,
"s": 29674,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to return the reversed queuefunction reverse(q){ // Size of queue let s = q.length; // Second queue let ans = []; for(let i = 0; i < s; i++) { // Get the last element to the // front of queue for(let j = 0; j < q.length - 1; j++) { let x = q.shift(); q.push(x); } // Get the last element and // add it to the new queue ans.push(q[0]); q.shift(); } return ans;} // Driver Codelet q = []; // Insert elementsq.push(1);q.push(2);q.push(3);q.push(4);q.push(5); q = reverse(q); // Print the queuewhile (q.length != 0){ document.write(q[0] + \" \"); q.shift();} // This code is contributed by patel2127 </script>",
"e": 31533,
"s": 30719,
"text": null
},
{
"code": null,
"e": 31543,
"s": 31533,
"text": "5 4 3 2 1"
},
{
"code": null,
"e": 31558,
"s": 31545,
"text": "princi singh"
},
{
"code": null,
"e": 31573,
"s": 31558,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31583,
"s": 31573,
"text": "patel2127"
},
{
"code": null,
"e": 31592,
"s": 31583,
"text": "rkbhola5"
},
{
"code": null,
"e": 31610,
"s": 31592,
"text": "germanshephered48"
},
{
"code": null,
"e": 31626,
"s": 31610,
"text": "Data Structures"
},
{
"code": null,
"e": 31646,
"s": 31626,
"text": "Java-Queue-Programs"
},
{
"code": null,
"e": 31670,
"s": 31646,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31676,
"s": 31670,
"text": "Queue"
},
{
"code": null,
"e": 31692,
"s": 31676,
"text": "Data Structures"
},
{
"code": null,
"e": 31698,
"s": 31692,
"text": "Queue"
},
{
"code": null,
"e": 31796,
"s": 31698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31829,
"s": 31796,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 31875,
"s": 31829,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 31933,
"s": 31875,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 31974,
"s": 31933,
"text": "5 Best Books for Competitive Programming"
},
{
"code": null,
"e": 32019,
"s": 31974,
"text": "5 Best Languages for Competitive Programming"
},
{
"code": null,
"e": 32059,
"s": 32019,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 32093,
"s": 32059,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 32117,
"s": 32093,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 32133,
"s": 32117,
"text": "Queue in Python"
}
] |
Collections synchronizedMap() method in Java with Examples - GeeksforGeeks
|
06 May, 2020
The synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.
Syntax:
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
Parameters: This method takes the map as a parameter to be “wrapped” in a synchronized map.
Return Value: This method returns a synchronized view of the specified map.
Below are the examples to illustrate the synchronizedMap() method.
Example 1:
// Java program to demonstrate// synchronizedMap() method// for <String, String> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Map<String, String> Map<String, String> map = new HashMap<String, String>(); // populate the map map.put("Value1", "20"); map.put("Value2", "30"); map.put("Value3", "40"); // printing the Collection System.out.println("Map : " + map); // create a synchronized map Map<String, String> synmap = Collections.synchronizedMap(map); // printing the Collection System.out.println("Synchronized map is : " + synmap); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }}
Map : {Value3=40, Value1=20, Value2=30}
Synchronized map is : {Value3=40, Value1=20, Value2=30}
Example 2:
// Java program to demonstrate// synchronizedMap() method// for <String, Boolean> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Map<String, Boolean> Map<String, Boolean> map = new HashMap<String, Boolean>(); // populate the map map.put("Bramha", true); map.put("Vishnu", true); map.put("Mahesh", true); // printing the Collection System.out.println("Map : " + map); // create a synchronized map Map<String, Boolean> synmap = Collections.synchronizedMap(map); // printing the Collection System.out.println("Synchronized map is : " + synmap); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }}
Map : {Bramha=true, Vishnu=true, Mahesh=true}
Synchronized map is : {Bramha=true, Vishnu=true, Mahesh=true}
ytxmobile
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 25846,
"s": 25818,
"text": "\n06 May, 2020"
},
{
"code": null,
"e": 26115,
"s": 25846,
"text": "The synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map."
},
{
"code": null,
"e": 26123,
"s": 26115,
"text": "Syntax:"
},
{
"code": null,
"e": 26183,
"s": 26123,
"text": "public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)"
},
{
"code": null,
"e": 26275,
"s": 26183,
"text": "Parameters: This method takes the map as a parameter to be “wrapped” in a synchronized map."
},
{
"code": null,
"e": 26351,
"s": 26275,
"text": "Return Value: This method returns a synchronized view of the specified map."
},
{
"code": null,
"e": 26418,
"s": 26351,
"text": "Below are the examples to illustrate the synchronizedMap() method."
},
{
"code": null,
"e": 26429,
"s": 26418,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// synchronizedMap() method// for <String, String> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Map<String, String> Map<String, String> map = new HashMap<String, String>(); // populate the map map.put(\"Value1\", \"20\"); map.put(\"Value2\", \"30\"); map.put(\"Value3\", \"40\"); // printing the Collection System.out.println(\"Map : \" + map); // create a synchronized map Map<String, String> synmap = Collections.synchronizedMap(map); // printing the Collection System.out.println(\"Synchronized map is : \" + synmap); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27405,
"s": 26429,
"text": null
},
{
"code": null,
"e": 27502,
"s": 27405,
"text": "Map : {Value3=40, Value1=20, Value2=30}\nSynchronized map is : {Value3=40, Value1=20, Value2=30}\n"
},
{
"code": null,
"e": 27513,
"s": 27502,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// synchronizedMap() method// for <String, Boolean> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Map<String, Boolean> Map<String, Boolean> map = new HashMap<String, Boolean>(); // populate the map map.put(\"Bramha\", true); map.put(\"Vishnu\", true); map.put(\"Mahesh\", true); // printing the Collection System.out.println(\"Map : \" + map); // create a synchronized map Map<String, Boolean> synmap = Collections.synchronizedMap(map); // printing the Collection System.out.println(\"Synchronized map is : \" + synmap); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 28494,
"s": 27513,
"text": null
},
{
"code": null,
"e": 28603,
"s": 28494,
"text": "Map : {Bramha=true, Vishnu=true, Mahesh=true}\nSynchronized map is : {Bramha=true, Vishnu=true, Mahesh=true}\n"
},
{
"code": null,
"e": 28613,
"s": 28603,
"text": "ytxmobile"
},
{
"code": null,
"e": 28633,
"s": 28613,
"text": "Java - util package"
},
{
"code": null,
"e": 28650,
"s": 28633,
"text": "Java-Collections"
},
{
"code": null,
"e": 28665,
"s": 28650,
"text": "Java-Functions"
},
{
"code": null,
"e": 28670,
"s": 28665,
"text": "Java"
},
{
"code": null,
"e": 28675,
"s": 28670,
"text": "Java"
},
{
"code": null,
"e": 28692,
"s": 28675,
"text": "Java-Collections"
},
{
"code": null,
"e": 28790,
"s": 28692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28841,
"s": 28790,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28860,
"s": 28841,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28875,
"s": 28860,
"text": "Stream In Java"
},
{
"code": null,
"e": 28906,
"s": 28875,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28924,
"s": 28906,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28956,
"s": 28924,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28976,
"s": 28956,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29008,
"s": 28976,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29032,
"s": 29008,
"text": "Singleton Class in Java"
}
] |
How to Abort a Command Execution in Command Prompt? - GeeksforGeeks
|
17 Sep, 2021
Command Prompt is an interpreter which helps us to execute various commands and functions. These commands may include diskpart, install, cls, etc. Using Command Prompt, we can perform a variety of functions, eg, formatting any drive/Pendrive or compiling any file, or getting IP address using ip-config.
But, what happens if any command stops executing?
What to do if the command prompt gets stuck? How to get out of it? Do we need to close the prompt or we can just abort that particular command and continue from the same place where we left?
We will find these answers in this article;
Suppose we are executing a command the below command:
npm install bootstrap
Now we can use the below keys to terminate the command execution:
CTRL + C
or
Ctrl+ Pause/break
After you press the button a message will appear whether you want to terminate this job or not as shown below:
Now Type ‘Y’ and hit “Enter” to terminate the process.
The Command will continue to execute if we type “N” when prompted. Take a look at the below image where we run the below command:
npm start
Then we hit Ctrl+C to terminate the execution. When prompted for confirmation, we type in “N” as shown below:
In this example, after typing “N” , the command continued its execution and completed it.
Blogathon-2021
Blogathon
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
|
[
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 26401,
"s": 26097,
"text": "Command Prompt is an interpreter which helps us to execute various commands and functions. These commands may include diskpart, install, cls, etc. Using Command Prompt, we can perform a variety of functions, eg, formatting any drive/Pendrive or compiling any file, or getting IP address using ip-config."
},
{
"code": null,
"e": 26451,
"s": 26401,
"text": "But, what happens if any command stops executing?"
},
{
"code": null,
"e": 26642,
"s": 26451,
"text": "What to do if the command prompt gets stuck? How to get out of it? Do we need to close the prompt or we can just abort that particular command and continue from the same place where we left?"
},
{
"code": null,
"e": 26686,
"s": 26642,
"text": "We will find these answers in this article;"
},
{
"code": null,
"e": 26740,
"s": 26686,
"text": "Suppose we are executing a command the below command:"
},
{
"code": null,
"e": 26763,
"s": 26740,
"text": " npm install bootstrap"
},
{
"code": null,
"e": 26829,
"s": 26763,
"text": "Now we can use the below keys to terminate the command execution:"
},
{
"code": null,
"e": 26838,
"s": 26829,
"text": "CTRL + C"
},
{
"code": null,
"e": 26841,
"s": 26838,
"text": "or"
},
{
"code": null,
"e": 26859,
"s": 26841,
"text": "Ctrl+ Pause/break"
},
{
"code": null,
"e": 26970,
"s": 26859,
"text": "After you press the button a message will appear whether you want to terminate this job or not as shown below:"
},
{
"code": null,
"e": 27025,
"s": 26970,
"text": "Now Type ‘Y’ and hit “Enter” to terminate the process."
},
{
"code": null,
"e": 27155,
"s": 27025,
"text": "The Command will continue to execute if we type “N” when prompted. Take a look at the below image where we run the below command:"
},
{
"code": null,
"e": 27165,
"s": 27155,
"text": "npm start"
},
{
"code": null,
"e": 27275,
"s": 27165,
"text": "Then we hit Ctrl+C to terminate the execution. When prompted for confirmation, we type in “N” as shown below:"
},
{
"code": null,
"e": 27365,
"s": 27275,
"text": "In this example, after typing “N” , the command continued its execution and completed it."
},
{
"code": null,
"e": 27380,
"s": 27365,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27390,
"s": 27380,
"text": "Blogathon"
},
{
"code": null,
"e": 27397,
"s": 27390,
"text": "How To"
},
{
"code": null,
"e": 27406,
"s": 27397,
"text": "TechTips"
},
{
"code": null,
"e": 27504,
"s": 27406,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27561,
"s": 27504,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27602,
"s": 27561,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27632,
"s": 27602,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 27667,
"s": 27632,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27711,
"s": 27667,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 27743,
"s": 27711,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27796,
"s": 27743,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 27840,
"s": 27796,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 27867,
"s": 27840,
"text": "How to Align Text in HTML?"
}
] |
How to set & unset session variable in codeigniter ? - GeeksforGeeks
|
07 Jan, 2022
The session class in CodeIgniter allows the user to maintain a user’s “state” and track their activity while browsing the website. The session can be initialized using the library and auto-loaded in the environment using the following command.
$this->load->library('session');
Set the session variable: Session indexes can be assigned using key-value pairs. A particular key can be assigned to a value using the assignment operator. The value may be a string, key, or even an array.
Syntax:
$_SESSION['key'] = value;
Example 1:
PHP
<?PHP // Starting a new session session_start(); $_SESSION['id'] = 9 ; // Check if the session name exists if( isset($_SESSION['id']) ) { echo 'Session id is '.$_SESSION['id'].'<br>'; } else { echo 'Set the session id first '.'<br>'; } echo'<br>'; // Modifying the value of session $_SESSION['id'] = -8 ; echo 'New session id is '.$_SESSION['id'].'<br>'; ?>
Output:
Session id is 9
New session id is -8
The session value can also be assigned using the set_userdata() method in CodeIgniter. This method takes a key as the first argument and the. next is the value to be assigned.
Syntax:
set_userdata ('key' , value)
Multiple key-value pairs can also be added at the session index in CodeIgniter, indicated by the following code snippet.
Example 2:
PHP
<?php // Setting multiple key values $sess_arr = array('id'=>5, 'name' => 'yash'); // Setting index at logged_in $this->session->set_userdata('logged_in', $sess_arr); // Printing the contents at this index print_r($_SESSION['logged_in']);?>
Output:
Array ( [id] => 5 [name] => yash )
Unset the session variable: The session variable can be unset by assigning it to a NULL value. This destroys the value stored at this key value.
Syntax:
$_SESSION['ey'] = NULL
Example 3:
PHP
<?php // Starting a new session session_start(); // Setting multiple values $sess_arr = array('id'=>5, 'name' => 'yash'); $_SESSION['logged_in']= $sess_arr; echo ('Old session : '); print_r ($_SESSION['logged_in']); echo '</br>'; // Unsetting the value $_SESSION['logged_in']= NULL; echo ('New session? : '); print_r ($_SESSION['logged_in']);?>
Output:
Old session : Array ( [id] => 5 [name] => yash )
New session? :
anikakapoor
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Different ways for passing data to view in Laravel
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 26461,
"s": 26217,
"text": "The session class in CodeIgniter allows the user to maintain a user’s “state” and track their activity while browsing the website. The session can be initialized using the library and auto-loaded in the environment using the following command."
},
{
"code": null,
"e": 26494,
"s": 26461,
"text": "$this->load->library('session');"
},
{
"code": null,
"e": 26701,
"s": 26494,
"text": "Set the session variable: Session indexes can be assigned using key-value pairs. A particular key can be assigned to a value using the assignment operator. The value may be a string, key, or even an array. "
},
{
"code": null,
"e": 26709,
"s": 26701,
"text": "Syntax:"
},
{
"code": null,
"e": 26736,
"s": 26709,
"text": "$_SESSION['key'] = value; "
},
{
"code": null,
"e": 26749,
"s": 26738,
"text": "Example 1:"
},
{
"code": null,
"e": 26753,
"s": 26749,
"text": "PHP"
},
{
"code": "<?PHP // Starting a new session session_start(); $_SESSION['id'] = 9 ; // Check if the session name exists if( isset($_SESSION['id']) ) { echo 'Session id is '.$_SESSION['id'].'<br>'; } else { echo 'Set the session id first '.'<br>'; } echo'<br>'; // Modifying the value of session $_SESSION['id'] = -8 ; echo 'New session id is '.$_SESSION['id'].'<br>'; ?> ",
"e": 27163,
"s": 26753,
"text": null
},
{
"code": null,
"e": 27171,
"s": 27163,
"text": "Output:"
},
{
"code": null,
"e": 27208,
"s": 27171,
"text": "Session id is 9\nNew session id is -8"
},
{
"code": null,
"e": 27385,
"s": 27208,
"text": "The session value can also be assigned using the set_userdata() method in CodeIgniter. This method takes a key as the first argument and the. next is the value to be assigned. "
},
{
"code": null,
"e": 27393,
"s": 27385,
"text": "Syntax:"
},
{
"code": null,
"e": 27422,
"s": 27393,
"text": "set_userdata ('key' , value)"
},
{
"code": null,
"e": 27543,
"s": 27422,
"text": "Multiple key-value pairs can also be added at the session index in CodeIgniter, indicated by the following code snippet."
},
{
"code": null,
"e": 27554,
"s": 27543,
"text": "Example 2:"
},
{
"code": null,
"e": 27558,
"s": 27554,
"text": "PHP"
},
{
"code": "<?php // Setting multiple key values $sess_arr = array('id'=>5, 'name' => 'yash'); // Setting index at logged_in $this->session->set_userdata('logged_in', $sess_arr); // Printing the contents at this index print_r($_SESSION['logged_in']);?>",
"e": 27813,
"s": 27558,
"text": null
},
{
"code": null,
"e": 27821,
"s": 27813,
"text": "Output:"
},
{
"code": null,
"e": 27857,
"s": 27821,
"text": "Array ( [id] => 5 [name] => yash ) "
},
{
"code": null,
"e": 28003,
"s": 27857,
"text": "Unset the session variable: The session variable can be unset by assigning it to a NULL value. This destroys the value stored at this key value. "
},
{
"code": null,
"e": 28011,
"s": 28003,
"text": "Syntax:"
},
{
"code": null,
"e": 28034,
"s": 28011,
"text": "$_SESSION['ey'] = NULL"
},
{
"code": null,
"e": 28045,
"s": 28034,
"text": "Example 3:"
},
{
"code": null,
"e": 28049,
"s": 28045,
"text": "PHP"
},
{
"code": "<?php // Starting a new session session_start(); // Setting multiple values $sess_arr = array('id'=>5, 'name' => 'yash'); $_SESSION['logged_in']= $sess_arr; echo ('Old session : '); print_r ($_SESSION['logged_in']); echo '</br>'; // Unsetting the value $_SESSION['logged_in']= NULL; echo ('New session? : '); print_r ($_SESSION['logged_in']);?> ",
"e": 28421,
"s": 28049,
"text": null
},
{
"code": null,
"e": 28429,
"s": 28421,
"text": "Output:"
},
{
"code": null,
"e": 28493,
"s": 28429,
"text": "Old session : Array ( [id] => 5 [name] => yash )\nNew session? :"
},
{
"code": null,
"e": 28505,
"s": 28493,
"text": "anikakapoor"
},
{
"code": null,
"e": 28518,
"s": 28505,
"text": "PHP-function"
},
{
"code": null,
"e": 28532,
"s": 28518,
"text": "PHP-Questions"
},
{
"code": null,
"e": 28539,
"s": 28532,
"text": "Picked"
},
{
"code": null,
"e": 28543,
"s": 28539,
"text": "PHP"
},
{
"code": null,
"e": 28560,
"s": 28543,
"text": "Web Technologies"
},
{
"code": null,
"e": 28564,
"s": 28560,
"text": "PHP"
},
{
"code": null,
"e": 28662,
"s": 28564,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28744,
"s": 28662,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28786,
"s": 28744,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 28813,
"s": 28786,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 28877,
"s": 28813,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 28928,
"s": 28877,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 28968,
"s": 28928,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29001,
"s": 28968,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29046,
"s": 29001,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29089,
"s": 29046,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Minimum number of swaps required to sort an array - GeeksforGeeks
|
28 Mar, 2022
Given an array of n distinct elements, find the minimum number of swaps required to sort the array.
Examples:
Input: {4, 3, 2, 1}
Output: 2
Explanation: Swap index 0 with 3 and 1 with 2 to
form the sorted array {1, 2, 3, 4}.
Input: {1, 5, 4, 3, 2}
Output: 2
This can be easily done by visualizing the problem as a graph. We will have n nodes and an edge directed from node i to node j if the element at i’th index must be present at j’th index in the sorted array.
Graph for {4, 3, 2, 1}
The graph will now contain many non-intersecting cycles. Now a cycle with 2 nodes will only require 1 swap to reach the correct ordering, similarly, a cycle with 3 nodes will only require 2 swaps to do so.
Graph for {4, 5, 2, 1, 5}
Hence,
ans = Σi = 1k(cycle_size – 1)
where, k is the number of cycles
Below is the implementation of the idea.
C++
Java
Python3
C#
Javascript
// C++ program to find // minimum number of swaps// required to sort an array#include<bits/stdc++.h> using namespace std; // Function returns the// minimum number of swaps// required to sort the arrayint minSwaps(int arr[], int n){ // Create an array of // pairs where first // element is array element // and second element // is position of first element pair<int, int> arrPos[n]; for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; } // Sort the array by array // element values to // get right position of // every element as second // element of pair. sort(arrPos, arrPos + n); // To keep track of visited elements. // Initialize // all elements as not visited or false. vector<bool> vis(n, false); // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrPos[i].second == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = 1; // move to next node j = arrPos[j].second; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans;} // Driver program to test the above functionint main(){ int arr[] = {1, 5, 4, 3, 2}; int n = (sizeof(arr) / sizeof(int)); cout << minSwaps(arr, n); return 0;}
// Java program to find // minimum number of swaps// required to sort an arrayimport javafx.util.Pair;import java.util.ArrayList;import java.util.*; class GfG{ // Function returns the // minimum number of swaps // required to sort the array public static int minSwaps(int[] arr) { int n = arr.length; // Create two arrays and // use as pairs where first // array is element and second array // is position of first element ArrayList <Pair <Integer, Integer> > arrpos = new ArrayList <Pair <Integer, Integer> > (); for (int i = 0; i < n; i++) arrpos.add(new Pair <Integer, Integer> (arr[i], i)); // Sort the array by array element values to // get right position of every element as the // elements of second array. arrpos.sort(new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) { if (o1.getKey() > o2.getKey()) return -1; // We can change this to make // it then look at the // words alphabetical order else if (o1.getKey().equals(o2.getKey())) return 0; else return 1; } }); // To keep track of visited elements. Initialize // all elements as not visited or false. Boolean[] vis = new Boolean[n]; Arrays.fill(vis, false); // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrpos.get(i).getValue() == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = true; // move to next node j = arrpos.get(j).getValue(); cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans; }} // Driver classclass MinSwaps{ // Driver program to test the above function public static void main(String[] args) { int []a = {1, 5, 4, 3, 2}; GfG g = new GfG(); System.out.println(g.minSwaps(a)); }}// This code is contributed by Saksham Seth
# Python3 program to find # minimum number of swaps# required to sort an array # Function returns the minimum# number of swaps required to# sort the arraydef minSwaps(arr): n = len(arr) # Create two arrays and use # as pairs where first array # is element and second array # is position of first element arrpos = [*enumerate(arr)] # Sort the array by array element # values to get right position of # every element as the elements # of second array. arrpos.sort(key = lambda it : it[1]) # To keep track of visited elements. # Initialize all elements as not # visited or false. vis = {k : False for k in range(n)} # Initialize result ans = 0 for i in range(n): # already swapped or # already present at # correct position if vis[i] or arrpos[i][0] == i: continue # find number of nodes # in this cycle and # add it to ans cycle_size = 0 j = i while not vis[j]: # mark node as visited vis[j] = True # move to next node j = arrpos[j][0] cycle_size += 1 # update answer by adding # current cycle if cycle_size > 0: ans += (cycle_size - 1) # return answer return ans # Driver Code arr = [1, 5, 4, 3, 2]print(minSwaps(arr)) # This code is contributed# by Dharan Aditya
// C# program to find // minimum number of swaps// required to sort an arrayusing System;using System.Collections.Generic;using System.Linq; public class GfG{ // Function returns the // minimum number of swaps // required to sort the array public int minSwaps(int[] arr) { int n = arr.Length; // Create two arrays and // use as pairs where first // array is element and second array // is position of first element List <KeyValuePair <int, int> > arrpos = new List <KeyValuePair <int, int> > (); for (int i = 0; i < n; i++) arrpos.Add(new KeyValuePair <int, int> (arr[i], i)); // Sort the array by array element values to // get right position of every element as the // elements of second array. arrpos.Sort((a,b)=> a.Key-b.Key); // To keep track of visited elements. Initialize // all elements as not visited or false. Boolean[] vis = new Boolean[n]; // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrpos[i].Value == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = true; // move to next node j = arrpos[j].Value; cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans; }} // Driver classpublic class MinSwaps{ // Driver program to test the above function public static void Main(String[] args) { int []a = {1, 5, 4, 3, 2}; GfG g = new GfG(); Console.WriteLine(g.minSwaps(a)); }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to find// minimum number of swaps// required to sort an array // Function returns the// minimum number of swaps// required to sort the arrayfunction minSwaps(arr){ let n = arr.length; // Create two arrays and // use as pairs where first // array is element and second array // is position of first element let arrpos = []; for (let i = 0; i < n; i++) arrpos.push([arr[i], i]); // Sort the array by array element values to // get right position of every element as the // elements of second array. arrpos.sort(function(a,b){return a[0]-b[0];}); // To keep track of visited elements. Initialize // all elements as not visited or false. let vis = new Array(n); for(let i=0;i<n;i++) { vis[i]=false; } // Initialize result let ans = 0; // Traverse array elements for (let i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrpos[i][1] == i) continue; // find out the number of node in // this cycle and add in ans let cycle_size = 0; let j = i; while (!vis[j]) { vis[j] = true; // move to next node j = arrpos[j][1]; cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans;} // Driver classlet a=[1, 5, 4, 3, 2];document.write(minSwaps(a)) // This code is contributed by ab2127 </script>
Output:
2
Time Complexity: O(n Log n) Auxiliary Space: O(n)
Approach: As Pair class available in java from java 8 so we can use hashmap in older java version.
Below is the implementation of the idea.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;// Function returns the// minimum number of swaps// required to sort the arrayint minSwaps(int nums[], int n){ int len = n; map<int, int> map; for (int i = 0; i < len; i++) map[nums[i]] = i; sort(nums, nums + n); // To keep track of visited elements. Initialize // all elements as not visited or false. bool visited[len] = { 0 }; // Initialize result int ans = 0; for (int i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map[nums[i]] == i) continue; int j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map[nums[j]]; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans;}int main(){ // Driver program to test the above function int a[] = { 1, 5, 4, 3, 2 }; int n = 5; cout << minSwaps(a, n); return 0;} // This code is contributed by Harshal Khond
import java.util.*;import java.io.*; class GfG{ // Function returns the // minimum number of swaps // required to sort the array public static int minSwaps(int[] nums) { int len = nums.length; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0;i<len;i++) map.put(nums[i], i); Arrays.sort(nums); // To keep track of visited elements. Initialize // all elements as not visited or false. boolean[] visited = new boolean[len]; Arrays.fill(visited, false); // Initialize result int ans = 0; for(int i=0;i<len;i++) { // already swapped and corrected or // already present at correct pos if(visited[i] || map.get(nums[i]) == i) continue; int j = i, cycle_size = 0; while(!visited[j]) { visited[j] = true; // move to next node j = map.get(nums[j]); cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } return ans; }} // Driver classclass MinSwaps{ // Driver program to test the above function public static void main(String[] args) { int []a = {1, 5, 4, 3, 2}; GfG g = new GfG(); System.out.println(g.minSwaps(a)); }}// This code is contributed by Saurabh Johari
# Function returns the# minimum number of swaps# required to sort the arrayfrom functools import cmp_to_key def cmp(a, b): return a - b def minSwaps(nums): Len = len(nums) map = {} for i in range(Len): map[nums[i]] = i nums = sorted(nums, key = cmp_to_key(cmp)) # To keep track of visited elements. Initialize # all elements as not visited or false. visited = [False for col in range(Len)] # Initialize result ans = 0 for i in range(Len): # already swapped and corrected or # already present at correct pos if (visited[i] or map[nums[i]] == i): continue j,cycle_size = i, 0 while (visited[j] == False): visited[j] = True # move to next node j = map[nums[j]] cycle_size += 1 # Update answer by adding current cycle. if (cycle_size > 0): ans += (cycle_size - 1) return ans # Driver program to test the above functiona = [ 1, 5, 4, 3, 2 ]print(minSwaps(a)) # This code is contributed by shinjanpatra
using System;using System.Collections.Generic; class GfG { // Function returns the // minimum number of swaps // required to sort the array public int minSwaps(int[] nums) { int len = nums.Length; Dictionary<int, int> map = new Dictionary<int,int>(); for (int i = 0; i < len; i++) map.Add(nums[i], i); Array.Sort(nums); // To keep track of visited elements. Initialize // all elements as not visited or false. bool[] visited = new bool[len]; // Initialize result int ans = 0; for (int i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map[nums[i]] == i) continue; int j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map[nums[j]]; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans; }} // Driver classpublic class MinSwaps{ // Driver program to test the above function public static void Main(String[] args) { int[] a = { 1, 5, 4, 3, 2 }; GfG g = new GfG(); Console.WriteLine(g.minSwaps(a)); }} // This code is contributed by gauravrajput1
<script> // Function returns the // minimum number of swaps // required to sort the array function minSwaps(nums) { var len = nums.length; var map = new Map(); for (i = 0; i < len; i++) map.set(nums[i], i); nums.sort((a,b)=>a-b); // To keep track of visited elements. Initialize // all elements as not visited or false. var visited = Array(len).fill(false); // Initialize result var ans = 0; for (var i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map.get(nums[i]) == i) continue; var j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map.get(nums[j]); cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans; } // Driver program to test the above function var a = [ 1, 5, 4, 3, 2 ]; document.write(minSwaps(a)); // This code is contributed by Rajput-Ji</script>
Time Complexity: O(n Log n)
Auxiliary Space: O(n)
Straight forward solution
While iterating over the array, check the current element, and if not in the correct place, replace that element with the index of the element which should have come in this place.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find minimum number// of swaps required to sort an array#include <bits/stdc++.h>using namespace std; void swap(vector<int> &arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} int indexOf(vector<int> &arr, int ele){ for(int i = 0; i < arr.size(); i++) { if (arr[i] == ele) { return i; } } return -1;} // Return the minimum number// of swaps required to sort the arrayint minSwaps(vector<int> arr, int N){ int ans = 0; vector<int> temp(arr.begin(),arr.end()); sort(temp.begin(),temp.end()); for(int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans;} // Driver Codeint main(){ vector<int> a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n);} // This code is contributed by mohit kumar 29
// Java program to find// minimum number of swaps// required to sort an arrayimport java.util.*;import java.io.*; class GfG{ // Return the minimum number // of swaps required to sort the array public int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = Arrays.copyOfRange(arr, 0, N); Arrays.sort(temp); for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public int indexOf(int[] arr, int ele) { for (int i = 0; i < arr.length; i++) { if (arr[i] == ele) { return i; } } return -1; }}// Driver classclass Main{ // Driver program to test // the above function public static void main(String[] args) throws Exception { int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.length; // Output will be 5 System.out.println(new GfG().minSwaps(a, n)); }}// This code is contributed by Satvik Nema
# Python3 program to find#minimum number of swaps# required to sort an array # Return the minimum number# of swaps required to sort# the arraydef minSwaps(arr, N): ans = 0 temp = arr.copy() temp.sort() for i in range(N): # This is checking whether # the current element is # at the right place or not if (arr[i] != temp[i]): ans += 1 # Swap the current element # with the right index # so that arr[0] to arr[i] # is sorted swap(arr, i, indexOf(arr, temp[i])) return ans def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp def indexOf(arr, ele): for i in range(len(arr)): if (arr[i] == ele): return i return -1 # Driver codeif __name__ == "__main__": a = [101, 758, 315, 730, 472, 619, 460, 479] n = len(a) # Output will be 5 print(minSwaps(a, n)) # This code is contributed by Chitranayal
// C# program to find// minimum number of swaps// required to sort an arrayusing System;public class GFG{ // Return the minimum number // of swaps required to sort the array static int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = new int[N]; Array.Copy(arr, temp, N); Array.Sort(temp); for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int indexOf(int[] arr, int ele) { for (int i = 0; i < arr.Length; i++) { if (arr[i] == ele) { return i; } } return -1; } // Driver program to test // the above function static public void Main (){ int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.Length; // Output will be 5 Console.WriteLine(minSwaps(a, n)); }} // This code is contributed by rag2127
<script>// Javascript program to find// minimum number of swaps// required to sort an array // Return the minimum number // of swaps required to sort the array function minSwaps(arr,N) { let ans = 0; let temp = [...arr]; temp.sort(function(a,b){return a-b;}); for (let i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } function swap(arr,i,j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } function indexOf(arr,ele) { for (let i = 0; i < arr.length; i++) { if (arr[i] == ele) { return i; } } return -1; } // Driver class let a=[101, 758, 315, 730, 472, 619, 460, 479 ]; let n = a.length; document.write(minSwaps(a, n)); // This code is contributed by unknown2108</script>
Output:
5
Time Complexity: O(n*n) Auxiliary Space: O(n)
We can still improve the complexity by using a hashmap. The main operation here is the indexOf method inside the loop, which costs us n*n. We can improve this section to O(n), by using a hashmap to store the indexes. Still, we use the sort method, so the complexity cannot improve beyond O(n Log n)
Method using HashMap:
Same as before, make a new array (called temp), which is the sorted form of the input array. We know that we need to transform the input array to the new array (temp) in the minimum number of swaps. Make a map that stores the elements and their corresponding index, of the input array.
So at each i starting from 0 to N in the given array, where N is the size of the array:
1. If i is not in its correct position according to the sorted array, then
2. We will fill this position with the correct element from the hashmap we built earlier. We know the correct element which should come here is temp[i], so we look up the index of this element from the hashmap.
3. After swapping the required elements, we update the content of the hashmap accordingly, as temp[i] to the ith position, and arr[i] to where temp[i] was earlier.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find// minimum number of swaps// required to sort an array#include<bits/stdc++.h>using namespace std; void swap(vector<int> &arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;}// Return the minimum number// of swaps required to sort// the arrayint minSwaps(vector<int>arr, int N){ int ans = 0; vector<int>temp = arr; // Hashmap which stores the // indexes of the input array map <int, int> h; sort(temp.begin(), temp.end()); for (int i = 0; i < N; i++) { h[arr[i]] = i; } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h[temp[i]]); // Update the indexes in // the hashmap accordingly h[init] = h[temp[i]]; h[temp[i]] = i; } } return ans;} // Driver classint main(){ // Driver program to // test the above function vector <int> a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n);} // This code is contributed by Stream_Cipher
// Java program to find// minimum number of swaps// required to sort an arrayimport java.util.*;import java.io.*; class GfG{ // Return the minimum number // of swaps required to sort the array public int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = Arrays.copyOfRange(arr, 0, N); // Hashmap which stores the // indexes of the input array HashMap<Integer, Integer> h = new HashMap<Integer, Integer>(); Arrays.sort(temp); for (int i = 0; i < N; i++) { h.put(arr[i], i); } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h.get(temp[i])); // Update the indexes in // the hashmap accordingly h.put(init, h.get(temp[i])); h.put(temp[i], i); } } return ans; } public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }} // Driver classclass Main{ // Driver program to test the above function public static void main(String[] args) throws Exception { int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.length; // Output will be 5 System.out.println(new GfG().minSwaps(a, n)); }}// This code is contributed by Satvik Nema
# Python3 program to find# minimum number of swaps# required to sort an array # Return the minimum number# of swaps required to sort# the arraydef minSwap(arr, n): ans = 0 temp = arr.copy() # Dictionary which stores the # indexes of the input array h = {} temp.sort() for i in range(n): #h.[arr[i] h[arr[i]] = i init = 0 for i in range(n): # This is checking whether # the current element is # at the right place or not if (arr[i] != temp[i]): ans += 1 init = arr[i] # If not, swap this element # with the index of the # element which should come here arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i] # Update the indexes in # the hashmap accordingly h[init] = h[temp[i]] h[temp[i]] = i return ans # Driver codea = [ 101, 758, 315, 730, 472, 619, 460, 479 ]n = len(a) # Output will be 5print(minSwap(a, n)) # This code is contributed by avanitrachhadiya2155
// C# program to find// minimum number of swaps// required to sort an arrayusing System;using System.Collections.Generic;using System.Linq;public class GfG { // Return the minimum number // of swaps required to sort the array public int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = new int[N]; arr.CopyTo(temp,0); // Hashmap which stores the // indexes of the input array Dictionary<int, int> h = new Dictionary<int, int>(); Array.Sort(temp); for (int i = 0; i < N; i++) { h.Add(arr[i], i); } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h[temp[i]]); // Update the indexes in // the hashmap accordingly h[init]= h[temp[i]]; h[temp[i]]= i; } } return ans; } public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }} // Driver classpublic class GFG { public static void Main(String[] args) { int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.Length; // Output will be 5 Console.WriteLine(new GfG().minSwaps(a, n)); }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to find// minimum number of swaps// required to sort an arrayfunction swap(arr, i, j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} // Return the minimum number// of swaps required to sort// the arrayfunction minSwaps(arr,N){ let ans = 0; let temp = arr.slice(); // Hashmap which stores the // indexes of the input array let h = new Map(); temp.sort(); for (let i = 0; i < N; i++) { h.set(arr[i], i); } for (let i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; let init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h.get(temp[i])); // Update the indexes in // the hashmap accordingly h.set(init,h.get(temp[i])); h.set(temp[i],i); } } return ans;} // Driver class // Driver program to // test the above functionlet a = [101, 758, 315, 730, 472, 619, 460, 479];let n = a.length; // Output will be 5document.write(minSwaps(a, n)); // This code is contributed by shinjanpatra </script>
Output:
5
Time Complexity: O(n Log n) Auxiliary Space: O(n)
Related Article : Number of swaps to sort when only adjacent swapping allowed
This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
dharan1011
prem_ukkoji
EeshwaraSai
SatvikNema
ukasp
Stream_Cipher
avanitrachhadiya2155
rag2127
mohit kumar 29
unknown2108
Johari Saurabh
ab2127
GauravRajput1
Rajput-Ji
harshalkhond
shinjanpatra
simmytarika5
Arrays
Graph
Sorting
Arrays
Sorting
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Search an element in a sorted and rotated array
Queue | Set 1 (Introduction and Array Implementation)
Find Second largest element in an array
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
|
[
{
"code": null,
"e": 26315,
"s": 26287,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 26415,
"s": 26315,
"text": "Given an array of n distinct elements, find the minimum number of swaps required to sort the array."
},
{
"code": null,
"e": 26426,
"s": 26415,
"text": "Examples: "
},
{
"code": null,
"e": 26590,
"s": 26426,
"text": "Input: {4, 3, 2, 1}\nOutput: 2\nExplanation: Swap index 0 with 3 and 1 with 2 to \n form the sorted array {1, 2, 3, 4}.\n\nInput: {1, 5, 4, 3, 2}\nOutput: 2"
},
{
"code": null,
"e": 26799,
"s": 26590,
"text": "This can be easily done by visualizing the problem as a graph. We will have n nodes and an edge directed from node i to node j if the element at i’th index must be present at j’th index in the sorted array. "
},
{
"code": null,
"e": 26822,
"s": 26799,
"text": "Graph for {4, 3, 2, 1}"
},
{
"code": null,
"e": 27030,
"s": 26822,
"text": "The graph will now contain many non-intersecting cycles. Now a cycle with 2 nodes will only require 1 swap to reach the correct ordering, similarly, a cycle with 3 nodes will only require 2 swaps to do so. "
},
{
"code": null,
"e": 27056,
"s": 27030,
"text": "Graph for {4, 5, 2, 1, 5}"
},
{
"code": null,
"e": 27063,
"s": 27056,
"text": "Hence,"
},
{
"code": null,
"e": 27093,
"s": 27063,
"text": "ans = Σi = 1k(cycle_size – 1)"
},
{
"code": null,
"e": 27126,
"s": 27093,
"text": "where, k is the number of cycles"
},
{
"code": null,
"e": 27168,
"s": 27126,
"text": "Below is the implementation of the idea. "
},
{
"code": null,
"e": 27172,
"s": 27168,
"text": "C++"
},
{
"code": null,
"e": 27177,
"s": 27172,
"text": "Java"
},
{
"code": null,
"e": 27185,
"s": 27177,
"text": "Python3"
},
{
"code": null,
"e": 27188,
"s": 27185,
"text": "C#"
},
{
"code": null,
"e": 27199,
"s": 27188,
"text": "Javascript"
},
{
"code": "// C++ program to find // minimum number of swaps// required to sort an array#include<bits/stdc++.h> using namespace std; // Function returns the// minimum number of swaps// required to sort the arrayint minSwaps(int arr[], int n){ // Create an array of // pairs where first // element is array element // and second element // is position of first element pair<int, int> arrPos[n]; for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; } // Sort the array by array // element values to // get right position of // every element as second // element of pair. sort(arrPos, arrPos + n); // To keep track of visited elements. // Initialize // all elements as not visited or false. vector<bool> vis(n, false); // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrPos[i].second == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = 1; // move to next node j = arrPos[j].second; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans;} // Driver program to test the above functionint main(){ int arr[] = {1, 5, 4, 3, 2}; int n = (sizeof(arr) / sizeof(int)); cout << minSwaps(arr, n); return 0;}",
"e": 28882,
"s": 27199,
"text": null
},
{
"code": "// Java program to find // minimum number of swaps// required to sort an arrayimport javafx.util.Pair;import java.util.ArrayList;import java.util.*; class GfG{ // Function returns the // minimum number of swaps // required to sort the array public static int minSwaps(int[] arr) { int n = arr.length; // Create two arrays and // use as pairs where first // array is element and second array // is position of first element ArrayList <Pair <Integer, Integer> > arrpos = new ArrayList <Pair <Integer, Integer> > (); for (int i = 0; i < n; i++) arrpos.add(new Pair <Integer, Integer> (arr[i], i)); // Sort the array by array element values to // get right position of every element as the // elements of second array. arrpos.sort(new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) { if (o1.getKey() > o2.getKey()) return -1; // We can change this to make // it then look at the // words alphabetical order else if (o1.getKey().equals(o2.getKey())) return 0; else return 1; } }); // To keep track of visited elements. Initialize // all elements as not visited or false. Boolean[] vis = new Boolean[n]; Arrays.fill(vis, false); // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrpos.get(i).getValue() == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = true; // move to next node j = arrpos.get(j).getValue(); cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans; }} // Driver classclass MinSwaps{ // Driver program to test the above function public static void main(String[] args) { int []a = {1, 5, 4, 3, 2}; GfG g = new GfG(); System.out.println(g.minSwaps(a)); }}// This code is contributed by Saksham Seth",
"e": 31697,
"s": 28882,
"text": null
},
{
"code": "# Python3 program to find # minimum number of swaps# required to sort an array # Function returns the minimum# number of swaps required to# sort the arraydef minSwaps(arr): n = len(arr) # Create two arrays and use # as pairs where first array # is element and second array # is position of first element arrpos = [*enumerate(arr)] # Sort the array by array element # values to get right position of # every element as the elements # of second array. arrpos.sort(key = lambda it : it[1]) # To keep track of visited elements. # Initialize all elements as not # visited or false. vis = {k : False for k in range(n)} # Initialize result ans = 0 for i in range(n): # already swapped or # already present at # correct position if vis[i] or arrpos[i][0] == i: continue # find number of nodes # in this cycle and # add it to ans cycle_size = 0 j = i while not vis[j]: # mark node as visited vis[j] = True # move to next node j = arrpos[j][0] cycle_size += 1 # update answer by adding # current cycle if cycle_size > 0: ans += (cycle_size - 1) # return answer return ans # Driver Code arr = [1, 5, 4, 3, 2]print(minSwaps(arr)) # This code is contributed# by Dharan Aditya",
"e": 33194,
"s": 31697,
"text": null
},
{
"code": "// C# program to find // minimum number of swaps// required to sort an arrayusing System;using System.Collections.Generic;using System.Linq; public class GfG{ // Function returns the // minimum number of swaps // required to sort the array public int minSwaps(int[] arr) { int n = arr.Length; // Create two arrays and // use as pairs where first // array is element and second array // is position of first element List <KeyValuePair <int, int> > arrpos = new List <KeyValuePair <int, int> > (); for (int i = 0; i < n; i++) arrpos.Add(new KeyValuePair <int, int> (arr[i], i)); // Sort the array by array element values to // get right position of every element as the // elements of second array. arrpos.Sort((a,b)=> a.Key-b.Key); // To keep track of visited elements. Initialize // all elements as not visited or false. Boolean[] vis = new Boolean[n]; // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrpos[i].Value == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = true; // move to next node j = arrpos[j].Value; cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans; }} // Driver classpublic class MinSwaps{ // Driver program to test the above function public static void Main(String[] args) { int []a = {1, 5, 4, 3, 2}; GfG g = new GfG(); Console.WriteLine(g.minSwaps(a)); }} // This code is contributed by Rajput-Ji",
"e": 35057,
"s": 33194,
"text": null
},
{
"code": "<script> // JavaScript program to find// minimum number of swaps// required to sort an array // Function returns the// minimum number of swaps// required to sort the arrayfunction minSwaps(arr){ let n = arr.length; // Create two arrays and // use as pairs where first // array is element and second array // is position of first element let arrpos = []; for (let i = 0; i < n; i++) arrpos.push([arr[i], i]); // Sort the array by array element values to // get right position of every element as the // elements of second array. arrpos.sort(function(a,b){return a[0]-b[0];}); // To keep track of visited elements. Initialize // all elements as not visited or false. let vis = new Array(n); for(let i=0;i<n;i++) { vis[i]=false; } // Initialize result let ans = 0; // Traverse array elements for (let i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrpos[i][1] == i) continue; // find out the number of node in // this cycle and add in ans let cycle_size = 0; let j = i; while (!vis[j]) { vis[j] = true; // move to next node j = arrpos[j][1]; cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans;} // Driver classlet a=[1, 5, 4, 3, 2];document.write(minSwaps(a)) // This code is contributed by ab2127 </script>",
"e": 36914,
"s": 35057,
"text": null
},
{
"code": null,
"e": 36923,
"s": 36914,
"text": "Output: "
},
{
"code": null,
"e": 36925,
"s": 36923,
"text": "2"
},
{
"code": null,
"e": 36975,
"s": 36925,
"text": "Time Complexity: O(n Log n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 37074,
"s": 36975,
"text": "Approach: As Pair class available in java from java 8 so we can use hashmap in older java version."
},
{
"code": null,
"e": 37116,
"s": 37074,
"text": "Below is the implementation of the idea. "
},
{
"code": null,
"e": 37120,
"s": 37116,
"text": "C++"
},
{
"code": null,
"e": 37125,
"s": 37120,
"text": "Java"
},
{
"code": null,
"e": 37133,
"s": 37125,
"text": "Python3"
},
{
"code": null,
"e": 37136,
"s": 37133,
"text": "C#"
},
{
"code": null,
"e": 37147,
"s": 37136,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;// Function returns the// minimum number of swaps// required to sort the arrayint minSwaps(int nums[], int n){ int len = n; map<int, int> map; for (int i = 0; i < len; i++) map[nums[i]] = i; sort(nums, nums + n); // To keep track of visited elements. Initialize // all elements as not visited or false. bool visited[len] = { 0 }; // Initialize result int ans = 0; for (int i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map[nums[i]] == i) continue; int j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map[nums[j]]; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans;}int main(){ // Driver program to test the above function int a[] = { 1, 5, 4, 3, 2 }; int n = 5; cout << minSwaps(a, n); return 0;} // This code is contributed by Harshal Khond",
"e": 38303,
"s": 37147,
"text": null
},
{
"code": "import java.util.*;import java.io.*; class GfG{ // Function returns the // minimum number of swaps // required to sort the array public static int minSwaps(int[] nums) { int len = nums.length; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0;i<len;i++) map.put(nums[i], i); Arrays.sort(nums); // To keep track of visited elements. Initialize // all elements as not visited or false. boolean[] visited = new boolean[len]; Arrays.fill(visited, false); // Initialize result int ans = 0; for(int i=0;i<len;i++) { // already swapped and corrected or // already present at correct pos if(visited[i] || map.get(nums[i]) == i) continue; int j = i, cycle_size = 0; while(!visited[j]) { visited[j] = true; // move to next node j = map.get(nums[j]); cycle_size++; } // Update answer by adding current cycle. if(cycle_size > 0) { ans += (cycle_size - 1); } } return ans; }} // Driver classclass MinSwaps{ // Driver program to test the above function public static void main(String[] args) { int []a = {1, 5, 4, 3, 2}; GfG g = new GfG(); System.out.println(g.minSwaps(a)); }}// This code is contributed by Saurabh Johari",
"e": 39868,
"s": 38303,
"text": null
},
{
"code": "# Function returns the# minimum number of swaps# required to sort the arrayfrom functools import cmp_to_key def cmp(a, b): return a - b def minSwaps(nums): Len = len(nums) map = {} for i in range(Len): map[nums[i]] = i nums = sorted(nums, key = cmp_to_key(cmp)) # To keep track of visited elements. Initialize # all elements as not visited or false. visited = [False for col in range(Len)] # Initialize result ans = 0 for i in range(Len): # already swapped and corrected or # already present at correct pos if (visited[i] or map[nums[i]] == i): continue j,cycle_size = i, 0 while (visited[j] == False): visited[j] = True # move to next node j = map[nums[j]] cycle_size += 1 # Update answer by adding current cycle. if (cycle_size > 0): ans += (cycle_size - 1) return ans # Driver program to test the above functiona = [ 1, 5, 4, 3, 2 ]print(minSwaps(a)) # This code is contributed by shinjanpatra",
"e": 40939,
"s": 39868,
"text": null
},
{
"code": "using System;using System.Collections.Generic; class GfG { // Function returns the // minimum number of swaps // required to sort the array public int minSwaps(int[] nums) { int len = nums.Length; Dictionary<int, int> map = new Dictionary<int,int>(); for (int i = 0; i < len; i++) map.Add(nums[i], i); Array.Sort(nums); // To keep track of visited elements. Initialize // all elements as not visited or false. bool[] visited = new bool[len]; // Initialize result int ans = 0; for (int i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map[nums[i]] == i) continue; int j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map[nums[j]]; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans; }} // Driver classpublic class MinSwaps{ // Driver program to test the above function public static void Main(String[] args) { int[] a = { 1, 5, 4, 3, 2 }; GfG g = new GfG(); Console.WriteLine(g.minSwaps(a)); }} // This code is contributed by gauravrajput1",
"e": 42403,
"s": 40939,
"text": null
},
{
"code": "<script> // Function returns the // minimum number of swaps // required to sort the array function minSwaps(nums) { var len = nums.length; var map = new Map(); for (i = 0; i < len; i++) map.set(nums[i], i); nums.sort((a,b)=>a-b); // To keep track of visited elements. Initialize // all elements as not visited or false. var visited = Array(len).fill(false); // Initialize result var ans = 0; for (var i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map.get(nums[i]) == i) continue; var j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map.get(nums[j]); cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans; } // Driver program to test the above function var a = [ 1, 5, 4, 3, 2 ]; document.write(minSwaps(a)); // This code is contributed by Rajput-Ji</script>",
"e": 43673,
"s": 42403,
"text": null
},
{
"code": null,
"e": 43702,
"s": 43673,
"text": "Time Complexity: O(n Log n) "
},
{
"code": null,
"e": 43724,
"s": 43702,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 43750,
"s": 43724,
"text": "Straight forward solution"
},
{
"code": null,
"e": 43931,
"s": 43750,
"text": "While iterating over the array, check the current element, and if not in the correct place, replace that element with the index of the element which should have come in this place."
},
{
"code": null,
"e": 43982,
"s": 43931,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 43986,
"s": 43982,
"text": "C++"
},
{
"code": null,
"e": 43991,
"s": 43986,
"text": "Java"
},
{
"code": null,
"e": 43999,
"s": 43991,
"text": "Python3"
},
{
"code": null,
"e": 44002,
"s": 43999,
"text": "C#"
},
{
"code": null,
"e": 44013,
"s": 44002,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum number// of swaps required to sort an array#include <bits/stdc++.h>using namespace std; void swap(vector<int> &arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} int indexOf(vector<int> &arr, int ele){ for(int i = 0; i < arr.size(); i++) { if (arr[i] == ele) { return i; } } return -1;} // Return the minimum number// of swaps required to sort the arrayint minSwaps(vector<int> arr, int N){ int ans = 0; vector<int> temp(arr.begin(),arr.end()); sort(temp.begin(),temp.end()); for(int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans;} // Driver Codeint main(){ vector<int> a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n);} // This code is contributed by mohit kumar 29",
"e": 45249,
"s": 44013,
"text": null
},
{
"code": "// Java program to find// minimum number of swaps// required to sort an arrayimport java.util.*;import java.io.*; class GfG{ // Return the minimum number // of swaps required to sort the array public int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = Arrays.copyOfRange(arr, 0, N); Arrays.sort(temp); for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public int indexOf(int[] arr, int ele) { for (int i = 0; i < arr.length; i++) { if (arr[i] == ele) { return i; } } return -1; }}// Driver classclass Main{ // Driver program to test // the above function public static void main(String[] args) throws Exception { int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.length; // Output will be 5 System.out.println(new GfG().minSwaps(a, n)); }}// This code is contributed by Satvik Nema",
"e": 46812,
"s": 45249,
"text": null
},
{
"code": "# Python3 program to find#minimum number of swaps# required to sort an array # Return the minimum number# of swaps required to sort# the arraydef minSwaps(arr, N): ans = 0 temp = arr.copy() temp.sort() for i in range(N): # This is checking whether # the current element is # at the right place or not if (arr[i] != temp[i]): ans += 1 # Swap the current element # with the right index # so that arr[0] to arr[i] # is sorted swap(arr, i, indexOf(arr, temp[i])) return ans def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp def indexOf(arr, ele): for i in range(len(arr)): if (arr[i] == ele): return i return -1 # Driver codeif __name__ == \"__main__\": a = [101, 758, 315, 730, 472, 619, 460, 479] n = len(a) # Output will be 5 print(minSwaps(a, n)) # This code is contributed by Chitranayal",
"e": 47851,
"s": 46812,
"text": null
},
{
"code": "// C# program to find// minimum number of swaps// required to sort an arrayusing System;public class GFG{ // Return the minimum number // of swaps required to sort the array static int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = new int[N]; Array.Copy(arr, temp, N); Array.Sort(temp); for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int indexOf(int[] arr, int ele) { for (int i = 0; i < arr.Length; i++) { if (arr[i] == ele) { return i; } } return -1; } // Driver program to test // the above function static public void Main (){ int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.Length; // Output will be 5 Console.WriteLine(minSwaps(a, n)); }} // This code is contributed by rag2127",
"e": 49317,
"s": 47851,
"text": null
},
{
"code": "<script>// Javascript program to find// minimum number of swaps// required to sort an array // Return the minimum number // of swaps required to sort the array function minSwaps(arr,N) { let ans = 0; let temp = [...arr]; temp.sort(function(a,b){return a-b;}); for (let i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } function swap(arr,i,j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } function indexOf(arr,ele) { for (let i = 0; i < arr.length; i++) { if (arr[i] == ele) { return i; } } return -1; } // Driver class let a=[101, 758, 315, 730, 472, 619, 460, 479 ]; let n = a.length; document.write(minSwaps(a, n)); // This code is contributed by unknown2108</script>",
"e": 50609,
"s": 49317,
"text": null
},
{
"code": null,
"e": 50617,
"s": 50609,
"text": "Output:"
},
{
"code": null,
"e": 50619,
"s": 50617,
"text": "5"
},
{
"code": null,
"e": 50665,
"s": 50619,
"text": "Time Complexity: O(n*n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 50964,
"s": 50665,
"text": "We can still improve the complexity by using a hashmap. The main operation here is the indexOf method inside the loop, which costs us n*n. We can improve this section to O(n), by using a hashmap to store the indexes. Still, we use the sort method, so the complexity cannot improve beyond O(n Log n)"
},
{
"code": null,
"e": 50986,
"s": 50964,
"text": "Method using HashMap:"
},
{
"code": null,
"e": 51272,
"s": 50986,
"text": "Same as before, make a new array (called temp), which is the sorted form of the input array. We know that we need to transform the input array to the new array (temp) in the minimum number of swaps. Make a map that stores the elements and their corresponding index, of the input array."
},
{
"code": null,
"e": 51360,
"s": 51272,
"text": "So at each i starting from 0 to N in the given array, where N is the size of the array:"
},
{
"code": null,
"e": 51435,
"s": 51360,
"text": "1. If i is not in its correct position according to the sorted array, then"
},
{
"code": null,
"e": 51647,
"s": 51435,
"text": "2. We will fill this position with the correct element from the hashmap we built earlier. We know the correct element which should come here is temp[i], so we look up the index of this element from the hashmap. "
},
{
"code": null,
"e": 51811,
"s": 51647,
"text": "3. After swapping the required elements, we update the content of the hashmap accordingly, as temp[i] to the ith position, and arr[i] to where temp[i] was earlier."
},
{
"code": null,
"e": 51862,
"s": 51811,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 51866,
"s": 51862,
"text": "C++"
},
{
"code": null,
"e": 51871,
"s": 51866,
"text": "Java"
},
{
"code": null,
"e": 51879,
"s": 51871,
"text": "Python3"
},
{
"code": null,
"e": 51882,
"s": 51879,
"text": "C#"
},
{
"code": null,
"e": 51893,
"s": 51882,
"text": "Javascript"
},
{
"code": "// C++ program to find// minimum number of swaps// required to sort an array#include<bits/stdc++.h>using namespace std; void swap(vector<int> &arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;}// Return the minimum number// of swaps required to sort// the arrayint minSwaps(vector<int>arr, int N){ int ans = 0; vector<int>temp = arr; // Hashmap which stores the // indexes of the input array map <int, int> h; sort(temp.begin(), temp.end()); for (int i = 0; i < N; i++) { h[arr[i]] = i; } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h[temp[i]]); // Update the indexes in // the hashmap accordingly h[init] = h[temp[i]]; h[temp[i]] = i; } } return ans;} // Driver classint main(){ // Driver program to // test the above function vector <int> a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n);} // This code is contributed by Stream_Cipher",
"e": 53189,
"s": 51893,
"text": null
},
{
"code": "// Java program to find// minimum number of swaps// required to sort an arrayimport java.util.*;import java.io.*; class GfG{ // Return the minimum number // of swaps required to sort the array public int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = Arrays.copyOfRange(arr, 0, N); // Hashmap which stores the // indexes of the input array HashMap<Integer, Integer> h = new HashMap<Integer, Integer>(); Arrays.sort(temp); for (int i = 0; i < N; i++) { h.put(arr[i], i); } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h.get(temp[i])); // Update the indexes in // the hashmap accordingly h.put(init, h.get(temp[i])); h.put(temp[i], i); } } return ans; } public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }} // Driver classclass Main{ // Driver program to test the above function public static void main(String[] args) throws Exception { int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.length; // Output will be 5 System.out.println(new GfG().minSwaps(a, n)); }}// This code is contributed by Satvik Nema",
"e": 54962,
"s": 53189,
"text": null
},
{
"code": "# Python3 program to find# minimum number of swaps# required to sort an array # Return the minimum number# of swaps required to sort# the arraydef minSwap(arr, n): ans = 0 temp = arr.copy() # Dictionary which stores the # indexes of the input array h = {} temp.sort() for i in range(n): #h.[arr[i] h[arr[i]] = i init = 0 for i in range(n): # This is checking whether # the current element is # at the right place or not if (arr[i] != temp[i]): ans += 1 init = arr[i] # If not, swap this element # with the index of the # element which should come here arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i] # Update the indexes in # the hashmap accordingly h[init] = h[temp[i]] h[temp[i]] = i return ans # Driver codea = [ 101, 758, 315, 730, 472, 619, 460, 479 ]n = len(a) # Output will be 5print(minSwap(a, n)) # This code is contributed by avanitrachhadiya2155",
"e": 56063,
"s": 54962,
"text": null
},
{
"code": "// C# program to find// minimum number of swaps// required to sort an arrayusing System;using System.Collections.Generic;using System.Linq;public class GfG { // Return the minimum number // of swaps required to sort the array public int minSwaps(int[] arr, int N) { int ans = 0; int[] temp = new int[N]; arr.CopyTo(temp,0); // Hashmap which stores the // indexes of the input array Dictionary<int, int> h = new Dictionary<int, int>(); Array.Sort(temp); for (int i = 0; i < N; i++) { h.Add(arr[i], i); } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h[temp[i]]); // Update the indexes in // the hashmap accordingly h[init]= h[temp[i]]; h[temp[i]]= i; } } return ans; } public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }} // Driver classpublic class GFG { public static void Main(String[] args) { int[] a = { 101, 758, 315, 730, 472, 619, 460, 479 }; int n = a.Length; // Output will be 5 Console.WriteLine(new GfG().minSwaps(a, n)); }} // This code is contributed by Rajput-Ji",
"e": 57484,
"s": 56063,
"text": null
},
{
"code": "<script> // JavaScript program to find// minimum number of swaps// required to sort an arrayfunction swap(arr, i, j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} // Return the minimum number// of swaps required to sort// the arrayfunction minSwaps(arr,N){ let ans = 0; let temp = arr.slice(); // Hashmap which stores the // indexes of the input array let h = new Map(); temp.sort(); for (let i = 0; i < N; i++) { h.set(arr[i], i); } for (let i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; let init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h.get(temp[i])); // Update the indexes in // the hashmap accordingly h.set(init,h.get(temp[i])); h.set(temp[i],i); } } return ans;} // Driver class // Driver program to // test the above functionlet a = [101, 758, 315, 730, 472, 619, 460, 479];let n = a.length; // Output will be 5document.write(minSwaps(a, n)); // This code is contributed by shinjanpatra </script>",
"e": 58656,
"s": 57484,
"text": null
},
{
"code": null,
"e": 58664,
"s": 58656,
"text": "Output:"
},
{
"code": null,
"e": 58666,
"s": 58664,
"text": "5"
},
{
"code": null,
"e": 58716,
"s": 58666,
"text": "Time Complexity: O(n Log n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 58795,
"s": 58716,
"text": "Related Article : Number of swaps to sort when only adjacent swapping allowed "
},
{
"code": null,
"e": 59092,
"s": 58795,
"text": "This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 59103,
"s": 59092,
"text": "dharan1011"
},
{
"code": null,
"e": 59115,
"s": 59103,
"text": "prem_ukkoji"
},
{
"code": null,
"e": 59127,
"s": 59115,
"text": "EeshwaraSai"
},
{
"code": null,
"e": 59138,
"s": 59127,
"text": "SatvikNema"
},
{
"code": null,
"e": 59144,
"s": 59138,
"text": "ukasp"
},
{
"code": null,
"e": 59158,
"s": 59144,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 59179,
"s": 59158,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 59187,
"s": 59179,
"text": "rag2127"
},
{
"code": null,
"e": 59202,
"s": 59187,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 59214,
"s": 59202,
"text": "unknown2108"
},
{
"code": null,
"e": 59229,
"s": 59214,
"text": "Johari Saurabh"
},
{
"code": null,
"e": 59236,
"s": 59229,
"text": "ab2127"
},
{
"code": null,
"e": 59250,
"s": 59236,
"text": "GauravRajput1"
},
{
"code": null,
"e": 59260,
"s": 59250,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 59273,
"s": 59260,
"text": "harshalkhond"
},
{
"code": null,
"e": 59286,
"s": 59273,
"text": "shinjanpatra"
},
{
"code": null,
"e": 59299,
"s": 59286,
"text": "simmytarika5"
},
{
"code": null,
"e": 59306,
"s": 59299,
"text": "Arrays"
},
{
"code": null,
"e": 59312,
"s": 59306,
"text": "Graph"
},
{
"code": null,
"e": 59320,
"s": 59312,
"text": "Sorting"
},
{
"code": null,
"e": 59327,
"s": 59320,
"text": "Arrays"
},
{
"code": null,
"e": 59335,
"s": 59327,
"text": "Sorting"
},
{
"code": null,
"e": 59341,
"s": 59335,
"text": "Graph"
},
{
"code": null,
"e": 59439,
"s": 59341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 59462,
"s": 59439,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 59483,
"s": 59462,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 59531,
"s": 59483,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 59585,
"s": 59531,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 59625,
"s": 59585,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 59665,
"s": 59625,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 59703,
"s": 59665,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 59754,
"s": 59703,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 59812,
"s": 59754,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
How to use Zoom Component in ReactJS ? - GeeksforGeeks
|
22 Feb, 2021
Zoom Component adds a Zoom animation to a child element or component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Zoom Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure:
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Zoom from '@material-ui/core/Zoom'; export default function App() { const [isChecked, setIsChecked] = React.useState(false); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Zoom Component in ReactJS?</h4> <FormControlLabel control={<Switch checked={isChecked} onChange={() => { setIsChecked((prev) => !prev); }} />} label="Toggle me to see Zoom Effect" /> <div style={{ display: 'flex' }}> <Zoom in={isChecked} style={{ transitionDelay:'100ms'}} > <Paper elevation={5} style={{ margin: 5 }} > <svg style={{ width: 100, height: 100 }}> <polygon points="0,50 40,0,50,90" style={{ fill: 'red', stroke: 'dimgrey', strokeWidth: 1, }} /> </svg> </Paper> </Zoom> </div> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/transitions/#zoom
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 26305,
"s": 26071,
"text": "Zoom Component adds a Zoom animation to a child element or component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Zoom Component in ReactJS using the following approach."
},
{
"code": null,
"e": 26355,
"s": 26305,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26419,
"s": 26355,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 26451,
"s": 26419,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26551,
"s": 26451,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 26565,
"s": 26551,
"text": "cd foldername"
},
{
"code": null,
"e": 26674,
"s": 26565,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command."
},
{
"code": null,
"e": 26704,
"s": 26674,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 26724,
"s": 26704,
"text": "Project Structure: "
},
{
"code": null,
"e": 26742,
"s": 26724,
"text": "Project Structure"
},
{
"code": null,
"e": 26873,
"s": 26742,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. "
},
{
"code": null,
"e": 26880,
"s": 26873,
"text": "App.js"
},
{
"code": "import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Zoom from '@material-ui/core/Zoom'; export default function App() { const [isChecked, setIsChecked] = React.useState(false); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Zoom Component in ReactJS?</h4> <FormControlLabel control={<Switch checked={isChecked} onChange={() => { setIsChecked((prev) => !prev); }} />} label=\"Toggle me to see Zoom Effect\" /> <div style={{ display: 'flex' }}> <Zoom in={isChecked} style={{ transitionDelay:'100ms'}} > <Paper elevation={5} style={{ margin: 5 }} > <svg style={{ width: 100, height: 100 }}> <polygon points=\"0,50 40,0,50,90\" style={{ fill: 'red', stroke: 'dimgrey', strokeWidth: 1, }} /> </svg> </Paper> </Zoom> </div> </div> );}",
"e": 28022,
"s": 26880,
"text": null
},
{
"code": null,
"e": 28135,
"s": 28022,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 28145,
"s": 28135,
"text": "npm start"
},
{
"code": null,
"e": 28244,
"s": 28145,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 28308,
"s": 28244,
"text": "Reference: https://material-ui.com/components/transitions/#zoom"
},
{
"code": null,
"e": 28320,
"s": 28308,
"text": "Material-UI"
},
{
"code": null,
"e": 28336,
"s": 28320,
"text": "React-Questions"
},
{
"code": null,
"e": 28344,
"s": 28336,
"text": "ReactJS"
},
{
"code": null,
"e": 28361,
"s": 28344,
"text": "Web Technologies"
},
{
"code": null,
"e": 28459,
"s": 28361,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28486,
"s": 28459,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 28528,
"s": 28486,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28566,
"s": 28528,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 28601,
"s": 28566,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28659,
"s": 28601,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28699,
"s": 28659,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28732,
"s": 28699,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28777,
"s": 28732,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28827,
"s": 28777,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
What does immutable mean? Which Python types are mutable and which are not?
|
In Python, there are two types of Objects.
Mutable Object
Immutable Object
Mutable: Mutable objects are modified, (i.e) objects are a changeable list, set, dict, etc are mutable.
mutable objects are easy to change.
list =["Tutorials ","Point", "Pvt","Ltd"]
list[2]= 'Tutorix'
list
['Tutorials ', 'Point', 'Tutorix', 'Ltd']
list=['Car','Bike','Scooty','Bus','Metro']
list[4]= 'Bicycle'
list
['Car', 'Bike', 'Scooty', 'Bus', 'Bicycle']
Immutable: immutable objects are not modified (i.e) not changeable int, float, bool, str, tuple, Unicode, etc ... are immutable. immutable objects are expensive and difficult to change. a tuple is enclosed within the parenthesis tuples are immutable and can't be changed.
tuple=('1','2','Python','Perl')
tuple
('1', '2', 'Python', 'Perl')
tuple=('1','2','Python','Perl')
tuple[4]='2019'
tuple
TypeError Traceback (most recent call last)
in
1 tuple=('1','2','Python','Perl')
----> 2 tuple[4]='2019'
3 tuple
TypeError: 'tuple' object does not support item assignment
tuple object cant be changed by seeing above output you get a clear understanding
|
[
{
"code": null,
"e": 1105,
"s": 1062,
"text": "In Python, there are two types of Objects."
},
{
"code": null,
"e": 1120,
"s": 1105,
"text": "Mutable Object"
},
{
"code": null,
"e": 1137,
"s": 1120,
"text": "Immutable Object"
},
{
"code": null,
"e": 1241,
"s": 1137,
"text": "Mutable: Mutable objects are modified, (i.e) objects are a changeable list, set, dict, etc are mutable."
},
{
"code": null,
"e": 1277,
"s": 1241,
"text": "mutable objects are easy to change."
},
{
"code": null,
"e": 1343,
"s": 1277,
"text": "list =[\"Tutorials \",\"Point\", \"Pvt\",\"Ltd\"]\nlist[2]= 'Tutorix'\nlist"
},
{
"code": null,
"e": 1386,
"s": 1343,
"text": "['Tutorials ', 'Point', 'Tutorix', 'Ltd']\n"
},
{
"code": null,
"e": 1453,
"s": 1386,
"text": "list=['Car','Bike','Scooty','Bus','Metro']\nlist[4]= 'Bicycle'\nlist"
},
{
"code": null,
"e": 1498,
"s": 1453,
"text": "['Car', 'Bike', 'Scooty', 'Bus', 'Bicycle']\n"
},
{
"code": null,
"e": 1770,
"s": 1498,
"text": "Immutable: immutable objects are not modified (i.e) not changeable int, float, bool, str, tuple, Unicode, etc ... are immutable. immutable objects are expensive and difficult to change. a tuple is enclosed within the parenthesis tuples are immutable and can't be changed."
},
{
"code": null,
"e": 1808,
"s": 1770,
"text": "tuple=('1','2','Python','Perl')\ntuple"
},
{
"code": null,
"e": 1838,
"s": 1808,
"text": "('1', '2', 'Python', 'Perl')\n"
},
{
"code": null,
"e": 1892,
"s": 1838,
"text": "tuple=('1','2','Python','Perl')\ntuple[4]='2019'\ntuple"
},
{
"code": null,
"e": 2064,
"s": 1892,
"text": "TypeError Traceback (most recent call last)\nin\n1 tuple=('1','2','Python','Perl')\n----> 2 tuple[4]='2019'\n3 tuple\nTypeError: 'tuple' object does not support item assignment"
},
{
"code": null,
"e": 2146,
"s": 2064,
"text": "tuple object cant be changed by seeing above output you get a clear understanding"
}
] |
How to generate Unique ID of device for iPhone/iPad using Swift?
|
UDID(Unique Device Identifier) − A sequence of 40 hexadecimal characters that uniquely identify an iOS device.
Since from iOS 5, Apple has deprecated the UIDevice unique identifier, that means the traditional way of getting the unique id. Apple removed the truly unique identifier and introduced an identifier for each vendor i.e UUID that's the same for all apps for a given developer for each user, but varies between developers and between devices.
Apple has defined an instance property identifier for the vendor, which is an alphanumeric string that uniquely identifies a device to the app’s vendor.
You can read more about it here: https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor
So we will see how we can get, Copy the below code in viewDidLoad method,
override func viewDidLoad() {
super.viewDidLoad()
guard let deviceID = UIDevice.current.identifierForVendor?.uuidString else {
return
}
print(deviceID) // 7ABAB8B5-E805-437F-9D6C-5448BB19AEA5
}
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "UDID(Unique Device Identifier) − A sequence of 40 hexadecimal characters that uniquely identify an iOS device."
},
{
"code": null,
"e": 1514,
"s": 1173,
"text": "Since from iOS 5, Apple has deprecated the UIDevice unique identifier, that means the traditional way of getting the unique id. Apple removed the truly unique identifier and introduced an identifier for each vendor i.e UUID that's the same for all apps for a given developer for each user, but varies between developers and between devices."
},
{
"code": null,
"e": 1667,
"s": 1514,
"text": "Apple has defined an instance property identifier for the vendor, which is an alphanumeric string that uniquely identifies a device to the app’s vendor."
},
{
"code": null,
"e": 1785,
"s": 1667,
"text": "You can read more about it here: https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor"
},
{
"code": null,
"e": 1859,
"s": 1785,
"text": "So we will see how we can get, Copy the below code in viewDidLoad method,"
},
{
"code": null,
"e": 2071,
"s": 1859,
"text": "override func viewDidLoad() {\n super.viewDidLoad()\n guard let deviceID = UIDevice.current.identifierForVendor?.uuidString else {\n return\n }\n print(deviceID) // 7ABAB8B5-E805-437F-9D6C-5448BB19AEA5\n}"
}
] |
How do you create a legend for a contour plot in Matplotlib?
|
To create a legend for a contour plot in matplotlib, we can take the following steps−
Create x, y and z data points to plot the contour function.
To create a 3D filled contour plot, we can use contourf() method with x, y, z and different levels.
Make a list of rectangle with the returned contour signature collection and set face color
Now, place the legend in the plot using proxy (of step 3) and different labels.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x, y = np.meshgrid(np.arange(10), np.arange(10))
z = np.tan(x ** 2 + y ** 2)
cs = plt.contourf(x, y, z, levels=[2, 3, 4, 6])
proxy = [plt.Rectangle((1, 1), 2, 2, fc=pc.get_facecolor()[0]) for pc in
cs.collections]
plt.legend(proxy, ["C1", "C2", "C3"])
plt.show()
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To create a legend for a contour plot in matplotlib, we can take the following steps−"
},
{
"code": null,
"e": 1208,
"s": 1148,
"text": "Create x, y and z data points to plot the contour function."
},
{
"code": null,
"e": 1308,
"s": 1208,
"text": "To create a 3D filled contour plot, we can use contourf() method with x, y, z and different levels."
},
{
"code": null,
"e": 1399,
"s": 1308,
"text": "Make a list of rectangle with the returned contour signature collection and set face color"
},
{
"code": null,
"e": 1479,
"s": 1399,
"text": "Now, place the legend in the plot using proxy (of step 3) and different labels."
},
{
"code": null,
"e": 1521,
"s": 1479,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1927,
"s": 1521,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx, y = np.meshgrid(np.arange(10), np.arange(10))\nz = np.tan(x ** 2 + y ** 2)\ncs = plt.contourf(x, y, z, levels=[2, 3, 4, 6])\nproxy = [plt.Rectangle((1, 1), 2, 2, fc=pc.get_facecolor()[0]) for pc in\ncs.collections]\nplt.legend(proxy, [\"C1\", \"C2\", \"C3\"])\nplt.show()"
}
] |
Display Content on hovering Card using CSS - GeeksforGeeks
|
01 Sep, 2021
In this article, we will see how we can create a card which displays content on hovering using the hover property using HTML and CSS.
HTML Code: In this section, we will create the structure of our HTML card.
Create a “div” with class name “card”.Create another “div” inside the main “div” with class name “card__inner”.Add heading “h2” and paragraph inside the second “div” with some random content.
Create a “div” with class name “card”.
Create another “div” inside the main “div” with class name “card__inner”.
Add heading “h2” and paragraph inside the second “div” with some random content.
HTML
<!DOCTYPE html><html> <body> <!-- div with class which will act as a container for us --> <div class="card"> <!-- Content of card to be display on hovering --> <div class="card__inner"> <h2>GeeksforGeeks</h2> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </p> </div> </div></body> </html>
CSS Code: In this section, we will assign general properties to the element using CSS.
CSS
<style> /* Assigning general property to card */ .card { position: relative; width: 20rem; height: 30rem; background-size: cover; background-color: black; background-image: url('one.png'); border-radius: 20px; background-position: center center; overflow: hidden; } /* Assigning properties to inner content of card */ .card__inner { background-color: rgba(0, 0, 0, 0.9); color: #fff; position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 1; opacity: 0; padding: 2rem 1.3rem 2rem 2rem; transition: all 0.4s ease 0s; } /* On hovering card opacity of content must be 1*/ .card:hover .card__inner { opacity: 1; } /* General property for heading and paragraph*/ .card__inner h2 { margin-top: 1rem; } .card__inner p { overflow-y: scroll; height: 87%; padding-right: 1rem; font-weight: 200; line-height: 2.5rem; margin-top: 1.5rem; }</style>
Complete Code: In this section, we will combined the above two sections of code.
HTML
<!DOCTYPE html><html> <head> <style type="text/css"> /* Assigning general property to card */ .card { position: relative; width: 20rem; height: 30rem; background-size: cover; background-color: black; background-image: url('one.png'); border-radius: 20px; background-position: center center; overflow: hidden; } /* Assigning properties to inner content of card */ .card__inner { background-color: rgba(0, 0, 0, 0.9); color: #fff; position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 1; opacity: 0; padding: 2rem 1.3rem 2rem 2rem; transition: all 0.4s ease 0s; } /* On hovering card opacity of content must be 1*/ .card:hover .card__inner { opacity: 1; } /* General property for heading and paragraph*/ .card__inner h2 { margin-top: 1rem; } .card__inner p { overflow-y: scroll; height: 87%; padding-right: 1rem; font-weight: 200; line-height: 2.5rem; margin-top: 1.5rem; } </style></head> <body> <!-- div with class which will act as a container for us --> <div class="card"> <!-- Content of card to be display on hovering --> <div class="card__inner"> <h2>GeeksforGeeks</h2> <p> GeeksforGeeks: Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. It contains many free and premium contents. GeeksforGeeks: Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. It contains many free and premium contents. </p> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
kalrap615
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Primer CSS Flexbox Flex Direction
HTML Course | First Web Page | Printing Hello World
Design a web page using HTML and CSS
Search Bar using HTML, CSS and JavaScript
How to wrap the text around an image using HTML and CSS ?
How to set input type date in dd-mm-yyyy format using HTML ?
Form validation using HTML and JavaScript
HTML | <img> align Attribute
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 25119,
"s": 24985,
"text": "In this article, we will see how we can create a card which displays content on hovering using the hover property using HTML and CSS."
},
{
"code": null,
"e": 25196,
"s": 25119,
"text": "HTML Code: In this section, we will create the structure of our HTML card. "
},
{
"code": null,
"e": 25388,
"s": 25196,
"text": "Create a “div” with class name “card”.Create another “div” inside the main “div” with class name “card__inner”.Add heading “h2” and paragraph inside the second “div” with some random content."
},
{
"code": null,
"e": 25427,
"s": 25388,
"text": "Create a “div” with class name “card”."
},
{
"code": null,
"e": 25501,
"s": 25427,
"text": "Create another “div” inside the main “div” with class name “card__inner”."
},
{
"code": null,
"e": 25582,
"s": 25501,
"text": "Add heading “h2” and paragraph inside the second “div” with some random content."
},
{
"code": null,
"e": 25587,
"s": 25582,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <!-- div with class which will act as a container for us --> <div class=\"card\"> <!-- Content of card to be display on hovering --> <div class=\"card__inner\"> <h2>GeeksforGeeks</h2> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </p> </div> </div></body> </html>",
"e": 26150,
"s": 25587,
"text": null
},
{
"code": null,
"e": 26237,
"s": 26150,
"text": "CSS Code: In this section, we will assign general properties to the element using CSS."
},
{
"code": null,
"e": 26241,
"s": 26237,
"text": "CSS"
},
{
"code": "<style> /* Assigning general property to card */ .card { position: relative; width: 20rem; height: 30rem; background-size: cover; background-color: black; background-image: url('one.png'); border-radius: 20px; background-position: center center; overflow: hidden; } /* Assigning properties to inner content of card */ .card__inner { background-color: rgba(0, 0, 0, 0.9); color: #fff; position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 1; opacity: 0; padding: 2rem 1.3rem 2rem 2rem; transition: all 0.4s ease 0s; } /* On hovering card opacity of content must be 1*/ .card:hover .card__inner { opacity: 1; } /* General property for heading and paragraph*/ .card__inner h2 { margin-top: 1rem; } .card__inner p { overflow-y: scroll; height: 87%; padding-right: 1rem; font-weight: 200; line-height: 2.5rem; margin-top: 1.5rem; }</style>",
"e": 27365,
"s": 26241,
"text": null
},
{
"code": null,
"e": 27446,
"s": 27365,
"text": "Complete Code: In this section, we will combined the above two sections of code."
},
{
"code": null,
"e": 27451,
"s": 27446,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style type=\"text/css\"> /* Assigning general property to card */ .card { position: relative; width: 20rem; height: 30rem; background-size: cover; background-color: black; background-image: url('one.png'); border-radius: 20px; background-position: center center; overflow: hidden; } /* Assigning properties to inner content of card */ .card__inner { background-color: rgba(0, 0, 0, 0.9); color: #fff; position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 1; opacity: 0; padding: 2rem 1.3rem 2rem 2rem; transition: all 0.4s ease 0s; } /* On hovering card opacity of content must be 1*/ .card:hover .card__inner { opacity: 1; } /* General property for heading and paragraph*/ .card__inner h2 { margin-top: 1rem; } .card__inner p { overflow-y: scroll; height: 87%; padding-right: 1rem; font-weight: 200; line-height: 2.5rem; margin-top: 1.5rem; } </style></head> <body> <!-- div with class which will act as a container for us --> <div class=\"card\"> <!-- Content of card to be display on hovering --> <div class=\"card__inner\"> <h2>GeeksforGeeks</h2> <p> GeeksforGeeks: Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. It contains many free and premium contents. GeeksforGeeks: Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. It contains many free and premium contents. </p> </div> </div></body> </html>",
"e": 29719,
"s": 27451,
"text": null
},
{
"code": null,
"e": 29727,
"s": 29719,
"text": "Output:"
},
{
"code": null,
"e": 29864,
"s": 29727,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29874,
"s": 29864,
"text": "kalrap615"
},
{
"code": null,
"e": 29883,
"s": 29874,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29893,
"s": 29883,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29897,
"s": 29893,
"text": "CSS"
},
{
"code": null,
"e": 29902,
"s": 29897,
"text": "HTML"
},
{
"code": null,
"e": 29919,
"s": 29902,
"text": "Web Technologies"
},
{
"code": null,
"e": 29946,
"s": 29919,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29951,
"s": 29946,
"text": "HTML"
},
{
"code": null,
"e": 30049,
"s": 29951,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30058,
"s": 30049,
"text": "Comments"
},
{
"code": null,
"e": 30071,
"s": 30058,
"text": "Old Comments"
},
{
"code": null,
"e": 30105,
"s": 30071,
"text": "Primer CSS Flexbox Flex Direction"
},
{
"code": null,
"e": 30157,
"s": 30105,
"text": "HTML Course | First Web Page | Printing Hello World"
},
{
"code": null,
"e": 30194,
"s": 30157,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30236,
"s": 30194,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30294,
"s": 30236,
"text": "How to wrap the text around an image using HTML and CSS ?"
},
{
"code": null,
"e": 30355,
"s": 30294,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30397,
"s": 30355,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 30426,
"s": 30397,
"text": "HTML | <img> align Attribute"
}
] |
C Program - Sum of digits of given number till single digit - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
C Program to print the sum of digits till single digit.
#include<stdio.h>
int main(void)
{
long num;
int dig,sum;
printf("Enter any number : ");
scanf("%ld",&num);
printf("%ld-> ",num);
do
{
sum = 0;
while(num!=0)
{
dig=num%10;
sum+=dig;
num/=10;
}
printf("%d-> ",sum);
num=sum;
}while(num/10!=0);
return 0;
}
Output:
Enter any number : 586596
586596-> 39-> 12-> 3
Happy Learning 🙂
C Program – Armstrong numbers between given numbers
C Program – Print prime numbers between two numbers
C Program – Print the sum of digits of given number
Java program to find sum of digits
C Program – Given number is Even or Odd
C Program – Reverse of a number
C Program – Find GCD of two numbers
C Program to add elements of an array
C Program – Addition of two Matrices Example
C Program – Multiplication of two Matrices Example
C Program – Ways to Generate Fibonacci Series
C Program – Check a number is Palindrome or not
C Program – Find the factorial of given number
C Program – Find a number is prime or not
C Program – Find Largest and Smallest number in an Array
C Program – Armstrong numbers between given numbers
C Program – Print prime numbers between two numbers
C Program – Print the sum of digits of given number
Java program to find sum of digits
C Program – Given number is Even or Odd
C Program – Reverse of a number
C Program – Find GCD of two numbers
C Program to add elements of an array
C Program – Addition of two Matrices Example
C Program – Multiplication of two Matrices Example
C Program – Ways to Generate Fibonacci Series
C Program – Check a number is Palindrome or not
C Program – Find the factorial of given number
C Program – Find a number is prime or not
C Program – Find Largest and Smallest number in an Array
Δ
C – Introduction
C – Features
C – Variables & Keywords
C – Program Structure
C – Comment Lines & Tokens
C – Number System
C – Local and Global Variables
C – Scope & Lifetime of Variables
C – Data Types
C – Integer Data Types
C – Floating Data Types
C – Derived, Defined Data Types
C – Type Conversions
C – Arithmetic Operators
C – Bitwise Operators
C – Logical Operators
C – Comma and sizeof Operators
C – Operator Precedence and Associativity
C – Relational Operators
C Flow Control – if, if-else, nested if-else, if-else-if
C – Switch Case
C Iterative – for, while, dowhile loops
C Unconditional – break, continue, goto statements
C – Expressions and Statements
C – Header Files & Preprocessor Directives
C – One Dimensional Arrays
C – Multi Dimensional Arrays
C – Pointers Basics
C – Pointers with Arrays
C – Functions
C – How to Pass Arrays to Functions
C – Categories of Functions
C – User defined Functions
C – Formal and Actual Arguments
C – Recursion functions
C – Structures Part -1
C – Structures Part -2
C – Unions
C – File Handling
C – File Operations
C – Dynamic Memory Allocation
C Program – Fibonacci Series
C Program – Prime or Not
C Program – Factorial of Number
C Program – Even or Odd
C Program – Sum of digits till Single Digit
C Program – Sum of digits
C Program – Reverse of a number
C Program – Armstrong Numbers
C Program – Print prime Numbers
C Program – GCD of two Numbers
C Program – Number Palindrome or Not
C Program – Find Largest and Smallest number in an Array
C Program – Add elements of an Array
C Program – Addition of Matrices
C Program – Multiplication of Matrices
C Program – Reverse of an Array
C Program – Bubble Sort
C Program – Add and Sub without using + –
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 454,
"s": 398,
"text": "C Program to print the sum of digits till single digit."
},
{
"code": null,
"e": 855,
"s": 454,
"text": "#include<stdio.h> \nint main(void) \n{ \n long num; \n int dig,sum; \n printf(\"Enter any number : \"); \n scanf(\"%ld\",&num); \n printf(\"%ld-> \",num); \n do \n { \n sum = 0; \n while(num!=0) \n { \n dig=num%10; \n sum+=dig; \n num/=10; \n } \n printf(\"%d-> \",sum); \n num=sum; \n }while(num/10!=0); \n return 0; \n}"
},
{
"code": null,
"e": 863,
"s": 855,
"text": "Output:"
},
{
"code": null,
"e": 911,
"s": 863,
"text": "Enter any number : 586596\n586596-> 39-> 12-> 3\n"
},
{
"code": null,
"e": 928,
"s": 911,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 1603,
"s": 928,
"text": "\nC Program – Armstrong numbers between given numbers\nC Program – Print prime numbers between two numbers\nC Program – Print the sum of digits of given number\nJava program to find sum of digits\nC Program – Given number is Even or Odd\nC Program – Reverse of a number\nC Program – Find GCD of two numbers\nC Program to add elements of an array\nC Program – Addition of two Matrices Example\nC Program – Multiplication of two Matrices Example\nC Program – Ways to Generate Fibonacci Series\nC Program – Check a number is Palindrome or not\nC Program – Find the factorial of given number\nC Program – Find a number is prime or not\nC Program – Find Largest and Smallest number in an Array\n"
},
{
"code": null,
"e": 1655,
"s": 1603,
"text": "C Program – Armstrong numbers between given numbers"
},
{
"code": null,
"e": 1707,
"s": 1655,
"text": "C Program – Print prime numbers between two numbers"
},
{
"code": null,
"e": 1759,
"s": 1707,
"text": "C Program – Print the sum of digits of given number"
},
{
"code": null,
"e": 1794,
"s": 1759,
"text": "Java program to find sum of digits"
},
{
"code": null,
"e": 1834,
"s": 1794,
"text": "C Program – Given number is Even or Odd"
},
{
"code": null,
"e": 1866,
"s": 1834,
"text": "C Program – Reverse of a number"
},
{
"code": null,
"e": 1902,
"s": 1866,
"text": "C Program – Find GCD of two numbers"
},
{
"code": null,
"e": 1940,
"s": 1902,
"text": "C Program to add elements of an array"
},
{
"code": null,
"e": 1985,
"s": 1940,
"text": "C Program – Addition of two Matrices Example"
},
{
"code": null,
"e": 2036,
"s": 1985,
"text": "C Program – Multiplication of two Matrices Example"
},
{
"code": null,
"e": 2082,
"s": 2036,
"text": "C Program – Ways to Generate Fibonacci Series"
},
{
"code": null,
"e": 2130,
"s": 2082,
"text": "C Program – Check a number is Palindrome or not"
},
{
"code": null,
"e": 2177,
"s": 2130,
"text": "C Program – Find the factorial of given number"
},
{
"code": null,
"e": 2219,
"s": 2177,
"text": "C Program – Find a number is prime or not"
},
{
"code": null,
"e": 2276,
"s": 2219,
"text": "C Program – Find Largest and Smallest number in an Array"
},
{
"code": null,
"e": 2282,
"s": 2280,
"text": "Δ"
},
{
"code": null,
"e": 2300,
"s": 2282,
"text": " C – Introduction"
},
{
"code": null,
"e": 2314,
"s": 2300,
"text": " C – Features"
},
{
"code": null,
"e": 2340,
"s": 2314,
"text": " C – Variables & Keywords"
},
{
"code": null,
"e": 2363,
"s": 2340,
"text": " C – Program Structure"
},
{
"code": null,
"e": 2392,
"s": 2363,
"text": " C – Comment Lines & Tokens"
},
{
"code": null,
"e": 2411,
"s": 2392,
"text": " C – Number System"
},
{
"code": null,
"e": 2443,
"s": 2411,
"text": " C – Local and Global Variables"
},
{
"code": null,
"e": 2478,
"s": 2443,
"text": " C – Scope & Lifetime of Variables"
},
{
"code": null,
"e": 2494,
"s": 2478,
"text": " C – Data Types"
},
{
"code": null,
"e": 2518,
"s": 2494,
"text": " C – Integer Data Types"
},
{
"code": null,
"e": 2543,
"s": 2518,
"text": " C – Floating Data Types"
},
{
"code": null,
"e": 2576,
"s": 2543,
"text": " C – Derived, Defined Data Types"
},
{
"code": null,
"e": 2598,
"s": 2576,
"text": " C – Type Conversions"
},
{
"code": null,
"e": 2624,
"s": 2598,
"text": " C – Arithmetic Operators"
},
{
"code": null,
"e": 2647,
"s": 2624,
"text": " C – Bitwise Operators"
},
{
"code": null,
"e": 2670,
"s": 2647,
"text": " C – Logical Operators"
},
{
"code": null,
"e": 2703,
"s": 2670,
"text": " C – Comma and sizeof Operators"
},
{
"code": null,
"e": 2746,
"s": 2703,
"text": " C – Operator Precedence and Associativity"
},
{
"code": null,
"e": 2772,
"s": 2746,
"text": " C – Relational Operators"
},
{
"code": null,
"e": 2830,
"s": 2772,
"text": " C Flow Control – if, if-else, nested if-else, if-else-if"
},
{
"code": null,
"e": 2847,
"s": 2830,
"text": " C – Switch Case"
},
{
"code": null,
"e": 2888,
"s": 2847,
"text": " C Iterative – for, while, dowhile loops"
},
{
"code": null,
"e": 2940,
"s": 2888,
"text": " C Unconditional – break, continue, goto statements"
},
{
"code": null,
"e": 2972,
"s": 2940,
"text": " C – Expressions and Statements"
},
{
"code": null,
"e": 3016,
"s": 2972,
"text": " C – Header Files & Preprocessor Directives"
},
{
"code": null,
"e": 3044,
"s": 3016,
"text": " C – One Dimensional Arrays"
},
{
"code": null,
"e": 3074,
"s": 3044,
"text": " C – Multi Dimensional Arrays"
},
{
"code": null,
"e": 3095,
"s": 3074,
"text": " C – Pointers Basics"
},
{
"code": null,
"e": 3121,
"s": 3095,
"text": " C – Pointers with Arrays"
},
{
"code": null,
"e": 3136,
"s": 3121,
"text": " C – Functions"
},
{
"code": null,
"e": 3173,
"s": 3136,
"text": " C – How to Pass Arrays to Functions"
},
{
"code": null,
"e": 3202,
"s": 3173,
"text": " C – Categories of Functions"
},
{
"code": null,
"e": 3230,
"s": 3202,
"text": " C – User defined Functions"
},
{
"code": null,
"e": 3263,
"s": 3230,
"text": " C – Formal and Actual Arguments"
},
{
"code": null,
"e": 3288,
"s": 3263,
"text": " C – Recursion functions"
},
{
"code": null,
"e": 3312,
"s": 3288,
"text": " C – Structures Part -1"
},
{
"code": null,
"e": 3336,
"s": 3312,
"text": " C – Structures Part -2"
},
{
"code": null,
"e": 3348,
"s": 3336,
"text": " C – Unions"
},
{
"code": null,
"e": 3367,
"s": 3348,
"text": " C – File Handling"
},
{
"code": null,
"e": 3388,
"s": 3367,
"text": " C – File Operations"
},
{
"code": null,
"e": 3419,
"s": 3388,
"text": " C – Dynamic Memory Allocation"
},
{
"code": null,
"e": 3449,
"s": 3419,
"text": " C Program – Fibonacci Series"
},
{
"code": null,
"e": 3475,
"s": 3449,
"text": " C Program – Prime or Not"
},
{
"code": null,
"e": 3508,
"s": 3475,
"text": " C Program – Factorial of Number"
},
{
"code": null,
"e": 3533,
"s": 3508,
"text": " C Program – Even or Odd"
},
{
"code": null,
"e": 3578,
"s": 3533,
"text": " C Program – Sum of digits till Single Digit"
},
{
"code": null,
"e": 3605,
"s": 3578,
"text": " C Program – Sum of digits"
},
{
"code": null,
"e": 3638,
"s": 3605,
"text": " C Program – Reverse of a number"
},
{
"code": null,
"e": 3669,
"s": 3638,
"text": " C Program – Armstrong Numbers"
},
{
"code": null,
"e": 3702,
"s": 3669,
"text": " C Program – Print prime Numbers"
},
{
"code": null,
"e": 3734,
"s": 3702,
"text": " C Program – GCD of two Numbers"
},
{
"code": null,
"e": 3772,
"s": 3734,
"text": " C Program – Number Palindrome or Not"
},
{
"code": null,
"e": 3830,
"s": 3772,
"text": " C Program – Find Largest and Smallest number in an Array"
},
{
"code": null,
"e": 3868,
"s": 3830,
"text": " C Program – Add elements of an Array"
},
{
"code": null,
"e": 3902,
"s": 3868,
"text": " C Program – Addition of Matrices"
},
{
"code": null,
"e": 3942,
"s": 3902,
"text": " C Program – Multiplication of Matrices"
},
{
"code": null,
"e": 3975,
"s": 3942,
"text": " C Program – Reverse of an Array"
},
{
"code": null,
"e": 4000,
"s": 3975,
"text": " C Program – Bubble Sort"
}
] |
Simulating Monopoly: Finding the Best Properties Using MATLAB | by Jake Mitchell | Towards Data Science
|
With 40 spaces, and 28 different properties, Monopoly may seem completely random at first, but there are certain properties that can be more beneficial to you over the course of a game. I wanted to find which properties these were using a MATLAB simulation of 10,000,000 dice rolls.
I simulate two dice being rolled using a random number generator and then add the two values together. I then add that amount on to the current position of the player to get their new position. I also have a variable to track the amount of doubles in a row. If the player rolls 3 doubles in a row, they are sent to jail for speeding.
die1 = randi(6); % roll first diedie2 = randi(6); % roll second dieif die1 == die2 % if same valuedoubles = doubles + 1; % increase number of doubles in a rowelsedoubles = 0; % set doubles to 0 if different dice valuesend
What follows in the code is all of the special case situations. For example, if the position adds up to be greater than 40, it reverts it back to the starting spot as a reference since the board is a loop. A position value of 43 would be changed to 3. Also, if the player lands on position 31 (“go to jail” space) they are sent to position 11 (jail).
if doubles < 3 % if less than 3 doubles in a rowposition = position + die1 + die2; % finds new positionif position > 40 % if above 40position = position - 40; % reverts position back to starting position as a referencearound = around + 1; % indicates the player went around the boardendif position == 31 % if player lands on the "go to jail" spacelands(position) = lands(position) + 1; % indicates player landed on position 31position = 11; % sends player to jailend
Other special case examples are community chest spaces and chance spaces. Of the 16 community chest cards, only 1 changes the location of the player (go to jail). Of the 16 chance cards, 9 change the player’s location:
Go to Jail
Advance to Boardwalk
Advance to Illinois Ave
Advance to St. Charles Place
Advance to Reading Railroad
Advance to Nearest Railroad
Advance to Nearest Utility
Advance to GO
Go Back 3 Spaces
After every turn is over, the space that the player ended up on is tallied in an array of all 40 spots, and then each spot is divided by the total amount of simulations (10 million). This gives us a percent likelihood of all 40 spaces being landed on.
After 10,000,000 dice rolls, the likelihood of each space being landed on is shown below:
Shown below is the top 20 board spaces from the bar graph above:
While the amount of times a property is landed on does affect the benefit it will bring to you as a player, we also need to consider how much it costs to buy the property, and how much players will pay you every time they land on it.
The probabilities shown above can also be described as the chances of a player landing on that property after every roll. We can use that, along with the rent for every property, to find the expected amount of money you will make on every player’s dice roll if you own said property.
For example, Ventnor Ave (shown above) is at a 2.691% chance of being landed on every roll. The rent with no houses for Ventnor Ave is $22, which means that every roll results in an expected $0.59202 for the owner.
The revenue per roll is not the best thing to compare between properties because a property that costs more than Ventnor should yield more revenue, but this is not always the case. If we divide the initial cost of buying the property by the revenue per roll, we can find how many rolls it will take to break-even on a property. For example Ventnor costs $260 to buy, so the owner should expect to make all of that money back after 439.18 rolls. Properties that take less rolls to break-even would be considered better investments because you could start turning a profit before other players.
We also need to consider how building houses and hotels on properties affects the rolls per break-even. Below is a breakdown of each property on a Monopoly board, given it’s situation regarding houses and hotels (excluding railroads and utilities). The value in each cell represents to amount of rolls it will take on average to make back the money spent on the property.
As you can see, some properties are almost guaranteed to lose you money in the long run. Buying Mediterranean Ave and not putting any houses on it will certainly cost you money over the course of a game. It won’t be a significant amount (only $60 to buy), but it is still not the best purchase.
All properties without houses take an extraordinary amount of time to break-even, which is why buying houses and hotels is so important.
The plot above shows how buying at least 3 houses for every monopoly you own can greatly reduce the amount of rolls it takes to make your money back. Even the brown-colored properties (brown line above), which are a horrible investment at the start, can start to turn a profit over the span of a game with 3 or more houses on it.
Something else interesting to note is that as the properties get more expensive, the less change is seen between 3 houses, 4 houses, and a hotel. Take the light-blue and yellow properties for example:
Light-blue properties see a considerable drop between 3 and 4 houses, and between 4 houses and a hotel. The yellow properties show almost no change between the 3 rightmost columns. This means that it will take the same amount of time to make back the money spent on 3 houses as it does for 4, but the revenue after breaking-even will be bigger (for the more expensive properties).
But what about the railroads and utilities?
The railroads are shown below, with all the different permutations for which ones you own. The value in each cell represents to amount of rolls it will take on average to make back the money spent on the property or properties.
For ownership of just 1 railroad, it is best to own B&O, just because it gets landed on more. If you want to own 2, go for the Reading and B&O combination. For 3, look for Reading, Pennsylvania, and B&O. Overall, the best investment for the railroads is either getting 3 or all 4, just because as people start to build houses on their properties, your 1 or 2 railroads won’t be making nearly as much compared to earlier in the game.
As for utilities:
Owning the utilities early in the game is probably one of the best moves. Both have the lowest rolls per break-even compared to any other property without houses. However, just like the railroads, you can’t build houses on these, so as the game goes on, these become less and less useful. Even owning both utilities still puts them at the bottom, considering 21 of the 22 other properties have lower rolls per break-even with 3 houses.
The orange properties are the best spots in the game. The oranges are all within the best 5 properties with 3 houses, and are the top 3 locations for hotels. The orange properties New York Ave and Tennessee Ave place 3rd and 5th amongst the spots most landed on.
Boardwalk and Park Place (dark blues) are tricky ones. Boardwalk consistently places high on the list in terms of rolls per break-even, while Park Place is always near the bottom. This monopoly is a high-risk, high-reward option compared to the oranges.
The absolute worst group to put hotels on are definitely the greens. All 3 place in the bottom 5 in terms of rolls per break-even with hotels. They are also below-average in terms of likelihood of being landed on.
Railroads are only beneficial near the end of the game if you have 3 or all 4. If you can get them early and start breaking-even, then that is a great move. Utilities are the best properties until people start building houses. You can’t win with just utilities or railroads, so do not put all of your effort and money into them.
Overall, this simulation showed that there is some strategy that can be implemented into your next Monopoly game. If this type of content interests you, I recommend reading my other board game articles, I Taught a Machine How to Play Connect 4, and The Best and Worst Catan Board Setups.
|
[
{
"code": null,
"e": 455,
"s": 172,
"text": "With 40 spaces, and 28 different properties, Monopoly may seem completely random at first, but there are certain properties that can be more beneficial to you over the course of a game. I wanted to find which properties these were using a MATLAB simulation of 10,000,000 dice rolls."
},
{
"code": null,
"e": 789,
"s": 455,
"text": "I simulate two dice being rolled using a random number generator and then add the two values together. I then add that amount on to the current position of the player to get their new position. I also have a variable to track the amount of doubles in a row. If the player rolls 3 doubles in a row, they are sent to jail for speeding."
},
{
"code": null,
"e": 1011,
"s": 789,
"text": "die1 = randi(6); % roll first diedie2 = randi(6); % roll second dieif die1 == die2 % if same valuedoubles = doubles + 1; % increase number of doubles in a rowelsedoubles = 0; % set doubles to 0 if different dice valuesend"
},
{
"code": null,
"e": 1362,
"s": 1011,
"text": "What follows in the code is all of the special case situations. For example, if the position adds up to be greater than 40, it reverts it back to the starting spot as a reference since the board is a loop. A position value of 43 would be changed to 3. Also, if the player lands on position 31 (“go to jail” space) they are sent to position 11 (jail)."
},
{
"code": null,
"e": 1829,
"s": 1362,
"text": "if doubles < 3 % if less than 3 doubles in a rowposition = position + die1 + die2; % finds new positionif position > 40 % if above 40position = position - 40; % reverts position back to starting position as a referencearound = around + 1; % indicates the player went around the boardendif position == 31 % if player lands on the \"go to jail\" spacelands(position) = lands(position) + 1; % indicates player landed on position 31position = 11; % sends player to jailend"
},
{
"code": null,
"e": 2048,
"s": 1829,
"text": "Other special case examples are community chest spaces and chance spaces. Of the 16 community chest cards, only 1 changes the location of the player (go to jail). Of the 16 chance cards, 9 change the player’s location:"
},
{
"code": null,
"e": 2059,
"s": 2048,
"text": "Go to Jail"
},
{
"code": null,
"e": 2080,
"s": 2059,
"text": "Advance to Boardwalk"
},
{
"code": null,
"e": 2104,
"s": 2080,
"text": "Advance to Illinois Ave"
},
{
"code": null,
"e": 2133,
"s": 2104,
"text": "Advance to St. Charles Place"
},
{
"code": null,
"e": 2161,
"s": 2133,
"text": "Advance to Reading Railroad"
},
{
"code": null,
"e": 2189,
"s": 2161,
"text": "Advance to Nearest Railroad"
},
{
"code": null,
"e": 2216,
"s": 2189,
"text": "Advance to Nearest Utility"
},
{
"code": null,
"e": 2230,
"s": 2216,
"text": "Advance to GO"
},
{
"code": null,
"e": 2247,
"s": 2230,
"text": "Go Back 3 Spaces"
},
{
"code": null,
"e": 2499,
"s": 2247,
"text": "After every turn is over, the space that the player ended up on is tallied in an array of all 40 spots, and then each spot is divided by the total amount of simulations (10 million). This gives us a percent likelihood of all 40 spaces being landed on."
},
{
"code": null,
"e": 2589,
"s": 2499,
"text": "After 10,000,000 dice rolls, the likelihood of each space being landed on is shown below:"
},
{
"code": null,
"e": 2654,
"s": 2589,
"text": "Shown below is the top 20 board spaces from the bar graph above:"
},
{
"code": null,
"e": 2888,
"s": 2654,
"text": "While the amount of times a property is landed on does affect the benefit it will bring to you as a player, we also need to consider how much it costs to buy the property, and how much players will pay you every time they land on it."
},
{
"code": null,
"e": 3172,
"s": 2888,
"text": "The probabilities shown above can also be described as the chances of a player landing on that property after every roll. We can use that, along with the rent for every property, to find the expected amount of money you will make on every player’s dice roll if you own said property."
},
{
"code": null,
"e": 3387,
"s": 3172,
"text": "For example, Ventnor Ave (shown above) is at a 2.691% chance of being landed on every roll. The rent with no houses for Ventnor Ave is $22, which means that every roll results in an expected $0.59202 for the owner."
},
{
"code": null,
"e": 3980,
"s": 3387,
"text": "The revenue per roll is not the best thing to compare between properties because a property that costs more than Ventnor should yield more revenue, but this is not always the case. If we divide the initial cost of buying the property by the revenue per roll, we can find how many rolls it will take to break-even on a property. For example Ventnor costs $260 to buy, so the owner should expect to make all of that money back after 439.18 rolls. Properties that take less rolls to break-even would be considered better investments because you could start turning a profit before other players."
},
{
"code": null,
"e": 4352,
"s": 3980,
"text": "We also need to consider how building houses and hotels on properties affects the rolls per break-even. Below is a breakdown of each property on a Monopoly board, given it’s situation regarding houses and hotels (excluding railroads and utilities). The value in each cell represents to amount of rolls it will take on average to make back the money spent on the property."
},
{
"code": null,
"e": 4647,
"s": 4352,
"text": "As you can see, some properties are almost guaranteed to lose you money in the long run. Buying Mediterranean Ave and not putting any houses on it will certainly cost you money over the course of a game. It won’t be a significant amount (only $60 to buy), but it is still not the best purchase."
},
{
"code": null,
"e": 4784,
"s": 4647,
"text": "All properties without houses take an extraordinary amount of time to break-even, which is why buying houses and hotels is so important."
},
{
"code": null,
"e": 5114,
"s": 4784,
"text": "The plot above shows how buying at least 3 houses for every monopoly you own can greatly reduce the amount of rolls it takes to make your money back. Even the brown-colored properties (brown line above), which are a horrible investment at the start, can start to turn a profit over the span of a game with 3 or more houses on it."
},
{
"code": null,
"e": 5315,
"s": 5114,
"text": "Something else interesting to note is that as the properties get more expensive, the less change is seen between 3 houses, 4 houses, and a hotel. Take the light-blue and yellow properties for example:"
},
{
"code": null,
"e": 5696,
"s": 5315,
"text": "Light-blue properties see a considerable drop between 3 and 4 houses, and between 4 houses and a hotel. The yellow properties show almost no change between the 3 rightmost columns. This means that it will take the same amount of time to make back the money spent on 3 houses as it does for 4, but the revenue after breaking-even will be bigger (for the more expensive properties)."
},
{
"code": null,
"e": 5740,
"s": 5696,
"text": "But what about the railroads and utilities?"
},
{
"code": null,
"e": 5968,
"s": 5740,
"text": "The railroads are shown below, with all the different permutations for which ones you own. The value in each cell represents to amount of rolls it will take on average to make back the money spent on the property or properties."
},
{
"code": null,
"e": 6401,
"s": 5968,
"text": "For ownership of just 1 railroad, it is best to own B&O, just because it gets landed on more. If you want to own 2, go for the Reading and B&O combination. For 3, look for Reading, Pennsylvania, and B&O. Overall, the best investment for the railroads is either getting 3 or all 4, just because as people start to build houses on their properties, your 1 or 2 railroads won’t be making nearly as much compared to earlier in the game."
},
{
"code": null,
"e": 6419,
"s": 6401,
"text": "As for utilities:"
},
{
"code": null,
"e": 6855,
"s": 6419,
"text": "Owning the utilities early in the game is probably one of the best moves. Both have the lowest rolls per break-even compared to any other property without houses. However, just like the railroads, you can’t build houses on these, so as the game goes on, these become less and less useful. Even owning both utilities still puts them at the bottom, considering 21 of the 22 other properties have lower rolls per break-even with 3 houses."
},
{
"code": null,
"e": 7118,
"s": 6855,
"text": "The orange properties are the best spots in the game. The oranges are all within the best 5 properties with 3 houses, and are the top 3 locations for hotels. The orange properties New York Ave and Tennessee Ave place 3rd and 5th amongst the spots most landed on."
},
{
"code": null,
"e": 7372,
"s": 7118,
"text": "Boardwalk and Park Place (dark blues) are tricky ones. Boardwalk consistently places high on the list in terms of rolls per break-even, while Park Place is always near the bottom. This monopoly is a high-risk, high-reward option compared to the oranges."
},
{
"code": null,
"e": 7586,
"s": 7372,
"text": "The absolute worst group to put hotels on are definitely the greens. All 3 place in the bottom 5 in terms of rolls per break-even with hotels. They are also below-average in terms of likelihood of being landed on."
},
{
"code": null,
"e": 7915,
"s": 7586,
"text": "Railroads are only beneficial near the end of the game if you have 3 or all 4. If you can get them early and start breaking-even, then that is a great move. Utilities are the best properties until people start building houses. You can’t win with just utilities or railroads, so do not put all of your effort and money into them."
}
] |
Tcl - Logical Operators
|
Following table shows all the logical operators supported by Tcl language. Assume variable A holds 1 and variable B holds 0, then −
Try the following example to understand all the logical operators available in Tcl language −
#!/usr/bin/tclsh
set a 5
set b 20
if { $a && $b } {
puts "Line 1 - Condition is true\n"
}
if { $a || $b } {
puts "Line 2 - Condition is true\n"
}
# lets change the value of a and b
set a 0
set b 10
if { $a && $b } {
puts "Line 3 - Condition is true\n"
} else {
puts "Line 3 - Condition is not true\n"
}
if { !($a && $b) } {
puts "Line 4 - Condition is true\n"
}
When you compile and execute the above program, it produces the following result −
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2333,
"s": 2201,
"text": "Following table shows all the logical operators supported by Tcl language. Assume variable A holds 1 and variable B holds 0, then −"
},
{
"code": null,
"e": 2427,
"s": 2333,
"text": "Try the following example to understand all the logical operators available in Tcl language −"
},
{
"code": null,
"e": 2812,
"s": 2427,
"text": "#!/usr/bin/tclsh\n\nset a 5\nset b 20\n\nif { $a && $b } {\n puts \"Line 1 - Condition is true\\n\"\n}\nif { $a || $b } {\n puts \"Line 2 - Condition is true\\n\"\n}\n# lets change the value of a and b \nset a 0\nset b 10\nif { $a && $b } {\n puts \"Line 3 - Condition is true\\n\"\n} else {\n puts \"Line 3 - Condition is not true\\n\" \n}\nif { !($a && $b) } {\n puts \"Line 4 - Condition is true\\n\" \n}"
},
{
"code": null,
"e": 2895,
"s": 2812,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 3011,
"s": 2895,
"text": "Line 1 - Condition is true\n\nLine 2 - Condition is true\n\nLine 3 - Condition is not true\n\nLine 4 - Condition is true\n"
},
{
"code": null,
"e": 3018,
"s": 3011,
"text": " Print"
},
{
"code": null,
"e": 3029,
"s": 3018,
"text": " Add Notes"
}
] |
Remove Duplicates from Sorted Array II in C++
|
Suppose we have a sorted array nums, we have to remove the duplicates in-place such that duplicates elements will appear at most twice and return the new length. To do this task we cannot take extra space. We have to solve this with O(1) amount of space. For example, if the array is like [0,0,0,1,1,1,1,2,3,3], then the output will be [0,0,1,1,2,3,3], its length is 7
Let us see the steps −
len := 2 and n := size of array
if n <= 2, then return n
for i := 2 to nif nums[i] != nums[len - 2] or nums[i] != nums[len - 1]nums[len] := nums[i], and increase len by 1
if nums[i] != nums[len - 2] or nums[i] != nums[len - 1]nums[len] := nums[i], and increase len by 1
nums[len] := nums[i], and increase len by 1
return len
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = 2;
int n = nums.size();
if(n <= 2)return n;
for(int i = 2; i < n; i++){
if( nums[i] != nums[len - 2] || nums[i] != nums[len - 1]){
nums[len] = nums[i];
len++;
}
}
return len;
}
};
main(){
Solution ob;
vector<int> v = {0,0,0,1,1,1,1,2,3,3};
cout << ob.removeDuplicates(v);
}
[0,0,0,1,1,1,1,2,3,3]
7
|
[
{
"code": null,
"e": 1431,
"s": 1062,
"text": "Suppose we have a sorted array nums, we have to remove the duplicates in-place such that duplicates elements will appear at most twice and return the new length. To do this task we cannot take extra space. We have to solve this with O(1) amount of space. For example, if the array is like [0,0,0,1,1,1,1,2,3,3], then the output will be [0,0,1,1,2,3,3], its length is 7"
},
{
"code": null,
"e": 1454,
"s": 1431,
"text": "Let us see the steps −"
},
{
"code": null,
"e": 1486,
"s": 1454,
"text": "len := 2 and n := size of array"
},
{
"code": null,
"e": 1511,
"s": 1486,
"text": "if n <= 2, then return n"
},
{
"code": null,
"e": 1625,
"s": 1511,
"text": "for i := 2 to nif nums[i] != nums[len - 2] or nums[i] != nums[len - 1]nums[len] := nums[i], and increase len by 1"
},
{
"code": null,
"e": 1724,
"s": 1625,
"text": "if nums[i] != nums[len - 2] or nums[i] != nums[len - 1]nums[len] := nums[i], and increase len by 1"
},
{
"code": null,
"e": 1768,
"s": 1724,
"text": "nums[len] := nums[i], and increase len by 1"
},
{
"code": null,
"e": 1779,
"s": 1768,
"text": "return len"
},
{
"code": null,
"e": 1849,
"s": 1779,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1860,
"s": 1849,
"text": " Live Demo"
},
{
"code": null,
"e": 2353,
"s": 1860,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int removeDuplicates(vector<int>& nums) {\n int len = 2;\n int n = nums.size();\n if(n <= 2)return n;\n for(int i = 2; i < n; i++){\n if( nums[i] != nums[len - 2] || nums[i] != nums[len - 1]){\n nums[len] = nums[i];\n len++;\n }\n }\n return len;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {0,0,0,1,1,1,1,2,3,3};\n cout << ob.removeDuplicates(v);\n}"
},
{
"code": null,
"e": 2375,
"s": 2353,
"text": "[0,0,0,1,1,1,1,2,3,3]"
},
{
"code": null,
"e": 2377,
"s": 2375,
"text": "7"
}
] |
Unix / Linux - User Administration
|
In this chapter, we will discuss in detail about user administration in Unix.
There are three types of accounts on a Unix system −
This is also called superuser and would have complete and unfettered control of the system. A superuser can run any commands without any restriction. This user should be assumed as a system administrator.
System accounts are those needed for the operation of system-specific components for example mail accounts and the sshd accounts. These accounts are usually needed for some specific function on your system, and any modifications to them could adversely affect the system.
User accounts provide interactive access to the system for users and groups of users. General users are typically assigned to these accounts and usually have limited access to critical system files and directories.
Unix supports a concept of Group Account which logically groups a number of accounts. Every account would be a part of another group account. A Unix group plays important role in handling file permissions and process management.
There are four main user administration files −
/etc/passwd − Keeps the user account and password information. This file holds the majority of information about accounts on the Unix system.
/etc/passwd − Keeps the user account and password information. This file holds the majority of information about accounts on the Unix system.
/etc/shadow − Holds the encrypted password of the corresponding account. Not all the systems support this file.
/etc/shadow − Holds the encrypted password of the corresponding account. Not all the systems support this file.
/etc/group − This file contains the group information for each account.
/etc/group − This file contains the group information for each account.
/etc/gshadow − This file contains secure group account information.
/etc/gshadow − This file contains secure group account information.
Check all the above files using the cat command.
The following table lists out commands that are available on majority of Unix systems to create and manage accounts and groups −
useradd
Adds accounts to the system
usermod
Modifies account attributes
userdel
Deletes accounts from the system
groupadd
Adds groups to the system
groupmod
Modifies group attributes
groupdel
Removes groups from the system
You can use Manpage Help to check complete syntax for each command mentioned here.
We will now understand how to create a group. For this, we need to create groups before creating any account otherwise, we can make use of the existing groups in our system. We have all the groups listed in /etc/groups file.
All the default groups are system account specific groups and it is not recommended to use them for ordinary accounts. So, following is the syntax to create a new group account −
groupadd [-g gid [-o]] [-r] [-f] groupname
The following table lists out the parameters −
-g GID
The numerical value of the group's ID
-o
This option permits to add group with non-unique GID
-r
This flag instructs groupadd to add a system account
-f
This option causes to just exit with success status, if the specified group already exists. With -g, if the specified GID already exists, other (unique) GID is chosen
groupname
Actual group name to be created
If you do not specify any parameter, then the system makes use of the default values.
Following example creates a developers group with default values, which is very much acceptable for most of the administrators.
$ groupadd developers
To modify a group, use the groupmod syntax −
$ groupmod -n new_modified_group_name old_group_name
To change the developers_2 group name to developer, type −
$ groupmod -n developer developer_2
Here is how you will change the financial GID to 545 −
$ groupmod -g 545 developer
We will now understand how to delete a group. To delete an existing group, all you need is the groupdel command and the group name. To delete the financial group, the command is −
$ groupdel developer
This removes only the group, not the files associated with that group. The files are still accessible by their owners.
Let us see how to create a new account on your Unix system. Following is the syntax to create a user's account −
useradd -d homedir -g groupname -m -s shell -u userid accountname
The following table lists out the parameters −
-d homedir
Specifies home directory for the account
-g groupname
Specifies a group account for this account
-m
Creates the home directory if it doesn't exist
-s shell
Specifies the default shell for this account
-u userid
You can specify a user id for this account
accountname
Actual account name to be created
If you do not specify any parameter, then the system makes use of the default values. The useradd command modifies the /etc/passwd, /etc/shadow, and /etc/group files and creates a home directory.
Following is the example that creates an account mcmohd, setting its home directory to /home/mcmohd and the group as developers. This user would have Korn Shell assigned to it.
$ useradd -d /home/mcmohd -g developers -s /bin/ksh mcmohd
Before issuing the above command, make sure you already have the developers group created using the groupadd command.
Once an account is created you can set its password using the passwd command as follows −
$ passwd mcmohd20
Changing password for user mcmohd20.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
When you type passwd accountname, it gives you an option to change the password, provided you are a superuser. Otherwise, you can change just your password using the same command but without specifying your account name.
The usermod command enables you to make changes to an existing account from the command line. It uses the same arguments as the useradd command, plus the -l argument, which allows you to change the account name.
For example, to change the account name mcmohd to mcmohd20 and to change home directory accordingly, you will need to issue the following command −
$ usermod -d /home/mcmohd20 -m -l mcmohd mcmohd20
The userdel command can be used to delete an existing user. This is a very dangerous command if not used with caution.
There is only one argument or option available for the command .r, for removing the account's home directory and mail file.
For example, to remove account mcmohd20, issue the following command −
$ userdel -r mcmohd20
If you want to keep the home directory for backup purposes, omit the -r option. You can remove the home directory as needed at a later time.
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": 2825,
"s": 2747,
"text": "In this chapter, we will discuss in detail about user administration in Unix."
},
{
"code": null,
"e": 2878,
"s": 2825,
"text": "There are three types of accounts on a Unix system −"
},
{
"code": null,
"e": 3083,
"s": 2878,
"text": "This is also called superuser and would have complete and unfettered control of the system. A superuser can run any commands without any restriction. This user should be assumed as a system administrator."
},
{
"code": null,
"e": 3355,
"s": 3083,
"text": "System accounts are those needed for the operation of system-specific components for example mail accounts and the sshd accounts. These accounts are usually needed for some specific function on your system, and any modifications to them could adversely affect the system."
},
{
"code": null,
"e": 3570,
"s": 3355,
"text": "User accounts provide interactive access to the system for users and groups of users. General users are typically assigned to these accounts and usually have limited access to critical system files and directories."
},
{
"code": null,
"e": 3799,
"s": 3570,
"text": "Unix supports a concept of Group Account which logically groups a number of accounts. Every account would be a part of another group account. A Unix group plays important role in handling file permissions and process management."
},
{
"code": null,
"e": 3847,
"s": 3799,
"text": "There are four main user administration files −"
},
{
"code": null,
"e": 3989,
"s": 3847,
"text": "/etc/passwd − Keeps the user account and password information. This file holds the majority of information about accounts on the Unix system."
},
{
"code": null,
"e": 4131,
"s": 3989,
"text": "/etc/passwd − Keeps the user account and password information. This file holds the majority of information about accounts on the Unix system."
},
{
"code": null,
"e": 4243,
"s": 4131,
"text": "/etc/shadow − Holds the encrypted password of the corresponding account. Not all the systems support this file."
},
{
"code": null,
"e": 4355,
"s": 4243,
"text": "/etc/shadow − Holds the encrypted password of the corresponding account. Not all the systems support this file."
},
{
"code": null,
"e": 4427,
"s": 4355,
"text": "/etc/group − This file contains the group information for each account."
},
{
"code": null,
"e": 4499,
"s": 4427,
"text": "/etc/group − This file contains the group information for each account."
},
{
"code": null,
"e": 4567,
"s": 4499,
"text": "/etc/gshadow − This file contains secure group account information."
},
{
"code": null,
"e": 4635,
"s": 4567,
"text": "/etc/gshadow − This file contains secure group account information."
},
{
"code": null,
"e": 4684,
"s": 4635,
"text": "Check all the above files using the cat command."
},
{
"code": null,
"e": 4813,
"s": 4684,
"text": "The following table lists out commands that are available on majority of Unix systems to create and manage accounts and groups −"
},
{
"code": null,
"e": 4821,
"s": 4813,
"text": "useradd"
},
{
"code": null,
"e": 4849,
"s": 4821,
"text": "Adds accounts to the system"
},
{
"code": null,
"e": 4857,
"s": 4849,
"text": "usermod"
},
{
"code": null,
"e": 4885,
"s": 4857,
"text": "Modifies account attributes"
},
{
"code": null,
"e": 4893,
"s": 4885,
"text": "userdel"
},
{
"code": null,
"e": 4926,
"s": 4893,
"text": "Deletes accounts from the system"
},
{
"code": null,
"e": 4935,
"s": 4926,
"text": "groupadd"
},
{
"code": null,
"e": 4961,
"s": 4935,
"text": "Adds groups to the system"
},
{
"code": null,
"e": 4970,
"s": 4961,
"text": "groupmod"
},
{
"code": null,
"e": 4996,
"s": 4970,
"text": "Modifies group attributes"
},
{
"code": null,
"e": 5005,
"s": 4996,
"text": "groupdel"
},
{
"code": null,
"e": 5036,
"s": 5005,
"text": "Removes groups from the system"
},
{
"code": null,
"e": 5119,
"s": 5036,
"text": "You can use Manpage Help to check complete syntax for each command mentioned here."
},
{
"code": null,
"e": 5344,
"s": 5119,
"text": "We will now understand how to create a group. For this, we need to create groups before creating any account otherwise, we can make use of the existing groups in our system. We have all the groups listed in /etc/groups file."
},
{
"code": null,
"e": 5523,
"s": 5344,
"text": "All the default groups are system account specific groups and it is not recommended to use them for ordinary accounts. So, following is the syntax to create a new group account −"
},
{
"code": null,
"e": 5568,
"s": 5523,
"text": " groupadd [-g gid [-o]] [-r] [-f] groupname\n"
},
{
"code": null,
"e": 5615,
"s": 5568,
"text": "The following table lists out the parameters −"
},
{
"code": null,
"e": 5622,
"s": 5615,
"text": "-g GID"
},
{
"code": null,
"e": 5660,
"s": 5622,
"text": "The numerical value of the group's ID"
},
{
"code": null,
"e": 5663,
"s": 5660,
"text": "-o"
},
{
"code": null,
"e": 5716,
"s": 5663,
"text": "This option permits to add group with non-unique GID"
},
{
"code": null,
"e": 5719,
"s": 5716,
"text": "-r"
},
{
"code": null,
"e": 5772,
"s": 5719,
"text": "This flag instructs groupadd to add a system account"
},
{
"code": null,
"e": 5776,
"s": 5772,
"text": "-f "
},
{
"code": null,
"e": 5943,
"s": 5776,
"text": "This option causes to just exit with success status, if the specified group already exists. With -g, if the specified GID already exists, other (unique) GID is chosen"
},
{
"code": null,
"e": 5953,
"s": 5943,
"text": "groupname"
},
{
"code": null,
"e": 5985,
"s": 5953,
"text": "Actual group name to be created"
},
{
"code": null,
"e": 6071,
"s": 5985,
"text": "If you do not specify any parameter, then the system makes use of the default values."
},
{
"code": null,
"e": 6199,
"s": 6071,
"text": "Following example creates a developers group with default values, which is very much acceptable for most of the administrators."
},
{
"code": null,
"e": 6222,
"s": 6199,
"text": "$ groupadd developers\n"
},
{
"code": null,
"e": 6267,
"s": 6222,
"text": "To modify a group, use the groupmod syntax −"
},
{
"code": null,
"e": 6321,
"s": 6267,
"text": "$ groupmod -n new_modified_group_name old_group_name\n"
},
{
"code": null,
"e": 6380,
"s": 6321,
"text": "To change the developers_2 group name to developer, type −"
},
{
"code": null,
"e": 6417,
"s": 6380,
"text": "$ groupmod -n developer developer_2\n"
},
{
"code": null,
"e": 6472,
"s": 6417,
"text": "Here is how you will change the financial GID to 545 −"
},
{
"code": null,
"e": 6501,
"s": 6472,
"text": "$ groupmod -g 545 developer\n"
},
{
"code": null,
"e": 6681,
"s": 6501,
"text": "We will now understand how to delete a group. To delete an existing group, all you need is the groupdel command and the group name. To delete the financial group, the command is −"
},
{
"code": null,
"e": 6703,
"s": 6681,
"text": "$ groupdel developer\n"
},
{
"code": null,
"e": 6822,
"s": 6703,
"text": "This removes only the group, not the files associated with that group. The files are still accessible by their owners."
},
{
"code": null,
"e": 6935,
"s": 6822,
"text": "Let us see how to create a new account on your Unix system. Following is the syntax to create a user's account −"
},
{
"code": null,
"e": 7002,
"s": 6935,
"text": "useradd -d homedir -g groupname -m -s shell -u userid accountname\n"
},
{
"code": null,
"e": 7049,
"s": 7002,
"text": "The following table lists out the parameters −"
},
{
"code": null,
"e": 7060,
"s": 7049,
"text": "-d homedir"
},
{
"code": null,
"e": 7101,
"s": 7060,
"text": "Specifies home directory for the account"
},
{
"code": null,
"e": 7114,
"s": 7101,
"text": "-g groupname"
},
{
"code": null,
"e": 7157,
"s": 7114,
"text": "Specifies a group account for this account"
},
{
"code": null,
"e": 7160,
"s": 7157,
"text": "-m"
},
{
"code": null,
"e": 7207,
"s": 7160,
"text": "Creates the home directory if it doesn't exist"
},
{
"code": null,
"e": 7216,
"s": 7207,
"text": "-s shell"
},
{
"code": null,
"e": 7261,
"s": 7216,
"text": "Specifies the default shell for this account"
},
{
"code": null,
"e": 7271,
"s": 7261,
"text": "-u userid"
},
{
"code": null,
"e": 7314,
"s": 7271,
"text": "You can specify a user id for this account"
},
{
"code": null,
"e": 7326,
"s": 7314,
"text": "accountname"
},
{
"code": null,
"e": 7360,
"s": 7326,
"text": "Actual account name to be created"
},
{
"code": null,
"e": 7556,
"s": 7360,
"text": "If you do not specify any parameter, then the system makes use of the default values. The useradd command modifies the /etc/passwd, /etc/shadow, and /etc/group files and creates a home directory."
},
{
"code": null,
"e": 7733,
"s": 7556,
"text": "Following is the example that creates an account mcmohd, setting its home directory to /home/mcmohd and the group as developers. This user would have Korn Shell assigned to it."
},
{
"code": null,
"e": 7793,
"s": 7733,
"text": "$ useradd -d /home/mcmohd -g developers -s /bin/ksh mcmohd\n"
},
{
"code": null,
"e": 7911,
"s": 7793,
"text": "Before issuing the above command, make sure you already have the developers group created using the groupadd command."
},
{
"code": null,
"e": 8001,
"s": 7911,
"text": "Once an account is created you can set its password using the passwd command as follows −"
},
{
"code": null,
"e": 8158,
"s": 8001,
"text": "$ passwd mcmohd20\nChanging password for user mcmohd20.\nNew UNIX password:\nRetype new UNIX password:\npasswd: all authentication tokens updated successfully.\n"
},
{
"code": null,
"e": 8379,
"s": 8158,
"text": "When you type passwd accountname, it gives you an option to change the password, provided you are a superuser. Otherwise, you can change just your password using the same command but without specifying your account name."
},
{
"code": null,
"e": 8591,
"s": 8379,
"text": "The usermod command enables you to make changes to an existing account from the command line. It uses the same arguments as the useradd command, plus the -l argument, which allows you to change the account name."
},
{
"code": null,
"e": 8739,
"s": 8591,
"text": "For example, to change the account name mcmohd to mcmohd20 and to change home directory accordingly, you will need to issue the following command −"
},
{
"code": null,
"e": 8790,
"s": 8739,
"text": "$ usermod -d /home/mcmohd20 -m -l mcmohd mcmohd20\n"
},
{
"code": null,
"e": 8909,
"s": 8790,
"text": "The userdel command can be used to delete an existing user. This is a very dangerous command if not used with caution."
},
{
"code": null,
"e": 9033,
"s": 8909,
"text": "There is only one argument or option available for the command .r, for removing the account's home directory and mail file."
},
{
"code": null,
"e": 9104,
"s": 9033,
"text": "For example, to remove account mcmohd20, issue the following command −"
},
{
"code": null,
"e": 9127,
"s": 9104,
"text": "$ userdel -r mcmohd20\n"
},
{
"code": null,
"e": 9268,
"s": 9127,
"text": "If you want to keep the home directory for backup purposes, omit the -r option. You can remove the home directory as needed at a later time."
},
{
"code": null,
"e": 9303,
"s": 9268,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 9331,
"s": 9303,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9365,
"s": 9331,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9382,
"s": 9365,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9415,
"s": 9382,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9426,
"s": 9415,
"text": " Pradeep D"
},
{
"code": null,
"e": 9461,
"s": 9426,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9477,
"s": 9461,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 9510,
"s": 9477,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9522,
"s": 9510,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 9554,
"s": 9522,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9562,
"s": 9554,
"text": " Uplatz"
},
{
"code": null,
"e": 9569,
"s": 9562,
"text": " Print"
},
{
"code": null,
"e": 9580,
"s": 9569,
"text": " Add Notes"
}
] |
How to Convert Vector to Array in Java? - GeeksforGeeks
|
15 Nov, 2021
As we all know an array is a group of liked-typed variables that are referred to by a common name while on the other hand vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implement the List interface which gives a superior advantage of using all the methods of List interface here. Now the problem simply breaks down to how to use these methods defined in order for the conversion of vector to array for which we will be proposing ways as listed below as follows:
Methods:
Using toArray() method of Vector classUsing toArray(new String[vector.size()]) method
Using toArray() method of Vector class
Using toArray(new String[vector.size()]) method
Let us go through an illustration before landing upon methods to get the understanding of approaches real quick.
Illustrations:
Input : Vector: ['G', 'e', 'e', 'k', 's']
Output: Array: ['G', 'e', 'e', 'k', 's']
Input : Vector: [1, 2, 3, 4, 5]
Output: Array: [1, 2, 3, 4, 5]
Method 1: Using toArray() method of Vector class
Approach:
Get the Vector.Convert the Vector to Object array using toArray() methodConvert the Object array to desired type array using Arrays.copyOf() methodReturn the print the Array.
Get the Vector.
Convert the Vector to Object array using toArray() method
Convert the Object array to desired type array using Arrays.copyOf() method
Return the print the Array.
Example:
Java
// Java Program to Convert Vector to Array // Importing required classesimport java.util.*; // Main classpublic class GFG { // Method 1 // To convert Vector to Array public static <T> Object[] convertVectorToArray(Vector<T> vector) { // Converting vector to array // using toArray() method of Vector class Object[] array = vector.toArray(); // Returning the array return array; } // Method 2 // Main driver method public static void main(String args[]) { // Creating a vector of string type Vector<String> vector = new Vector<String>(); // Adding custom elements using add() method vector.add("G"); vector.add("e"); vector.add("e"); vector.add("k"); vector.add("s"); // Printing the vector elements System.out.println("Vector: " + vector); // Converting vector to object array Object[] objArray = convertVectorToArray(vector); // Converting object array to string array String[] array = Arrays.copyOf( objArray, objArray.length, String[].class); // Lastly printing the string array System.out.println("Array: " + Arrays.toString(array)); }}
Vector: [G, e, e, k, s]
Array: [G, e, e, k, s]
Method 2: Using toArray(new String[vector.size()]) method
Approach:
Created a Vector String type.Added elements into Vector using add(E) method.Converted the Vector to Array using toArray(new String[vector.size()]).
Created a Vector String type.
Added elements into Vector using add(E) method.
Converted the Vector to Array using toArray(new String[vector.size()]).
Example:
Java
// Java Program to Convert Vector to Array // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating a vector of string type Vector<String> vector = new Vector<String>(); // Adding elements to above object // using add() method vector.add("G"); vector.add("e"); vector.add("e"); vector.add("k"); vector.add("s"); // Printing the elements inside vector System.out.println("Vector: " + vector); // Converting vector to string array String[] array = vector.toArray(new String[vector.size()]); // Printing the string array System.out.println("Array: " + Arrays.toString(array)); }}
Vector: [G, e, e, k, s]
Array: [G, e, e, k, s]
Rajput-Ji
solankimayank
Java-Array-Programs
Java-Arrays
Java-Collections
Java-Vector
Technical Scripter 2018
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 24858,
"s": 24316,
"text": "As we all know an array is a group of liked-typed variables that are referred to by a common name while on the other hand vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implement the List interface which gives a superior advantage of using all the methods of List interface here. Now the problem simply breaks down to how to use these methods defined in order for the conversion of vector to array for which we will be proposing ways as listed below as follows:"
},
{
"code": null,
"e": 24867,
"s": 24858,
"text": "Methods:"
},
{
"code": null,
"e": 24953,
"s": 24867,
"text": "Using toArray() method of Vector classUsing toArray(new String[vector.size()]) method"
},
{
"code": null,
"e": 24992,
"s": 24953,
"text": "Using toArray() method of Vector class"
},
{
"code": null,
"e": 25040,
"s": 24992,
"text": "Using toArray(new String[vector.size()]) method"
},
{
"code": null,
"e": 25153,
"s": 25040,
"text": "Let us go through an illustration before landing upon methods to get the understanding of approaches real quick."
},
{
"code": null,
"e": 25168,
"s": 25153,
"text": "Illustrations:"
},
{
"code": null,
"e": 25253,
"s": 25168,
"text": "Input : Vector: ['G', 'e', 'e', 'k', 's'] \nOutput: Array: ['G', 'e', 'e', 'k', 's'] "
},
{
"code": null,
"e": 25317,
"s": 25253,
"text": "Input : Vector: [1, 2, 3, 4, 5]\nOutput: Array: [1, 2, 3, 4, 5] "
},
{
"code": null,
"e": 25366,
"s": 25317,
"text": "Method 1: Using toArray() method of Vector class"
},
{
"code": null,
"e": 25377,
"s": 25366,
"text": "Approach: "
},
{
"code": null,
"e": 25552,
"s": 25377,
"text": "Get the Vector.Convert the Vector to Object array using toArray() methodConvert the Object array to desired type array using Arrays.copyOf() methodReturn the print the Array."
},
{
"code": null,
"e": 25568,
"s": 25552,
"text": "Get the Vector."
},
{
"code": null,
"e": 25626,
"s": 25568,
"text": "Convert the Vector to Object array using toArray() method"
},
{
"code": null,
"e": 25702,
"s": 25626,
"text": "Convert the Object array to desired type array using Arrays.copyOf() method"
},
{
"code": null,
"e": 25730,
"s": 25702,
"text": "Return the print the Array."
},
{
"code": null,
"e": 25739,
"s": 25730,
"text": "Example:"
},
{
"code": null,
"e": 25744,
"s": 25739,
"text": "Java"
},
{
"code": "// Java Program to Convert Vector to Array // Importing required classesimport java.util.*; // Main classpublic class GFG { // Method 1 // To convert Vector to Array public static <T> Object[] convertVectorToArray(Vector<T> vector) { // Converting vector to array // using toArray() method of Vector class Object[] array = vector.toArray(); // Returning the array return array; } // Method 2 // Main driver method public static void main(String args[]) { // Creating a vector of string type Vector<String> vector = new Vector<String>(); // Adding custom elements using add() method vector.add(\"G\"); vector.add(\"e\"); vector.add(\"e\"); vector.add(\"k\"); vector.add(\"s\"); // Printing the vector elements System.out.println(\"Vector: \" + vector); // Converting vector to object array Object[] objArray = convertVectorToArray(vector); // Converting object array to string array String[] array = Arrays.copyOf( objArray, objArray.length, String[].class); // Lastly printing the string array System.out.println(\"Array: \" + Arrays.toString(array)); }}",
"e": 27024,
"s": 25744,
"text": null
},
{
"code": null,
"e": 27071,
"s": 27024,
"text": "Vector: [G, e, e, k, s]\nArray: [G, e, e, k, s]"
},
{
"code": null,
"e": 27132,
"s": 27073,
"text": "Method 2: Using toArray(new String[vector.size()]) method "
},
{
"code": null,
"e": 27143,
"s": 27132,
"text": "Approach: "
},
{
"code": null,
"e": 27291,
"s": 27143,
"text": "Created a Vector String type.Added elements into Vector using add(E) method.Converted the Vector to Array using toArray(new String[vector.size()])."
},
{
"code": null,
"e": 27321,
"s": 27291,
"text": "Created a Vector String type."
},
{
"code": null,
"e": 27369,
"s": 27321,
"text": "Added elements into Vector using add(E) method."
},
{
"code": null,
"e": 27441,
"s": 27369,
"text": "Converted the Vector to Array using toArray(new String[vector.size()])."
},
{
"code": null,
"e": 27450,
"s": 27441,
"text": "Example:"
},
{
"code": null,
"e": 27455,
"s": 27450,
"text": "Java"
},
{
"code": "// Java Program to Convert Vector to Array // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating a vector of string type Vector<String> vector = new Vector<String>(); // Adding elements to above object // using add() method vector.add(\"G\"); vector.add(\"e\"); vector.add(\"e\"); vector.add(\"k\"); vector.add(\"s\"); // Printing the elements inside vector System.out.println(\"Vector: \" + vector); // Converting vector to string array String[] array = vector.toArray(new String[vector.size()]); // Printing the string array System.out.println(\"Array: \" + Arrays.toString(array)); }}",
"e": 28297,
"s": 27455,
"text": null
},
{
"code": null,
"e": 28344,
"s": 28297,
"text": "Vector: [G, e, e, k, s]\nArray: [G, e, e, k, s]"
},
{
"code": null,
"e": 28356,
"s": 28346,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 28370,
"s": 28356,
"text": "solankimayank"
},
{
"code": null,
"e": 28390,
"s": 28370,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 28402,
"s": 28390,
"text": "Java-Arrays"
},
{
"code": null,
"e": 28419,
"s": 28402,
"text": "Java-Collections"
},
{
"code": null,
"e": 28431,
"s": 28419,
"text": "Java-Vector"
},
{
"code": null,
"e": 28455,
"s": 28431,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 28460,
"s": 28455,
"text": "Java"
},
{
"code": null,
"e": 28465,
"s": 28460,
"text": "Java"
},
{
"code": null,
"e": 28482,
"s": 28465,
"text": "Java-Collections"
},
{
"code": null,
"e": 28580,
"s": 28482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28612,
"s": 28580,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28642,
"s": 28612,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28661,
"s": 28642,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28692,
"s": 28661,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28710,
"s": 28692,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28742,
"s": 28710,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28762,
"s": 28742,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28777,
"s": 28762,
"text": "Stream In Java"
},
{
"code": null,
"e": 28801,
"s": 28777,
"text": "Singleton Class in Java"
}
] |
Filter Python list by Predicate in Python - GeeksforGeeks
|
19 Dec, 2021
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method
Syntax:
filter(predicate, list)
where,
list is an input list
predicate is the condition to be performed on the given list
Here lambda is used to evaluate an expression that acts as a predicate.
Syntax:
filter(lambda x: condition, list)
where
list is an input list
condition act as predicate
Example: Filter all even numbers and odd numbers in a list
Python3
# create a list of 10 elementsdata = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59] # apply a filter that takes only even numbers with# lambda as predicatea = filter(lambda x: x % 2 == 0, data) # displayfor i in a: print(i) print("------------") # apply a filter that takes only odd numbers with# lambda as predicatea = filter(lambda x: x % 2 != 0, data) # displayfor i in a: print(i)
Output:
10
2
4
56
32
56
32
------------
3
21
59
Here list comprehension act as a predicate.
Syntax:
[iterator for iterator in list condition]
where,
list is the input list
iterator is used to iterate the input list of elements
condition act as predicate
Example: Python code to get odd and even numbers
Python3
# create a list of 10 elementsdata = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59] # filter data using comprehension# to get even numbersprint([x for x in data if x % 2 == 0]) # filter data using comprehension# to get odd numbersprint([x for x in data if x % 2 != 0])
Output:
[10, 2, 4, 56, 32, 56, 32]
[3, 21, 59]
Picked
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 24626,
"s": 24318,
"text": "In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method "
},
{
"code": null,
"e": 24634,
"s": 24626,
"text": "Syntax:"
},
{
"code": null,
"e": 24658,
"s": 24634,
"text": "filter(predicate, list)"
},
{
"code": null,
"e": 24665,
"s": 24658,
"text": "where,"
},
{
"code": null,
"e": 24687,
"s": 24665,
"text": "list is an input list"
},
{
"code": null,
"e": 24748,
"s": 24687,
"text": "predicate is the condition to be performed on the given list"
},
{
"code": null,
"e": 24820,
"s": 24748,
"text": "Here lambda is used to evaluate an expression that acts as a predicate."
},
{
"code": null,
"e": 24828,
"s": 24820,
"text": "Syntax:"
},
{
"code": null,
"e": 24862,
"s": 24828,
"text": "filter(lambda x: condition, list)"
},
{
"code": null,
"e": 24868,
"s": 24862,
"text": "where"
},
{
"code": null,
"e": 24890,
"s": 24868,
"text": "list is an input list"
},
{
"code": null,
"e": 24917,
"s": 24890,
"text": "condition act as predicate"
},
{
"code": null,
"e": 24977,
"s": 24917,
"text": "Example: Filter all even numbers and odd numbers in a list"
},
{
"code": null,
"e": 24985,
"s": 24977,
"text": "Python3"
},
{
"code": "# create a list of 10 elementsdata = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59] # apply a filter that takes only even numbers with# lambda as predicatea = filter(lambda x: x % 2 == 0, data) # displayfor i in a: print(i) print(\"------------\") # apply a filter that takes only odd numbers with# lambda as predicatea = filter(lambda x: x % 2 != 0, data) # displayfor i in a: print(i)",
"e": 25375,
"s": 24985,
"text": null
},
{
"code": null,
"e": 25383,
"s": 25375,
"text": "Output:"
},
{
"code": null,
"e": 25423,
"s": 25383,
"text": "10\n2\n4\n56\n32\n56\n32\n------------\n3\n21\n59"
},
{
"code": null,
"e": 25467,
"s": 25423,
"text": "Here list comprehension act as a predicate."
},
{
"code": null,
"e": 25475,
"s": 25467,
"text": "Syntax:"
},
{
"code": null,
"e": 25518,
"s": 25475,
"text": "[iterator for iterator in list condition]"
},
{
"code": null,
"e": 25525,
"s": 25518,
"text": "where,"
},
{
"code": null,
"e": 25548,
"s": 25525,
"text": "list is the input list"
},
{
"code": null,
"e": 25603,
"s": 25548,
"text": "iterator is used to iterate the input list of elements"
},
{
"code": null,
"e": 25630,
"s": 25603,
"text": "condition act as predicate"
},
{
"code": null,
"e": 25679,
"s": 25630,
"text": "Example: Python code to get odd and even numbers"
},
{
"code": null,
"e": 25687,
"s": 25679,
"text": "Python3"
},
{
"code": "# create a list of 10 elementsdata = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59] # filter data using comprehension# to get even numbersprint([x for x in data if x % 2 == 0]) # filter data using comprehension# to get odd numbersprint([x for x in data if x % 2 != 0])",
"e": 25949,
"s": 25687,
"text": null
},
{
"code": null,
"e": 25957,
"s": 25949,
"text": "Output:"
},
{
"code": null,
"e": 25996,
"s": 25957,
"text": "[10, 2, 4, 56, 32, 56, 32]\n[3, 21, 59]"
},
{
"code": null,
"e": 26003,
"s": 25996,
"text": "Picked"
},
{
"code": null,
"e": 26015,
"s": 26003,
"text": "python-list"
},
{
"code": null,
"e": 26022,
"s": 26015,
"text": "Python"
},
{
"code": null,
"e": 26034,
"s": 26022,
"text": "python-list"
},
{
"code": null,
"e": 26132,
"s": 26034,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26141,
"s": 26132,
"text": "Comments"
},
{
"code": null,
"e": 26154,
"s": 26141,
"text": "Old Comments"
},
{
"code": null,
"e": 26186,
"s": 26154,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26242,
"s": 26186,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26297,
"s": 26242,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26339,
"s": 26297,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26381,
"s": 26339,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26412,
"s": 26381,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26451,
"s": 26412,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26480,
"s": 26451,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26502,
"s": 26480,
"text": "Defaultdict in Python"
}
] |
Merge two sorted linked lists using C++.
|
Given 2 sorted singly linked list. Write a function to merge given two sorted linked lists
List1: 10->15->17->20
List2: 5->9->13->19
Result: 5->9->10->13->15->17->19->20
1. Traverse both lists
1.1. If list1->data < list2->data
1.1.1 Add list1->data to new list and increment list1 pointer
1.2 If list2->data < list1->data
1.2.1 Add list2->data to new list and increment list2 pointer
2. Repeat procedure until both lists are exhausted
3. Return resultant list
#include <iostream>
#include <new>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct node {
int data;
struct node *next;
};
node *createList(int *arr, int n){
node *head, *p;
p = head = new node;
head->data = arr[0];
head->next = NULL;
for (int i = 1; i < n; ++i) {
p->next = new node;
p = p->next;
p->data = arr[i];
p->next = NULL;
}
return head;
}
void displayList(node *head){
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
node *mergeSortedLists(node *head1, node *head2){
node *result = NULL;
if (head1 == NULL) {
return head2;
}
if (head2 == NULL) {
return head1;
}
if (head1->data < head2->data) {
result = head1;
result->next = mergeSortedLists(head1->next, head2);
} else {
result = head2;
result->next = mergeSortedLists(head1, head2->next);
}
return result;
}
int main(){
int arr1[] = {10, 15, 17, 20};
int arr2[] = {5, 9, 13, 19};
node *head1, *head2, *result = NULL;
head1 = createList(arr1, SIZE(arr1));
head2 = createList(arr2, SIZE(arr1));
cout << "First sorted list: " << endl;
displayList(head1);
cout << "Second sorted list: " << endl;
displayList(head2);
result = mergeSortedLists(head1, head2);
cout << "Final sorted list: " << endl;
displayList(result);
return 0;
}
When you compile and execute the above program. It generates the following output −
First sorted list:
10 15 17 20
Second sorted list:
5 9 13 19
Final sorted list:
5 9 10 13 15 17 19 20
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "Given 2 sorted singly linked list. Write a function to merge given two sorted linked lists"
},
{
"code": null,
"e": 1232,
"s": 1153,
"text": "List1: 10->15->17->20\nList2: 5->9->13->19\nResult: 5->9->10->13->15->17->19->20"
},
{
"code": null,
"e": 1540,
"s": 1232,
"text": "1. Traverse both lists\n 1.1. If list1->data < list2->data\n 1.1.1 Add list1->data to new list and increment list1 pointer\n 1.2 If list2->data < list1->data\n 1.2.1 Add list2->data to new list and increment list2 pointer\n2. Repeat procedure until both lists are exhausted\n3. Return resultant list"
},
{
"code": null,
"e": 2966,
"s": 1540,
"text": "#include <iostream>\n#include <new>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nstruct node {\n int data;\n struct node *next;\n};\nnode *createList(int *arr, int n){\n node *head, *p;\n p = head = new node;\n head->data = arr[0];\n head->next = NULL;\n for (int i = 1; i < n; ++i) {\n p->next = new node;\n p = p->next;\n p->data = arr[i];\n p->next = NULL;\n }\nreturn head;\n}\nvoid displayList(node *head){\n while (head != NULL) {\n cout << head->data << \" \";\n head = head->next;\n }\n cout << endl;\n}\nnode *mergeSortedLists(node *head1, node *head2){\n node *result = NULL;\n if (head1 == NULL) {\n return head2;\n }\n if (head2 == NULL) {\n return head1;\n }\n if (head1->data < head2->data) {\n result = head1;\n result->next = mergeSortedLists(head1->next, head2);\n } else {\n result = head2;\n result->next = mergeSortedLists(head1, head2->next);\n }\n return result;\n}\nint main(){\n int arr1[] = {10, 15, 17, 20};\n int arr2[] = {5, 9, 13, 19};\n node *head1, *head2, *result = NULL;\n head1 = createList(arr1, SIZE(arr1));\n head2 = createList(arr2, SIZE(arr1));\n cout << \"First sorted list: \" << endl;\n displayList(head1);\n cout << \"Second sorted list: \" << endl;\n displayList(head2);\n result = mergeSortedLists(head1, head2);\n cout << \"Final sorted list: \" << endl;\n displayList(result);\n return 0;\n}"
},
{
"code": null,
"e": 3050,
"s": 2966,
"text": "When you compile and execute the above program. It generates the following output −"
},
{
"code": null,
"e": 3152,
"s": 3050,
"text": "First sorted list:\n10 15 17 20\nSecond sorted list:\n5 9 13 19\nFinal sorted list:\n5 9 10 13 15 17 19 20"
}
] |
chvt command in Linux with examples - GeeksforGeeks
|
15 May, 2019
chvt command in Linux systems is used to switch between the different TTY (TeleTYpewriter) terminals available. These are essentially Virtual Terminals, which are toggled when the keys Ctrl + Alt + FunKey(1-6) are pressed. There are usually 6 TTY terminals, and the chvt command is used to switch between these terminals, without the use of function keys.
Note: This command needs Root Privilege to be executed.
Syntax:
chvt N
chvt with different N: This command takes an integer value for N, ranging from 1 to 6 (Since only 6 TTYs are present in the Linux OS). When an integer which is out of this range is specified, a blank screen pops up. To exit this screen, Alt + FunKey(7) needs to be pressed.
Note: The command fbcat which is used in the TTY terminals, serves to capture the screen of TTY terminals.
Example 1:
sudo chvt 1
Example 2:
sudo chvt 3
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Basic Operators in Shell Scripting
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 24762,
"s": 24406,
"text": "chvt command in Linux systems is used to switch between the different TTY (TeleTYpewriter) terminals available. These are essentially Virtual Terminals, which are toggled when the keys Ctrl + Alt + FunKey(1-6) are pressed. There are usually 6 TTY terminals, and the chvt command is used to switch between these terminals, without the use of function keys."
},
{
"code": null,
"e": 24818,
"s": 24762,
"text": "Note: This command needs Root Privilege to be executed."
},
{
"code": null,
"e": 24826,
"s": 24818,
"text": "Syntax:"
},
{
"code": null,
"e": 24833,
"s": 24826,
"text": "chvt N"
},
{
"code": null,
"e": 25107,
"s": 24833,
"text": "chvt with different N: This command takes an integer value for N, ranging from 1 to 6 (Since only 6 TTYs are present in the Linux OS). When an integer which is out of this range is specified, a blank screen pops up. To exit this screen, Alt + FunKey(7) needs to be pressed."
},
{
"code": null,
"e": 25214,
"s": 25107,
"text": "Note: The command fbcat which is used in the TTY terminals, serves to capture the screen of TTY terminals."
},
{
"code": null,
"e": 25225,
"s": 25214,
"text": "Example 1:"
},
{
"code": null,
"e": 25238,
"s": 25225,
"text": "sudo chvt 1\n"
},
{
"code": null,
"e": 25249,
"s": 25238,
"text": "Example 2:"
},
{
"code": null,
"e": 25262,
"s": 25249,
"text": "sudo chvt 3\n"
},
{
"code": null,
"e": 25276,
"s": 25262,
"text": "linux-command"
},
{
"code": null,
"e": 25296,
"s": 25276,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 25303,
"s": 25296,
"text": "Picked"
},
{
"code": null,
"e": 25314,
"s": 25303,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25412,
"s": 25314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25421,
"s": 25412,
"text": "Comments"
},
{
"code": null,
"e": 25434,
"s": 25421,
"text": "Old Comments"
},
{
"code": null,
"e": 25460,
"s": 25434,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25497,
"s": 25460,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25532,
"s": 25497,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 25569,
"s": 25532,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25609,
"s": 25569,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 25643,
"s": 25609,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25678,
"s": 25643,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 25707,
"s": 25678,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 25733,
"s": 25707,
"text": "Docker - COPY Instruction"
}
] |
Powershell - Start-Sleep Cmdlet
|
Start-Sleep cmdlet suspends the activity in a script or session for the particular period of time.
In these examples, we're see the Start-Sleep cmdlet in action.
In this example, we'll suspend the current process for 15 seconds.
Start-Sleep -s 15
You can see PowerShell console resumes after 15 seconds.
In this example, we'll suspend the current process for 500 milliseconds.
Start-Sleep -m 500
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2133,
"s": 2034,
"text": "Start-Sleep cmdlet suspends the activity in a script or session for the particular period of time."
},
{
"code": null,
"e": 2196,
"s": 2133,
"text": "In these examples, we're see the Start-Sleep cmdlet in action."
},
{
"code": null,
"e": 2263,
"s": 2196,
"text": "In this example, we'll suspend the current process for 15 seconds."
},
{
"code": null,
"e": 2281,
"s": 2263,
"text": "Start-Sleep -s 15"
},
{
"code": null,
"e": 2338,
"s": 2281,
"text": "You can see PowerShell console resumes after 15 seconds."
},
{
"code": null,
"e": 2411,
"s": 2338,
"text": "In this example, we'll suspend the current process for 500 milliseconds."
},
{
"code": null,
"e": 2430,
"s": 2411,
"text": "Start-Sleep -m 500"
},
{
"code": null,
"e": 2465,
"s": 2430,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2486,
"s": 2465,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2521,
"s": 2486,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2534,
"s": 2521,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2571,
"s": 2534,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2583,
"s": 2571,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2590,
"s": 2583,
"text": " Print"
},
{
"code": null,
"e": 2601,
"s": 2590,
"text": " Add Notes"
}
] |
Convert DateTime Value into String in MySQL?
|
To convert the DateTime value into string in MySQL, you can use the DATE_FORMAT() function. The syntax is as follows −
select date_format(yourColumnName, ‘%d %m %y’) as anyVariableName from yourTableName;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table DateAsStringDemo
-> (
-> YourDateTime datetime
-> );
Query OK, 0 rows affected (0.57 sec)
Inserting the date with the help of curdate() method. The query to insert date is as follows −
mysql> insert into DateAsStringDemo values(curdate());
Query OK, 1 row affected (0.24 sec)
Let us display all records with the help of select statement. The query is as follows −
mysql> select *from DateAsStringDemo;
The following is the output −
+---------------------+
| YourDateTime |
+---------------------+
| 2018-11-26 00:00:00 |
+---------------------+
1 row in set (0.00 sec)
The query to convert date to string is as follows −
mysql> select date_format(YourDateTime,'%d %m %y') as YourDateAsString from DateAsStringDemo;
The following is the output −
+------------------+
| YourDateAsString |
+------------------+
| 26 11 18 |
+------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "To convert the DateTime value into string in MySQL, you can use the DATE_FORMAT() function. The syntax is as follows −"
},
{
"code": null,
"e": 1267,
"s": 1181,
"text": "select date_format(yourColumnName, ‘%d %m %y’) as anyVariableName from yourTableName;"
},
{
"code": null,
"e": 1367,
"s": 1267,
"text": "To understand the above concept, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1486,
"s": 1367,
"text": "mysql> create table DateAsStringDemo\n -> (\n -> YourDateTime datetime\n -> );\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1581,
"s": 1486,
"text": "Inserting the date with the help of curdate() method. The query to insert date is as follows −"
},
{
"code": null,
"e": 1672,
"s": 1581,
"text": "mysql> insert into DateAsStringDemo values(curdate());\nQuery OK, 1 row affected (0.24 sec)"
},
{
"code": null,
"e": 1760,
"s": 1672,
"text": "Let us display all records with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 1798,
"s": 1760,
"text": "mysql> select *from DateAsStringDemo;"
},
{
"code": null,
"e": 1828,
"s": 1798,
"text": "The following is the output −"
},
{
"code": null,
"e": 1972,
"s": 1828,
"text": "+---------------------+\n| YourDateTime |\n+---------------------+\n| 2018-11-26 00:00:00 |\n+---------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2024,
"s": 1972,
"text": "The query to convert date to string is as follows −"
},
{
"code": null,
"e": 2118,
"s": 2024,
"text": "mysql> select date_format(YourDateTime,'%d %m %y') as YourDateAsString from DateAsStringDemo;"
},
{
"code": null,
"e": 2148,
"s": 2118,
"text": "The following is the output −"
},
{
"code": null,
"e": 2277,
"s": 2148,
"text": "+------------------+\n| YourDateAsString |\n+------------------+\n| 26 11 18 |\n+------------------+\n1 row in set (0.00 sec)"
}
] |
Python - First occurrence of one list in another - GeeksforGeeks
|
24 Feb, 2021
Given two lists, the task is to write a Python program to extract the first element that occurs in list 1 from list 2.
Examples:
Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 8, 2, 0, 11]
Output : 8
Explanation : 8 is first element from list 2, that occurs in list 1, in 5th index.
Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 18, 12, 0, 11]
Output : None
Explanation : No element of list 2 found in list 1.
Approach : Using set() + next()
In this, initially, the check container is converted to set, and each element is checked using next() and generator expression. The next() function returns the first element matching, else if no match element is found, None is returned.
Python3
# Python3 code to demonstrate working of# First occurrence of one list in another# Using next() + set() # initializing liststest_list1 = [1, 6, 3, 7, 8, 9, 2]test_list2 = [4, 10, 8, 2, 0, 11] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # converting test list to setstest_list2 = set(test_list2) # stops when 1st match element is foundres = next((ele for ele in test_list1 if ele in test_list2), None) # printing resultprint("First element in list 1 from 2 : " + str(res))
Output:
The original list 1 is : [1, 6, 3, 7, 8, 9, 2]
The original list 2 is : [4, 10, 8, 2, 0, 11]
First element in list 1 from 2 : 8
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 ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 24411,
"s": 24292,
"text": "Given two lists, the task is to write a Python program to extract the first element that occurs in list 1 from list 2."
},
{
"code": null,
"e": 24421,
"s": 24411,
"text": "Examples:"
},
{
"code": null,
"e": 24499,
"s": 24421,
"text": "Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 8, 2, 0, 11]"
},
{
"code": null,
"e": 24510,
"s": 24499,
"text": "Output : 8"
},
{
"code": null,
"e": 24593,
"s": 24510,
"text": "Explanation : 8 is first element from list 2, that occurs in list 1, in 5th index."
},
{
"code": null,
"e": 24673,
"s": 24593,
"text": "Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 18, 12, 0, 11]"
},
{
"code": null,
"e": 24687,
"s": 24673,
"text": "Output : None"
},
{
"code": null,
"e": 24739,
"s": 24687,
"text": "Explanation : No element of list 2 found in list 1."
},
{
"code": null,
"e": 24771,
"s": 24739,
"text": "Approach : Using set() + next()"
},
{
"code": null,
"e": 25008,
"s": 24771,
"text": "In this, initially, the check container is converted to set, and each element is checked using next() and generator expression. The next() function returns the first element matching, else if no match element is found, None is returned."
},
{
"code": null,
"e": 25016,
"s": 25008,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# First occurrence of one list in another# Using next() + set() # initializing liststest_list1 = [1, 6, 3, 7, 8, 9, 2]test_list2 = [4, 10, 8, 2, 0, 11] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # converting test list to setstest_list2 = set(test_list2) # stops when 1st match element is foundres = next((ele for ele in test_list1 if ele in test_list2), None) # printing resultprint(\"First element in list 1 from 2 : \" + str(res))",
"e": 25579,
"s": 25016,
"text": null
},
{
"code": null,
"e": 25587,
"s": 25579,
"text": "Output:"
},
{
"code": null,
"e": 25715,
"s": 25587,
"text": "The original list 1 is : [1, 6, 3, 7, 8, 9, 2]\nThe original list 2 is : [4, 10, 8, 2, 0, 11]\nFirst element in list 1 from 2 : 8"
},
{
"code": null,
"e": 25736,
"s": 25715,
"text": "Python list-programs"
},
{
"code": null,
"e": 25743,
"s": 25736,
"text": "Python"
},
{
"code": null,
"e": 25759,
"s": 25743,
"text": "Python Programs"
},
{
"code": null,
"e": 25857,
"s": 25759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25889,
"s": 25857,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25945,
"s": 25889,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25987,
"s": 25945,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26029,
"s": 25987,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26084,
"s": 26029,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26106,
"s": 26084,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26152,
"s": 26106,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26191,
"s": 26152,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26229,
"s": 26191,
"text": "Python | Convert a list to dictionary"
}
] |
Tk - Spinbox Widget
|
Spinbox widget allows users to choose numbers or arbitrary values. The syntax for spinbox widget is shown below.
spinbox spinboxName options
The options available for the spinbox widget are listed below in table.
-background color
Used to set background color for widget.
-borderwidth width
Used to draw with border in 3D effects.
-font fontDescriptor
Used to set font for widget.
-foreground color
Used to set foreground color for widget.
-from number
Range start value for spinbox.
-increment number
Range increment value for spinbox.
-relief condition
Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove.
-textvariable varName
Variable associated with the widget. When the text of widget changes, the variable is set to text of widget.
-to number
Range end value for spinbox.
-values array
Arbitrary values for spinbox widget.
-width number
Sets the width for widget.
A simple example for spinbox widget is shown below −
#!/usr/bin/wish
set mylist [list C C++ Lua Tcl]
pack [spinbox .s1 -textvariable spinval1 -values $mylist -background yellow -borderwidth
5 -font {Helvetica -18 bold} -foreground red -width 40 -relief ridge]
pack [spinbox .s2 -textvariable spinval2 -from 1.0 -to 100.0 -increment 5 -background
yellow -borderwidth 5 -font {Helvetica -18 bold} -foreground red -width 40
-relief ridge]
When we run the above program, we will get the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2315,
"s": 2201,
"text": "Spinbox widget allows users to choose numbers or arbitrary values. The syntax for spinbox widget is shown below."
},
{
"code": null,
"e": 2344,
"s": 2315,
"text": "spinbox spinboxName options\n"
},
{
"code": null,
"e": 2416,
"s": 2344,
"text": "The options available for the spinbox widget are listed below in table."
},
{
"code": null,
"e": 2434,
"s": 2416,
"text": "-background color"
},
{
"code": null,
"e": 2475,
"s": 2434,
"text": "Used to set background color for widget."
},
{
"code": null,
"e": 2494,
"s": 2475,
"text": "-borderwidth width"
},
{
"code": null,
"e": 2534,
"s": 2494,
"text": "Used to draw with border in 3D effects."
},
{
"code": null,
"e": 2555,
"s": 2534,
"text": "-font fontDescriptor"
},
{
"code": null,
"e": 2584,
"s": 2555,
"text": "Used to set font for widget."
},
{
"code": null,
"e": 2602,
"s": 2584,
"text": "-foreground color"
},
{
"code": null,
"e": 2643,
"s": 2602,
"text": "Used to set foreground color for widget."
},
{
"code": null,
"e": 2656,
"s": 2643,
"text": "-from number"
},
{
"code": null,
"e": 2687,
"s": 2656,
"text": "Range start value for spinbox."
},
{
"code": null,
"e": 2705,
"s": 2687,
"text": "-increment number"
},
{
"code": null,
"e": 2740,
"s": 2705,
"text": "Range increment value for spinbox."
},
{
"code": null,
"e": 2758,
"s": 2740,
"text": "-relief condition"
},
{
"code": null,
"e": 2862,
"s": 2758,
"text": "Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove."
},
{
"code": null,
"e": 2884,
"s": 2862,
"text": "-textvariable varName"
},
{
"code": null,
"e": 2993,
"s": 2884,
"text": "Variable associated with the widget. When the text of widget changes, the variable is set to text of widget."
},
{
"code": null,
"e": 3004,
"s": 2993,
"text": "-to number"
},
{
"code": null,
"e": 3033,
"s": 3004,
"text": "Range end value for spinbox."
},
{
"code": null,
"e": 3047,
"s": 3033,
"text": "-values array"
},
{
"code": null,
"e": 3084,
"s": 3047,
"text": "Arbitrary values for spinbox widget."
},
{
"code": null,
"e": 3098,
"s": 3084,
"text": "-width number"
},
{
"code": null,
"e": 3125,
"s": 3098,
"text": "Sets the width for widget."
},
{
"code": null,
"e": 3178,
"s": 3125,
"text": "A simple example for spinbox widget is shown below −"
},
{
"code": null,
"e": 3574,
"s": 3178,
"text": "#!/usr/bin/wish\n\nset mylist [list C C++ Lua Tcl]\npack [spinbox .s1 -textvariable spinval1 -values $mylist -background yellow -borderwidth\n 5 -font {Helvetica -18 bold} -foreground red -width 40 -relief ridge]\npack [spinbox .s2 -textvariable spinval2 -from 1.0 -to 100.0 -increment 5 -background\n yellow -borderwidth 5 -font {Helvetica -18 bold} -foreground red -width 40\n -relief ridge]"
},
{
"code": null,
"e": 3640,
"s": 3574,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 3647,
"s": 3640,
"text": " Print"
},
{
"code": null,
"e": 3658,
"s": 3647,
"text": " Add Notes"
}
] |
Maven - Snapshots
|
A large software application generally consists of multiple modules and it is common scenario where multiple teams are working on different modules of same application. For example, consider a team is working on the front end of the application as app-ui project (app-ui.jar:1.0) and they are using data-service project (data-service.jar:1.0).
Now it may happen that team working on data-service is undergoing bug fixing or enhancements at rapid pace and they are releasing the library to remote repository almost every other day.
Now if data-service team uploads a new version every other day, then following problems will arise −
data-service team should tell app-ui team every time when they have released an updated code.
data-service team should tell app-ui team every time when they have released an updated code.
app-ui team required to update their pom.xml regularly to get the updated version.
app-ui team required to update their pom.xml regularly to get the updated version.
To handle such kind of situation, SNAPSHOT concept comes into play.
SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build.
Now data-service team will release SNAPSHOT of its updated code every time to repository, say data-service: 1.0-SNAPSHOT, replacing an older SNAPSHOT jar.
In case of Version, if Maven once downloaded the mentioned version, say data-service:1.0, it will never try to download a newer 1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1.
In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) every time app-ui team build their project.
app-ui project is using 1.0-SNAPSHOT of data-service.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>app-ui</groupId>
<artifactId>app-ui</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>health</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>data-service</groupId>
<artifactId>data-service</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
data-service project is releasing 1.0-SNAPSHOT for every minor change.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>data-service</groupId>
<artifactId>data-service</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>health</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Although, in case of SNAPSHOT, Maven automatically fetches the latest SNAPSHOT on daily basis, you can force maven to download latest snapshot build using -U switch to any maven command.
mvn clean package -U
Let's open the command console, go to the C:\ > MVN > app-ui directory and execute the following mvn command.
C:\MVN\app-ui>mvn clean package -U
Maven will start building the project after downloading the latest SNAPSHOT of data-service.
[INFO] Scanning for projects...
[INFO]--------------------------------------------
[INFO] Building consumerBanking
[INFO] task-segment: [clean, package]
[INFO]--------------------------------------------
[INFO] Downloading data-service:1.0-SNAPSHOT
[INFO] 290K downloaded.
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory C:\MVN\app-ui\target
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\app-ui\src\main\resources
[INFO] [compiler:compile {execution:default-compile}]
[INFO] Compiling 1 source file to C:\MVN\app-ui\target\classes
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\app-ui\src\test\resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 1 source file to C:\MVN\app-ui\target\test-classes
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: C:\MVN\app-ui\target\
surefire-reports
--------------------------------------------------
T E S T S
--------------------------------------------------
Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\app-ui\target\
app-ui-1.0-SNAPSHOT.jar
[INFO]--------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO]--------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: 2015-09-27T12:30:02+05:30
[INFO] Final Memory: 16M/89M
[INFO]------------------------------------------------------------------------
34 Lectures
4 hours
Karthikeya T
14 Lectures
1.5 hours
Quaatso Learning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2404,
"s": 2060,
"text": "A large software application generally consists of multiple modules and it is common scenario where multiple teams are working on different modules of same application. For example, consider a team is working on the front end of the application as app-ui project (app-ui.jar:1.0) and they are using data-service project (data-service.jar:1.0)."
},
{
"code": null,
"e": 2591,
"s": 2404,
"text": "Now it may happen that team working on data-service is undergoing bug fixing or enhancements at rapid pace and they are releasing the library to remote repository almost every other day."
},
{
"code": null,
"e": 2692,
"s": 2591,
"text": "Now if data-service team uploads a new version every other day, then following problems will arise −"
},
{
"code": null,
"e": 2786,
"s": 2692,
"text": "data-service team should tell app-ui team every time when they have released an updated code."
},
{
"code": null,
"e": 2880,
"s": 2786,
"text": "data-service team should tell app-ui team every time when they have released an updated code."
},
{
"code": null,
"e": 2963,
"s": 2880,
"text": "app-ui team required to update their pom.xml regularly to get the updated version."
},
{
"code": null,
"e": 3046,
"s": 2963,
"text": "app-ui team required to update their pom.xml regularly to get the updated version."
},
{
"code": null,
"e": 3114,
"s": 3046,
"text": "To handle such kind of situation, SNAPSHOT concept comes into play."
},
{
"code": null,
"e": 3292,
"s": 3114,
"text": "SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build."
},
{
"code": null,
"e": 3447,
"s": 3292,
"text": "Now data-service team will release SNAPSHOT of its updated code every time to repository, say data-service: 1.0-SNAPSHOT, replacing an older SNAPSHOT jar."
},
{
"code": null,
"e": 3678,
"s": 3447,
"text": "In case of Version, if Maven once downloaded the mentioned version, say data-service:1.0, it will never try to download a newer 1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1."
},
{
"code": null,
"e": 3822,
"s": 3678,
"text": "In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) every time app-ui team build their project."
},
{
"code": null,
"e": 3876,
"s": 3822,
"text": "app-ui project is using 1.0-SNAPSHOT of data-service."
},
{
"code": null,
"e": 4665,
"s": 3876,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>app-ui</groupId>\n <artifactId>app-ui</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <name>health</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>data-service</groupId>\n <artifactId>data-service</artifactId>\n <version>1.0-SNAPSHOT</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n</project>"
},
{
"code": null,
"e": 4736,
"s": 4665,
"text": "data-service project is releasing 1.0-SNAPSHOT for every minor change."
},
{
"code": null,
"e": 5315,
"s": 4736,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>data-service</groupId>\n <artifactId>data-service</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>health</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n</project>"
},
{
"code": null,
"e": 5502,
"s": 5315,
"text": "Although, in case of SNAPSHOT, Maven automatically fetches the latest SNAPSHOT on daily basis, you can force maven to download latest snapshot build using -U switch to any maven command."
},
{
"code": null,
"e": 5524,
"s": 5502,
"text": "mvn clean package -U\n"
},
{
"code": null,
"e": 5634,
"s": 5524,
"text": "Let's open the command console, go to the C:\\ > MVN > app-ui directory and execute the following mvn command."
},
{
"code": null,
"e": 5670,
"s": 5634,
"text": "C:\\MVN\\app-ui>mvn clean package -U\n"
},
{
"code": null,
"e": 5763,
"s": 5670,
"text": "Maven will start building the project after downloading the latest SNAPSHOT of data-service."
},
{
"code": null,
"e": 7747,
"s": 5763,
"text": "[INFO] Scanning for projects...\n[INFO]--------------------------------------------\n[INFO] Building consumerBanking\n[INFO] task-segment: [clean, package]\n[INFO]--------------------------------------------\n[INFO] Downloading data-service:1.0-SNAPSHOT\n[INFO] 290K downloaded.\n[INFO] [clean:clean {execution: default-clean}]\n[INFO] Deleting directory C:\\MVN\\app-ui\\target\n[INFO] [resources:resources {execution: default-resources}]\n\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,\ni.e. build is platform dependent!\n\n[INFO] skip non existing resourceDirectory C:\\MVN\\app-ui\\src\\main\\resources\n[INFO] [compiler:compile {execution:default-compile}]\n[INFO] Compiling 1 source file to C:\\MVN\\app-ui\\target\\classes\n[INFO] [resources:testResources {execution: default-testResources}]\n\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,\ni.e. build is platform dependent!\n\n[INFO] skip non existing resourceDirectory C:\\MVN\\app-ui\\src\\test\\resources\n[INFO] [compiler:testCompile {execution: default-testCompile}]\n[INFO] Compiling 1 source file to C:\\MVN\\app-ui\\target\\test-classes\n[INFO] [surefire:test {execution: default-test}]\n[INFO] Surefire report directory: C:\\MVN\\app-ui\\target\\\nsurefire-reports\n\n--------------------------------------------------\n T E S T S\n--------------------------------------------------\n\nRunning com.companyname.bank.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\app-ui\\target\\\napp-ui-1.0-SNAPSHOT.jar\n[INFO]--------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO]--------------------------------------------------------\n[INFO] Total time: 2 seconds\n[INFO] Finished at: 2015-09-27T12:30:02+05:30\n[INFO] Final Memory: 16M/89M\n[INFO]------------------------------------------------------------------------\n"
},
{
"code": null,
"e": 7780,
"s": 7747,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7794,
"s": 7780,
"text": " Karthikeya T"
},
{
"code": null,
"e": 7829,
"s": 7794,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7847,
"s": 7829,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 7854,
"s": 7847,
"text": " Print"
},
{
"code": null,
"e": 7865,
"s": 7854,
"text": " Add Notes"
}
] |
Perl return Function
|
This function returns EXPR at the end of a subroutine, block, or do function. EXPR may be a scalar, array, or hash value; context will be selected at execution time. If no EXPR is given, returns an empty list in list context, undef in scalar context, or nothing in a void context.
Following is the simple syntax for this function −
return EXPR
return
This function returns in Scalar Context: List, which may be interpreted as scalar, list, or void context.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
$retval = Sum(5,10);
print ("Return value is $retval\n" );
@retval = Sum(5,10);
print ("Return value is @retval\n" );
sub Sum($$) {
my($a, $b ) = @_;
my $c = $a + $b;
return($a, $b, $c);
}
When above code is executed, it produces the following result −
Return value is 15
Return value is 5 10 15
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": 2501,
"s": 2220,
"text": "This function returns EXPR at the end of a subroutine, block, or do function. EXPR may be a scalar, array, or hash value; context will be selected at execution time. If no EXPR is given, returns an empty list in list context, undef in scalar context, or nothing in a void context."
},
{
"code": null,
"e": 2552,
"s": 2501,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2573,
"s": 2552,
"text": "return EXPR\n\nreturn\n"
},
{
"code": null,
"e": 2679,
"s": 2573,
"text": "This function returns in Scalar Context: List, which may be interpreted as scalar, list, or void context."
},
{
"code": null,
"e": 2735,
"s": 2679,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2961,
"s": 2735,
"text": "#!/usr/bin/perl -w\n\n$retval = Sum(5,10);\nprint (\"Return value is $retval\\n\" );\n\n@retval = Sum(5,10);\nprint (\"Return value is @retval\\n\" );\n\nsub Sum($$) {\n my($a, $b ) = @_; \n\n my $c = $a + $b;\n \n return($a, $b, $c);\n}"
},
{
"code": null,
"e": 3025,
"s": 2961,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3069,
"s": 3025,
"text": "Return value is 15\nReturn value is 5 10 15\n"
},
{
"code": null,
"e": 3104,
"s": 3069,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3118,
"s": 3104,
"text": " Devi Killada"
},
{
"code": null,
"e": 3153,
"s": 3118,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3173,
"s": 3153,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3206,
"s": 3173,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3222,
"s": 3206,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3255,
"s": 3222,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3272,
"s": 3255,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3305,
"s": 3272,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3328,
"s": 3305,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3363,
"s": 3328,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3386,
"s": 3363,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3393,
"s": 3386,
"text": " Print"
},
{
"code": null,
"e": 3404,
"s": 3393,
"text": " Add Notes"
}
] |
Block-level Elements and Block Boxes in CSS
|
Block-level elements have their CSS display property set to either ‘block’, ‘list-item’, or ‘table’ and these elements force a line break above and below themselves. Block-level boxes are generated by each block-level element which is a part of the positioning scheme as well as contains child boxes.
Block container boxes contain either block-level boxes and follow block formatting context or contain inline-level boxes and follow inline formatting context. Block boxes is a term used if block-level boxes are also block containers.
Anonymous block boxes are those boxes over which developer has no control. If an inline box contains a block box and the inline content around the block box is enclosed in an anonymous block box.
Let’s see an example for Block-level Elements and Block Boxes −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>CSS Block-level Elements and Block Boxes</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
box-sizing: border-box;
/*margin:5px;*/
}
input[type="button"] {
border-radius: 10px;
}
.child{
height: 40px;
width: 100%;
color: white;
border: 4px solid black;
}
.child:nth-of-type(1){
background-color: #FF8A00;
}
.child:nth-of-type(2){
background-color: #F44336;
}
.child:nth-of-type(3){
background-color: #C303C3;
}
.child:nth-of-type(4){
background-color: #4CAF50;
}
.child:nth-of-type(5){
background-color: #03A9F4;
}
.child:nth-of-type(6){
background-color: #FEDC11;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Block-level Elements and Block Boxes</legend>
<div id="container">Color Orange
<div class="child"></div>Color Red
<div class="child"></div>Color Violet
<div class="child"></div>
</div><br>
</body>
</html>
This will produce the following output −
|
[
{
"code": null,
"e": 1363,
"s": 1062,
"text": "Block-level elements have their CSS display property set to either ‘block’, ‘list-item’, or ‘table’ and these elements force a line break above and below themselves. Block-level boxes are generated by each block-level element which is a part of the positioning scheme as well as contains child boxes."
},
{
"code": null,
"e": 1597,
"s": 1363,
"text": "Block container boxes contain either block-level boxes and follow block formatting context or contain inline-level boxes and follow inline formatting context. Block boxes is a term used if block-level boxes are also block containers."
},
{
"code": null,
"e": 1793,
"s": 1597,
"text": "Anonymous block boxes are those boxes over which developer has no control. If an inline box contains a block box and the inline content around the block box is enclosed in an anonymous block box."
},
{
"code": null,
"e": 1857,
"s": 1793,
"text": "Let’s see an example for Block-level Elements and Block Boxes −"
},
{
"code": null,
"e": 1868,
"s": 1857,
"text": " Live Demo"
},
{
"code": null,
"e": 2822,
"s": 1868,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Block-level Elements and Block Boxes</title>\n<style>\nform {\n width:70%;\n margin: 0 auto;\n text-align: center;\n}\n* {\n padding: 2px;\n box-sizing: border-box;\n /*margin:5px;*/\n}\ninput[type=\"button\"] {\n border-radius: 10px;\n}\n.child{\n height: 40px;\n width: 100%;\n color: white;\n border: 4px solid black;\n}\n.child:nth-of-type(1){\n background-color: #FF8A00;\n}\n.child:nth-of-type(2){\n background-color: #F44336;\n}\n.child:nth-of-type(3){\n background-color: #C303C3;\n}\n.child:nth-of-type(4){\n background-color: #4CAF50;\n}\n.child:nth-of-type(5){\n background-color: #03A9F4;\n}\n.child:nth-of-type(6){\n background-color: #FEDC11;\n}\n</style>\n</head>\n<body>\n<form>\n<fieldset>\n<legend>CSS Block-level Elements and Block Boxes</legend>\n<div id=\"container\">Color Orange\n<div class=\"child\"></div>Color Red\n<div class=\"child\"></div>Color Violet\n<div class=\"child\"></div>\n</div><br>\n</body>\n</html>"
},
{
"code": null,
"e": 2863,
"s": 2822,
"text": "This will produce the following output −"
}
] |
Git Branch
|
In Git, a branch is a new/separate version of the main repository.
Let's say you have a large project, and you need to update the design on it.
How would that work without and with Git:
Without Git:
Make copies of all the relevant files to avoid impacting the live version
Start working with the design and find that code depend on code in other
files, that also need to be changed!
Make copies of the dependant files as well. Making sure that every file
dependency references the correct file name
EMERGENCY! There is an unrelated error somewhere else in the project that
needs to be fixed ASAP!
Save all your files, making a note of the names of the copies you were
working on
Work on the unrelated error and update the code to fix it
Go back to the design, and finish the work there
Copy the code or rename the files, so the updated design is on the live
version
(2 weeks later, you realize that the unrelated error was not fixed in the
new design version because you copied the files before the fix)
With Git:
With a new branch called new-design, edit the code directly without
impacting the main branch
EMERGENCY! There is an unrelated error somewhere else in the project that
needs to be fixed ASAP!
Create a new branch from the main project called small-error-fix
Fix the unrelated error and merge the small-error-fix branch with the main
branch
You go back to the new-design branch, and finish the work there
Merge the new-design branch with main (getting alerted to the small error
fix that you were missing)
Branches allow you to work on different parts of a project without impacting
the main branch.
When the work is complete, a branch can be merged with the main project.
You can even switch between branches and work on different projects without
them interfering with each other.
Branching in Git is very lightweight and fast!
Let add some new features to our index.html page.
We are working in our local repository, and we do not want to disturb or possibly wreck the main project.
So we create a new branch:
git branch hello-world-images
Now we created a new branch called "hello-world-images"
Let's confirm that we have created a new branch:
git branch
hello-world-images
* master
We can see the new branch with the name "hello-world-images", but the * beside
master specifies that we are currently on that branch.
checkout is the command used to check out a branch. Moving us from the current
branch, to the one specified at the end of the command:
git checkout hello-world-images
Switched to branch 'hello-world-images'
Now we have moved our current workspace from the master branch, to the new
branch
Open your favourite editor and make some changes.
For this example, we added an
image (img_hello_world.jpg) to the working folder and a line of code in the
index.html file:
We have made changes to a file and added a new file in the working directory
(same directory as the main
branch).
Now check the status of the current branch:
git status
On branch hello-world-images
Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git restore ..." to discard changes in working directory)
modified: index.html
Untracked files:
(use "git add ..." to include in what will be committed)
img_hello_world.jpg
no changes added to commit (use "git add" and/or "git commit -a")
So let's go through what happens here:
There are changes to our index.html, but the file is not staged for
commit
img_hello_world.jpg is not
tracked
So we need to add both files to the Staging Environment for this
branch:
git add --all
Using --all instead of individual filenames
will Stage all changed (new, modified, and deleted) files.
Check the status of the
branch:
git status
On branch hello-world-images
Changes to be committed:
(use "git restore --staged ..." to unstage)
new file: img_hello_world.jpg
modified: index.html
We are happy with our changes. So we will commit them to the
branch:
git commit -m "Added image to Hello World"
[hello-world-images 0312c55] Added image to Hello World
2 files changed, 1 insertion(+)
create mode 100644 img_hello_world.jpg
Now we have a new branch, that is different from the master branch.
Note: Using the -b option
on checkout will create a new branch, and move to it, if it does not exist
Now let's see just how quick and easy it is to work with different branches, and how well it works.
We are currently on the branch hello-world-images. We added an image to this branch, so let's list the files in the current directory:
ls
README.md bluestyle.css img_hello_world.jpg index.html
We can see the new file img_hello_world.jpg, and if we open the html file, we can see the code has been altered. All is as it should be.
Now, let's see what happens when we change branch to master
git checkout master
Switched to branch 'master'
The new image is not a part of this branch. List the files in the current directory again:
ls
README.md bluestyle.css index.html
img_hello_world.jpg is no longer there! And if we open the html file, we can see the code reverted to what it was before the alteration.
See how easy it is to work with branches? And how this allows you to work on different things?
Now imagine that we are not yet done with hello-world-images, but we need to fix an error on master.
I don't want to mess with master directly, and I do not want to mess with
hello-world-images, since it is not done yet.
So we create a new branch to deal with the emergency:
git checkout -b emergency-fix
Switched to a new branch 'emergency-fix'
Now we have created a new branch from master, and changed to it. We can
safely fix the error without disturbing the other branches.
Let's fix our imaginary error:
We have made changes in this file, and we need to get those changes to the
master branch.
Check the status:
git status
On branch emergency-fix
Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git restore ..." to discard changes in working directory)
modified: index.html
no changes added to commit (use "git add" and/or "git commit -a")
stage the file, and commit:
git add index.html
git commit -m "updated index.html with emergency fix"
[emergency-fix dfa79db] updated index.html with emergency fix
1 file changed, 1 insertion(+), 1 deletion(-)
Now we have a fix ready for master, and we need to merge the two branches.
Create a new branch called hello-world-images:
git
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 67,
"s": 0,
"text": "In Git, a branch is a new/separate version of the main repository."
},
{
"code": null,
"e": 144,
"s": 67,
"text": "Let's say you have a large project, and you need to update the design on it."
},
{
"code": null,
"e": 186,
"s": 144,
"text": "How would that work without and with Git:"
},
{
"code": null,
"e": 199,
"s": 186,
"text": "Without Git:"
},
{
"code": null,
"e": 273,
"s": 199,
"text": "Make copies of all the relevant files to avoid impacting the live version"
},
{
"code": null,
"e": 386,
"s": 273,
"text": "Start working with the design and find that code depend on code in other \n files, that also need to be changed!"
},
{
"code": null,
"e": 505,
"s": 386,
"text": "Make copies of the dependant files as well. Making sure that every file \n dependency references the correct file name"
},
{
"code": null,
"e": 606,
"s": 505,
"text": "EMERGENCY! There is an unrelated error somewhere else in the project that \n needs to be fixed ASAP!"
},
{
"code": null,
"e": 691,
"s": 606,
"text": "Save all your files, making a note of the names of the copies you were \n working on"
},
{
"code": null,
"e": 749,
"s": 691,
"text": "Work on the unrelated error and update the code to fix it"
},
{
"code": null,
"e": 798,
"s": 749,
"text": "Go back to the design, and finish the work there"
},
{
"code": null,
"e": 881,
"s": 798,
"text": "Copy the code or rename the files, so the updated design is on the live \n version"
},
{
"code": null,
"e": 1022,
"s": 881,
"text": "(2 weeks later, you realize that the unrelated error was not fixed in the \n new design version because you copied the files before the fix)"
},
{
"code": null,
"e": 1032,
"s": 1022,
"text": "With Git:"
},
{
"code": null,
"e": 1129,
"s": 1032,
"text": "With a new branch called new-design, edit the code directly without \n impacting the main branch"
},
{
"code": null,
"e": 1230,
"s": 1129,
"text": "EMERGENCY! There is an unrelated error somewhere else in the project that \n needs to be fixed ASAP!"
},
{
"code": null,
"e": 1295,
"s": 1230,
"text": "Create a new branch from the main project called small-error-fix"
},
{
"code": null,
"e": 1380,
"s": 1295,
"text": "Fix the unrelated error and merge the small-error-fix branch with the main \n branch"
},
{
"code": null,
"e": 1444,
"s": 1380,
"text": "You go back to the new-design branch, and finish the work there"
},
{
"code": null,
"e": 1548,
"s": 1444,
"text": "Merge the new-design branch with main (getting alerted to the small error \n fix that you were missing)"
},
{
"code": null,
"e": 1643,
"s": 1548,
"text": "Branches allow you to work on different parts of a project without impacting \nthe main branch."
},
{
"code": null,
"e": 1716,
"s": 1643,
"text": "When the work is complete, a branch can be merged with the main project."
},
{
"code": null,
"e": 1827,
"s": 1716,
"text": "You can even switch between branches and work on different projects without \nthem interfering with each other."
},
{
"code": null,
"e": 1874,
"s": 1827,
"text": "Branching in Git is very lightweight and fast!"
},
{
"code": null,
"e": 1924,
"s": 1874,
"text": "Let add some new features to our index.html page."
},
{
"code": null,
"e": 2030,
"s": 1924,
"text": "We are working in our local repository, and we do not want to disturb or possibly wreck the main project."
},
{
"code": null,
"e": 2057,
"s": 2030,
"text": "So we create a new branch:"
},
{
"code": null,
"e": 2087,
"s": 2057,
"text": "git branch hello-world-images"
},
{
"code": null,
"e": 2143,
"s": 2087,
"text": "Now we created a new branch called \"hello-world-images\""
},
{
"code": null,
"e": 2192,
"s": 2143,
"text": "Let's confirm that we have created a new branch:"
},
{
"code": null,
"e": 2233,
"s": 2192,
"text": "git branch\n hello-world-images\n* master"
},
{
"code": null,
"e": 2368,
"s": 2233,
"text": "We can see the new branch with the name \"hello-world-images\", but the * beside \nmaster specifies that we are currently on that branch."
},
{
"code": null,
"e": 2504,
"s": 2368,
"text": "checkout is the command used to check out a branch. Moving us from the current \nbranch, to the one specified at the end of the command:"
},
{
"code": null,
"e": 2576,
"s": 2504,
"text": "git checkout hello-world-images\nSwitched to branch 'hello-world-images'"
},
{
"code": null,
"e": 2661,
"s": 2576,
"text": "Now we have moved our current workspace from the master branch, to the new \n branch"
},
{
"code": null,
"e": 2711,
"s": 2661,
"text": "Open your favourite editor and make some changes."
},
{
"code": null,
"e": 2836,
"s": 2711,
"text": "For this example, we added an \nimage (img_hello_world.jpg) to the working folder and a line of code in the \nindex.html file:"
},
{
"code": null,
"e": 2951,
"s": 2836,
"text": "We have made changes to a file and added a new file in the working directory \n(same directory as the main\nbranch)."
},
{
"code": null,
"e": 2995,
"s": 2951,
"text": "Now check the status of the current branch:"
},
{
"code": null,
"e": 3390,
"s": 2995,
"text": "git status\nOn branch hello-world-images\nChanges not staged for commit:\n (use \"git add ...\" to update what will be committed)\n (use \"git restore ...\" to discard changes in working directory)\n modified: index.html\n\nUntracked files:\n (use \"git add ...\" to include in what will be committed)\n img_hello_world.jpg\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")"
},
{
"code": null,
"e": 3429,
"s": 3390,
"text": "So let's go through what happens here:"
},
{
"code": null,
"e": 3507,
"s": 3429,
"text": "There are changes to our index.html, but the file is not staged for \n commit"
},
{
"code": null,
"e": 3545,
"s": 3507,
"text": "img_hello_world.jpg is not \n tracked"
},
{
"code": null,
"e": 3619,
"s": 3545,
"text": "So we need to add both files to the Staging Environment for this \nbranch:"
},
{
"code": null,
"e": 3633,
"s": 3619,
"text": "git add --all"
},
{
"code": null,
"e": 3737,
"s": 3633,
"text": "Using --all instead of individual filenames \nwill Stage all changed (new, modified, and deleted) files."
},
{
"code": null,
"e": 3770,
"s": 3737,
"text": "Check the status of the \nbranch:"
},
{
"code": null,
"e": 3940,
"s": 3770,
"text": "git status\nOn branch hello-world-images\nChanges to be committed:\n (use \"git restore --staged ...\" to unstage)\n new file: img_hello_world.jpg\n modified: index.html"
},
{
"code": null,
"e": 4010,
"s": 3940,
"text": "We are happy with our changes. So we will commit them to the \nbranch:"
},
{
"code": null,
"e": 4180,
"s": 4010,
"text": "git commit -m \"Added image to Hello World\"\n[hello-world-images 0312c55] Added image to Hello World\n2 files changed, 1 insertion(+)\ncreate mode 100644 img_hello_world.jpg"
},
{
"code": null,
"e": 4248,
"s": 4180,
"text": "Now we have a new branch, that is different from the master branch."
},
{
"code": null,
"e": 4352,
"s": 4248,
"text": "Note: Using the -b option \n on checkout will create a new branch, and move to it, if it does not exist"
},
{
"code": null,
"e": 4452,
"s": 4352,
"text": "Now let's see just how quick and easy it is to work with different branches, and how well it works."
},
{
"code": null,
"e": 4587,
"s": 4452,
"text": "We are currently on the branch hello-world-images. We added an image to this branch, so let's list the files in the current directory:"
},
{
"code": null,
"e": 4648,
"s": 4587,
"text": "ls\nREADME.md bluestyle.css img_hello_world.jpg index.html"
},
{
"code": null,
"e": 4785,
"s": 4648,
"text": "We can see the new file img_hello_world.jpg, and if we open the html file, we can see the code has been altered. All is as it should be."
},
{
"code": null,
"e": 4845,
"s": 4785,
"text": "Now, let's see what happens when we change branch to master"
},
{
"code": null,
"e": 4893,
"s": 4845,
"text": "git checkout master\nSwitched to branch 'master'"
},
{
"code": null,
"e": 4984,
"s": 4893,
"text": "The new image is not a part of this branch. List the files in the current directory again:"
},
{
"code": null,
"e": 5024,
"s": 4984,
"text": "ls\nREADME.md bluestyle.css index.html"
},
{
"code": null,
"e": 5161,
"s": 5024,
"text": "img_hello_world.jpg is no longer there! And if we open the html file, we can see the code reverted to what it was before the alteration."
},
{
"code": null,
"e": 5256,
"s": 5161,
"text": "See how easy it is to work with branches? And how this allows you to work on different things?"
},
{
"code": null,
"e": 5357,
"s": 5256,
"text": "Now imagine that we are not yet done with hello-world-images, but we need to fix an error on master."
},
{
"code": null,
"e": 5478,
"s": 5357,
"text": "I don't want to mess with master directly, and I do not want to mess with \nhello-world-images, since it is not done yet."
},
{
"code": null,
"e": 5532,
"s": 5478,
"text": "So we create a new branch to deal with the emergency:"
},
{
"code": null,
"e": 5603,
"s": 5532,
"text": "git checkout -b emergency-fix\nSwitched to a new branch 'emergency-fix'"
},
{
"code": null,
"e": 5736,
"s": 5603,
"text": "Now we have created a new branch from master, and changed to it. We can \nsafely fix the error without disturbing the other branches."
},
{
"code": null,
"e": 5767,
"s": 5736,
"text": "Let's fix our imaginary error:"
},
{
"code": null,
"e": 5858,
"s": 5767,
"text": "We have made changes in this file, and we need to get those changes to the \nmaster branch."
},
{
"code": null,
"e": 5876,
"s": 5858,
"text": "Check the status:"
},
{
"code": null,
"e": 6161,
"s": 5876,
"text": "git status\nOn branch emergency-fix\nChanges not staged for commit:\n (use \"git add ...\" to update what will be committed)\n (use \"git restore ...\" to discard changes in working directory)\n modified: index.html\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")"
},
{
"code": null,
"e": 6189,
"s": 6161,
"text": "stage the file, and commit:"
},
{
"code": null,
"e": 6371,
"s": 6189,
"text": "git add index.html\ngit commit -m \"updated index.html with emergency fix\"\n[emergency-fix dfa79db] updated index.html with emergency fix\n 1 file changed, 1 insertion(+), 1 deletion(-)"
},
{
"code": null,
"e": 6446,
"s": 6371,
"text": "Now we have a fix ready for master, and we need to merge the two branches."
},
{
"code": null,
"e": 6493,
"s": 6446,
"text": "Create a new branch called hello-world-images:"
},
{
"code": null,
"e": 6500,
"s": 6493,
"text": "git \n"
},
{
"code": null,
"e": 6520,
"s": 6500,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 6553,
"s": 6520,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 6595,
"s": 6553,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 6702,
"s": 6595,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 6721,
"s": 6702,
"text": "help@w3schools.com"
}
] |
How to get creation and modification date/time of a file using Python?
|
To get the creation time of a file, you can use the os.path.getctime(file_path) on windows. On UNIX systems, you cant use the same function as it returns the last time that the file's attributes or content were changed. To get the creation time on UNIX based systems, use the st_birthtime attribute of the stat tuple.
On Windows −
>>> import os
>>> print os.path.getctime('my_file')
1505928271.0689342
It gives the time in the number of seconds since the epoch. For UNIX systems,
import os
stat = os.stat(path_to_file)
try:
print(stat.st_birthtime)
except AttributeError:
# Probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
print(stat.st_mtime)
This will give the output −
1505928271.0689342
For getting the modification time for a file, you can use the os.path.getmtime(path). It is supported cross-platform.For example,
>>> import os
>>> print os.path.getmtime('my_file')
1505928275.3081832
|
[
{
"code": null,
"e": 1380,
"s": 1062,
"text": "To get the creation time of a file, you can use the os.path.getctime(file_path) on windows. On UNIX systems, you cant use the same function as it returns the last time that the file's attributes or content were changed. To get the creation time on UNIX based systems, use the st_birthtime attribute of the stat tuple."
},
{
"code": null,
"e": 1393,
"s": 1380,
"text": "On Windows −"
},
{
"code": null,
"e": 1464,
"s": 1393,
"text": ">>> import os\n>>> print os.path.getctime('my_file')\n1505928271.0689342"
},
{
"code": null,
"e": 1542,
"s": 1464,
"text": "It gives the time in the number of seconds since the epoch. For UNIX systems,"
},
{
"code": null,
"e": 1790,
"s": 1542,
"text": "import os\nstat = os.stat(path_to_file)\ntry:\n print(stat.st_birthtime)\nexcept AttributeError:\n # Probably on Linux. No easy way to get creation dates here,\n # so we'll settle for when its content was last modified.\n print(stat.st_mtime)"
},
{
"code": null,
"e": 1818,
"s": 1790,
"text": "This will give the output −"
},
{
"code": null,
"e": 1837,
"s": 1818,
"text": "1505928271.0689342"
},
{
"code": null,
"e": 1967,
"s": 1837,
"text": "For getting the modification time for a file, you can use the os.path.getmtime(path). It is supported cross-platform.For example,"
},
{
"code": null,
"e": 2038,
"s": 1967,
"text": ">>> import os\n>>> print os.path.getmtime('my_file')\n1505928275.3081832"
}
] |
Java Program to Sort a HashMap by Keys and Values - GeeksforGeeks
|
08 Jun, 2021
HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate key, it will replace the element of the corresponding key.
HashMap Sorting by Values
The idea is to store the entry set in a list and then sort the list based on values using the Collections.sort() method with the help of Comparator. Then fetch the value for each key from the list and then display the result.
Example
Java
// Java program to sort Hashmap based on values import java.lang.*;import java.util.*; public class GFG { // function to sort hashmap based on values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Creating a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >( hm.entrySet()); // Sorting the list using Collections.sort() method // using Comparator Collections.sort( list, new Comparator<Map.Entry<String, Integer> >() { public int compare( Map.Entry<String, Integer> object1, Map.Entry<String, Integer> object2) { return (object1.getValue()) .compareTo(object2.getValue()); } }); // putting the data from sorted list back to hashmap HashMap<String, Integer> result = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> me : list) { result.put(me.getKey(), me.getValue()); } // returning the sorted HashMap return result; } // Driver Code public static void main(String[] args) { // creating object of HashMap class HashMap<String, Integer> hashmap = new HashMap<String, Integer>(); // inserting key-value pair into hashmap hashmap.put("five", 5); hashmap.put("seven", 7); hashmap.put("three", 3); hashmap.put("nine", 9); hashmap.put("zero", 0); hashmap.put("eight", 8); // sorting the HashMap based on values Map<String, Integer> map = sortByValue(hashmap); // print the sorted hashmap(based on values) for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue()); } }}
Key : zero, Value : 0
Key : three, Value : 3
Key : five, Value : 5
Key : seven, Value : 7
Key : eight, Value : 8
Key : nine, Value : 9
HashMap Sorting by Keys
The idea is to put all data of HashMap into an ArrayList.Then extract all the keys of HashMap into an ArrayList. Next, sort the extracted keys using the Collections.sort() method, and then for each key extract its value using the get() method. Finally, the map is sorted according to its keys.
Example
Java
// Java Code to sort Map by key valueimport java.util.*;class GFG { // This map stores unsorted values static HashMap<Integer, String> m = new HashMap<>(); // Function to sort map by Key public static void sortMapByKey() { ArrayList<Integer> sortKeys = new ArrayList<Integer>(m.keySet()); Collections.sort(sortKeys); // Getting value for each key and displaying // results. for (Integer x : sortKeys) System.out.println("Key = " + x + ", Value = " + m.get(x)); } // Driver Code public static void main(String args[]) { // putting values in the Map m.put(7, "seven"); m.put(5, "five"); m.put(1, "one"); m.put(3, "three"); m.put(9, "nine"); // Calling the function to sortMapByKey to // perform sorting based on keys sortMapByKey(); }}
Key = 1, Value = one
Key = 3, Value = three
Key = 5, Value = five
Key = 7, Value = seven
Key = 9, Value = nine
ruhelaa48
Java-HashMap
Picked
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 23910,
"s": 23557,
"text": "HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate key, it will replace the element of the corresponding key."
},
{
"code": null,
"e": 23936,
"s": 23910,
"text": "HashMap Sorting by Values"
},
{
"code": null,
"e": 24162,
"s": 23936,
"text": "The idea is to store the entry set in a list and then sort the list based on values using the Collections.sort() method with the help of Comparator. Then fetch the value for each key from the list and then display the result."
},
{
"code": null,
"e": 24170,
"s": 24162,
"text": "Example"
},
{
"code": null,
"e": 24175,
"s": 24170,
"text": "Java"
},
{
"code": "// Java program to sort Hashmap based on values import java.lang.*;import java.util.*; public class GFG { // function to sort hashmap based on values public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Creating a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >( hm.entrySet()); // Sorting the list using Collections.sort() method // using Comparator Collections.sort( list, new Comparator<Map.Entry<String, Integer> >() { public int compare( Map.Entry<String, Integer> object1, Map.Entry<String, Integer> object2) { return (object1.getValue()) .compareTo(object2.getValue()); } }); // putting the data from sorted list back to hashmap HashMap<String, Integer> result = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> me : list) { result.put(me.getKey(), me.getValue()); } // returning the sorted HashMap return result; } // Driver Code public static void main(String[] args) { // creating object of HashMap class HashMap<String, Integer> hashmap = new HashMap<String, Integer>(); // inserting key-value pair into hashmap hashmap.put(\"five\", 5); hashmap.put(\"seven\", 7); hashmap.put(\"three\", 3); hashmap.put(\"nine\", 9); hashmap.put(\"zero\", 0); hashmap.put(\"eight\", 8); // sorting the HashMap based on values Map<String, Integer> map = sortByValue(hashmap); // print the sorted hashmap(based on values) for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(\"Key : \" + entry.getKey() + \", Value : \" + entry.getValue()); } }}",
"e": 26253,
"s": 24175,
"text": null
},
{
"code": null,
"e": 26391,
"s": 26256,
"text": "Key : zero, Value : 0\nKey : three, Value : 3\nKey : five, Value : 5\nKey : seven, Value : 7\nKey : eight, Value : 8\nKey : nine, Value : 9"
},
{
"code": null,
"e": 26417,
"s": 26393,
"text": "HashMap Sorting by Keys"
},
{
"code": null,
"e": 26713,
"s": 26419,
"text": "The idea is to put all data of HashMap into an ArrayList.Then extract all the keys of HashMap into an ArrayList. Next, sort the extracted keys using the Collections.sort() method, and then for each key extract its value using the get() method. Finally, the map is sorted according to its keys."
},
{
"code": null,
"e": 26723,
"s": 26715,
"text": "Example"
},
{
"code": null,
"e": 26730,
"s": 26725,
"text": "Java"
},
{
"code": "// Java Code to sort Map by key valueimport java.util.*;class GFG { // This map stores unsorted values static HashMap<Integer, String> m = new HashMap<>(); // Function to sort map by Key public static void sortMapByKey() { ArrayList<Integer> sortKeys = new ArrayList<Integer>(m.keySet()); Collections.sort(sortKeys); // Getting value for each key and displaying // results. for (Integer x : sortKeys) System.out.println(\"Key = \" + x + \", Value = \" + m.get(x)); } // Driver Code public static void main(String args[]) { // putting values in the Map m.put(7, \"seven\"); m.put(5, \"five\"); m.put(1, \"one\"); m.put(3, \"three\"); m.put(9, \"nine\"); // Calling the function to sortMapByKey to // perform sorting based on keys sortMapByKey(); }}",
"e": 27650,
"s": 26730,
"text": null
},
{
"code": null,
"e": 27764,
"s": 27653,
"text": "Key = 1, Value = one\nKey = 3, Value = three\nKey = 5, Value = five\nKey = 7, Value = seven\nKey = 9, Value = nine"
},
{
"code": null,
"e": 27776,
"s": 27766,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27789,
"s": 27776,
"text": "Java-HashMap"
},
{
"code": null,
"e": 27796,
"s": 27789,
"text": "Picked"
},
{
"code": null,
"e": 27801,
"s": 27796,
"text": "Java"
},
{
"code": null,
"e": 27815,
"s": 27801,
"text": "Java Programs"
},
{
"code": null,
"e": 27834,
"s": 27815,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27839,
"s": 27834,
"text": "Java"
},
{
"code": null,
"e": 27937,
"s": 27839,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27946,
"s": 27937,
"text": "Comments"
},
{
"code": null,
"e": 27959,
"s": 27946,
"text": "Old Comments"
},
{
"code": null,
"e": 27989,
"s": 27959,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28004,
"s": 27989,
"text": "Stream In Java"
},
{
"code": null,
"e": 28025,
"s": 28004,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28071,
"s": 28025,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28090,
"s": 28071,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28134,
"s": 28090,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28160,
"s": 28134,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28194,
"s": 28160,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28241,
"s": 28194,
"text": "Implementing a Linked List in Java using Class"
}
] |
What is the difference between ODBC and JDBC
|
Both ODBC and JDBC are the programming interface that is required by the applications at the client side to access the database at server side. Basically both are known as drivers to get connected with a database and are provided by the vendors of RDBMS.
The following are the important differences between ODBC and JDBC.
ODBC connection in c#
using System;
using System.Windows.Forms;
using System.Data.Odbc;
namespace WindowsApplication1{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
string connetionString = null;
OdbcConnection cnn ;
connetionString = "Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;";
cnn = new OdbcConnection(connetionString);
try{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex){
MessageBox.Show("Can not open connection ! ");
}
}
}
}
JDBC connection in java
import java.sql.*;
class JavaTester{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/'yourDBname'","username","userpassword");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){ System.out.println(e);}
}
}
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "Both ODBC and JDBC are the programming interface that is required by the applications at the client side to access the database at server side. Basically both are known as drivers to get connected with a database and are provided by the vendors of RDBMS."
},
{
"code": null,
"e": 1384,
"s": 1317,
"text": "The following are the important differences between ODBC and JDBC."
},
{
"code": null,
"e": 1406,
"s": 1384,
"text": "ODBC connection in c#"
},
{
"code": null,
"e": 2126,
"s": 1406,
"text": "using System;\nusing System.Windows.Forms;\nusing System.Data.Odbc;\nnamespace WindowsApplication1{\n public partial class Form1 : Form{\n public Form1(){\n InitializeComponent();\n }\n private void button1_Click(object sender, EventArgs e){\n string connetionString = null;\n OdbcConnection cnn ;\n connetionString = \"Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;\";\n cnn = new OdbcConnection(connetionString);\n try{\n cnn.Open();\n MessageBox.Show (\"Connection Open ! \");\n cnn.Close();\n }\n catch (Exception ex){\n MessageBox.Show(\"Can not open connection ! \");\n }\n }\n }\n}"
},
{
"code": null,
"e": 2150,
"s": 2126,
"text": "JDBC connection in java"
},
{
"code": null,
"e": 2728,
"s": 2150,
"text": "import java.sql.*;\nclass JavaTester{\n public static void main(String args[]){\n try{\n Class.forName(\"com.mysql.jdbc.Driver\");\n Connection con=DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/'yourDBname'\",\"username\",\"userpassword\");\n Statement stmt=con.createStatement();\n ResultSet rs=stmt.executeQuery(\"select * from emp\");\n while(rs.next())\n System.out.println(rs.getInt(1)+\" \"+rs.getString(2)+\" \"+rs.getString(3));\n con.close();\n }\n catch(Exception e){ System.out.println(e);}\n }\n}"
}
] |
Circular Linked List Program in C
|
Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a circular linked list.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
bool isEmpty() {
return head == NULL;
}
int length() {
int length = 0;
//if list is empty
if(head == NULL) {
return 0;
}
current = head->next;
while(current != head) {
length++;
current = current->next;
}
return length;
}
//insert link at the first location
void insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if (isEmpty()) {
head = link;
head->next = head;
} else {
//point it to old first node
link->next = head;
//point first to new first node
head = link;
}
}
//delete first item
struct node * deleteFirst() {
//save reference to first link
struct node *tempLink = head;
if(head->next == head) {
head = NULL;
return tempLink;
}
//mark next to first link as first
head = head->next;
//return the deleted link
return tempLink;
}
//display the list
void printList() {
struct node *ptr = head;
printf("\n[ ");
//start from the beginning
if(head != NULL) {
while(ptr->next != ptr) {
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
}
printf(" ]");
}
void main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Original List: ");
//print list
printList();
while(!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}
printf("\nList after deleting all items: ");
printList();
}
If we compile and run the above program, it will produce the following result −
Original List:
[ (6,56) (5,40) (4,1) (3,30) (2,20) ]
Deleted value:(6,56)
Deleted value:(5,40)
Deleted value:(4,1)
Deleted value:(3,30)
Deleted value:(2,20)
Deleted value:(1,10)
List after deleting all items:
[ ]
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2823,
"s": 2580,
"text": "Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a circular linked list."
},
{
"code": null,
"e": 4774,
"s": 2823,
"text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nstruct node {\n int data;\n int key;\n\t\n struct node *next;\n};\n\nstruct node *head = NULL;\nstruct node *current = NULL;\n\nbool isEmpty() {\n return head == NULL;\n}\n\nint length() {\n int length = 0;\n\n //if list is empty\n if(head == NULL) {\n return 0;\n }\n\n current = head->next;\n\n while(current != head) {\n length++;\n current = current->next; \n }\n\t\n return length;\n}\n\n//insert link at the first location\nvoid insertFirst(int key, int data) {\n\n //create a link\n struct node *link = (struct node*) malloc(sizeof(struct node));\n link->key = key;\n link->data = data;\n\t\n if (isEmpty()) {\n head = link;\n head->next = head;\n } else {\n //point it to old first node\n link->next = head;\n\t\t\n //point first to new first node\n head = link;\n } \n}\n\n//delete first item\nstruct node * deleteFirst() {\n\n //save reference to first link\n struct node *tempLink = head;\n\t\n if(head->next == head) { \n head = NULL;\n return tempLink;\n } \n\n //mark next to first link as first \n head = head->next;\n\t\n //return the deleted link\n return tempLink;\n}\n\n//display the list\nvoid printList() {\n\n struct node *ptr = head;\n printf(\"\\n[ \");\n\t\n //start from the beginning\n if(head != NULL) {\n\t\n while(ptr->next != ptr) { \n printf(\"(%d,%d) \",ptr->key,ptr->data);\n ptr = ptr->next;\n }\n }\n\t\n printf(\" ]\");\n}\n\nvoid main() {\n insertFirst(1,10);\n insertFirst(2,20);\n insertFirst(3,30);\n insertFirst(4,1);\n insertFirst(5,40);\n insertFirst(6,56); \n\n printf(\"Original List: \"); \n\t\n //print list\n printList();\n\n while(!isEmpty()) { \n struct node *temp = deleteFirst();\n printf(\"\\nDeleted value:\"); \n printf(\"(%d,%d) \",temp->key,temp->data);\n } \n\t\n printf(\"\\nList after deleting all items: \");\n printList(); \n}"
},
{
"code": null,
"e": 4854,
"s": 4774,
"text": "If we compile and run the above program, it will produce the following result −"
},
{
"code": null,
"e": 5076,
"s": 4854,
"text": "Original List: \n[ (6,56) (5,40) (4,1) (3,30) (2,20) ]\nDeleted value:(6,56) \nDeleted value:(5,40) \nDeleted value:(4,1) \nDeleted value:(3,30) \nDeleted value:(2,20) \nDeleted value:(1,10) \nList after deleting all items: \n[ ]\n"
},
{
"code": null,
"e": 5111,
"s": 5076,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5123,
"s": 5111,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 5158,
"s": 5123,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5177,
"s": 5158,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5212,
"s": 5177,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5227,
"s": 5212,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5260,
"s": 5227,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5279,
"s": 5260,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5313,
"s": 5279,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5341,
"s": 5313,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5377,
"s": 5341,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5405,
"s": 5377,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5412,
"s": 5405,
"text": " Print"
},
{
"code": null,
"e": 5423,
"s": 5412,
"text": " Add Notes"
}
] |
Back-off Algorithm for CSMA/CD
|
Back Off Algorithm is an algorithm used for collision resolution. It works as,
When this collision occurs, both the devices wait for a random amount of time before retransmitting the signal again, they keep on trying until the data is transferred successfully. This is called back off, since the nodes ‘back-off’ for a certain amount of time, before they try to re-access it again. This random amount of time is directly proportional to the number of attempts it has made to transmit the signal.
Below is a simple flowchart to explain the Back Off Algorithm in brief.
As can be seen, that after each iteration value of N increases and so does the range [0,2^n-1], this way the probability of collisions decreases!
Moreover, it can be a drawback in some cases because continuous back-off can cause some nodes to discard packets. After all, maximum attempt limits have been reached.
So, after the collision, each node has to wait for a certain amount of time which is given by the formula,
Waiting time = K * Tslot
Tslot is the discrete-time slot of length equal to 2t, where t is the maximum propagation delay in the network.
K = [0, 2n -1]. n is the collision number.
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "Back Off Algorithm is an algorithm used for collision resolution. It works as,"
},
{
"code": null,
"e": 1558,
"s": 1141,
"text": "When this collision occurs, both the devices wait for a random amount of time before retransmitting the signal again, they keep on trying until the data is transferred successfully. This is called back off, since the nodes ‘back-off’ for a certain amount of time, before they try to re-access it again. This random amount of time is directly proportional to the number of attempts it has made to transmit the signal."
},
{
"code": null,
"e": 1630,
"s": 1558,
"text": "Below is a simple flowchart to explain the Back Off Algorithm in brief."
},
{
"code": null,
"e": 1776,
"s": 1630,
"text": "As can be seen, that after each iteration value of N increases and so does the range [0,2^n-1], this way the probability of collisions decreases!"
},
{
"code": null,
"e": 1943,
"s": 1776,
"text": "Moreover, it can be a drawback in some cases because continuous back-off can cause some nodes to discard packets. After all, maximum attempt limits have been reached."
},
{
"code": null,
"e": 2050,
"s": 1943,
"text": "So, after the collision, each node has to wait for a certain amount of time which is given by the formula,"
},
{
"code": null,
"e": 2075,
"s": 2050,
"text": "Waiting time = K * Tslot"
},
{
"code": null,
"e": 2187,
"s": 2075,
"text": "Tslot is the discrete-time slot of length equal to 2t, where t is the maximum propagation delay in the network."
},
{
"code": null,
"e": 2230,
"s": 2187,
"text": "K = [0, 2n -1]. n is the collision number."
}
] |
How to get time difference between two timestamps in seconds?
|
To get the time difference between two timestamps, try to run the following code. Here, we are calculating the total number of hours, minutes and seconds between two timestamps −
Live Demo
<html>
<head>
<title>JavaScript Dates</title>
</head>
<body>
<script>
var date1, date2;
date1 = new Date( "Jan 1, 2018 11:10:05" );
document.write(""+date1);
date2 = new Date( "Jan 1, 2018 08:15:10" );
document.write("<br>"+date2);
var res = Math.abs(date1 - date2) / 1000;
// get total days between two dates
var days = Math.floor(res / 86400);
document.write("<br>Difference (Days): "+days);
// get hours
var hours = Math.floor(res / 3600) % 24;
document.write("<br>Difference (Hours): "+hours);
// get minutes
var minutes = Math.floor(res / 60) % 60;
document.write("<br>Difference (Minutes): "+minutes);
// get seconds
var seconds = res % 60;
document.write("<br>Difference (Seconds): "+seconds);
</script>
</body>
</html>
Mon Jan 01 2018 11:10:05 GMT+0530 (India Standard Time)
Mon Jan 01 2018 08:15:10 GMT+0530 (India Standard Time)
Difference (Days): 0
Difference (Hours): 2
Difference (Minutes): 54
Difference (Seconds): 55
|
[
{
"code": null,
"e": 1241,
"s": 1062,
"text": "To get the time difference between two timestamps, try to run the following code. Here, we are calculating the total number of hours, minutes and seconds between two timestamps −"
},
{
"code": null,
"e": 1251,
"s": 1241,
"text": "Live Demo"
},
{
"code": null,
"e": 2259,
"s": 1251,
"text": "<html>\n <head>\n <title>JavaScript Dates</title>\n </head>\n <body>\n <script> \n var date1, date2; \n\n date1 = new Date( \"Jan 1, 2018 11:10:05\" );\n document.write(\"\"+date1);\n\n date2 = new Date( \"Jan 1, 2018 08:15:10\" );\n document.write(\"<br>\"+date2);\n\n var res = Math.abs(date1 - date2) / 1000;\n \n // get total days between two dates\n var days = Math.floor(res / 86400);\n document.write(\"<br>Difference (Days): \"+days); \n \n // get hours \n var hours = Math.floor(res / 3600) % 24; \n document.write(\"<br>Difference (Hours): \"+hours); \n \n // get minutes\n var minutes = Math.floor(res / 60) % 60;\n document.write(\"<br>Difference (Minutes): \"+minutes); \n \n // get seconds\n var seconds = res % 60;\n document.write(\"<br>Difference (Seconds): \"+seconds); \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2464,
"s": 2259,
"text": "Mon Jan 01 2018 11:10:05 GMT+0530 (India Standard Time)\nMon Jan 01 2018 08:15:10 GMT+0530 (India Standard Time)\nDifference (Days): 0\nDifference (Hours): 2\nDifference (Minutes): 54\nDifference (Seconds): 55"
}
] |
How to combine multiple columns into one in R data frame without using column names?
|
To combine multiple columns into one in R data frame without using column names, we
can follow the below steps −
First of all, create a data frame.
Then, convert the data frame into a single column data frame.
Again, convert the data frame into a single column without column names
displayed in rows using row.names function.
Let's create a data frame as shown below −
Live Demo
x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y z a b c
1 48 6 8 48 49 22
2 7 34 48 28 17 17
3 25 40 1 22 12 29
4 38 21 27 33 8 5
5 5 20 7 50 46 32
Using unlist function to convert df into a single data frame −
Live Demo
x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
data.frame(unlist(df))
unlist.df.
x1 48
x2 7
x3 25
x4 38
x5 5
y1 6
y2 34
y3 40
y4 21
y5 20
z1 8
z2 48
z3 1
z4 27
z5 7
a1 48
a2 28
a3 22
a4 33
a5 50
b1 49
b2 17
b3 12
b4 8
b5 46
c1 22
c2 17
c3 29
c4 5
c5 32
Using unlist function to convert df into a single data frame without row numbers
represented by column names −
Live Demo
x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
data.frame(One=unlist(df,use.names=FALSE))
One
1 48
2 7
3 25
4 38
5 5
6 6
7 34
8 40
9 21
10 20
11 8
12 48
13 1
14 27
15 7
16 48
17 28
18 22
19 33
20 50
21 49
22 17
23 12
24 8
25 46
26 22
27 17
28 29
29 5
30 32
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "To combine multiple columns into one in R data frame without using column names, we\ncan follow the below steps −"
},
{
"code": null,
"e": 1210,
"s": 1175,
"text": "First of all, create a data frame."
},
{
"code": null,
"e": 1272,
"s": 1210,
"text": "Then, convert the data frame into a single column data frame."
},
{
"code": null,
"e": 1388,
"s": 1272,
"text": "Again, convert the data frame into a single column without column names\ndisplayed in rows using row.names function."
},
{
"code": null,
"e": 1431,
"s": 1388,
"text": "Let's create a data frame as shown below −"
},
{
"code": null,
"e": 1442,
"s": 1431,
"text": " Live Demo"
},
{
"code": null,
"e": 1581,
"s": 1442,
"text": "x<-sample(1:50,5)\ny<-sample(1:50,5)\nz<-sample(1:50,5)\na<-sample(1:50,5)\nb<-sample(1:50,5)\nc<-sample(1:50,5)\ndf<-data.frame(x,y,z,a,b,c)\ndf"
},
{
"code": null,
"e": 1700,
"s": 1581,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 1810,
"s": 1700,
"text": " x y z a b c\n1 48 6 8 48 49 22\n2 7 34 48 28 17 17\n3 25 40 1 22 12 29\n4 38 21 27 33 8 5\n5 5 20 7 50 46 32"
},
{
"code": null,
"e": 1873,
"s": 1810,
"text": "Using unlist function to convert df into a single data frame −"
},
{
"code": null,
"e": 1884,
"s": 1873,
"text": " Live Demo"
},
{
"code": null,
"e": 2043,
"s": 1884,
"text": "x<-sample(1:50,5)\ny<-sample(1:50,5)\nz<-sample(1:50,5)\na<-sample(1:50,5)\nb<-sample(1:50,5)\nc<-sample(1:50,5)\ndf<-data.frame(x,y,z,a,b,c)\ndata.frame(unlist(df))"
},
{
"code": null,
"e": 2226,
"s": 2043,
"text": "unlist.df.\nx1 48\nx2 7\nx3 25\nx4 38\nx5 5\ny1 6\ny2 34\ny3 40\ny4 21\ny5 20\nz1 8\nz2 48\nz3 1\nz4 27\nz5 7\na1 48\na2 28\na3 22\na4 33\na5 50\nb1 49\nb2 17\nb3 12\nb4 8\nb5 46\nc1 22\nc2 17\nc3 29\nc4 5\nc5 32"
},
{
"code": null,
"e": 2337,
"s": 2226,
"text": "Using unlist function to convert df into a single data frame without row numbers\nrepresented by column names −"
},
{
"code": null,
"e": 2348,
"s": 2337,
"text": " Live Demo"
},
{
"code": null,
"e": 2527,
"s": 2348,
"text": "x<-sample(1:50,5)\ny<-sample(1:50,5)\nz<-sample(1:50,5)\na<-sample(1:50,5)\nb<-sample(1:50,5)\nc<-sample(1:50,5)\ndf<-data.frame(x,y,z,a,b,c)\ndata.frame(One=unlist(df,use.names=FALSE))"
},
{
"code": null,
"e": 2695,
"s": 2527,
"text": " One\n1 48\n2 7\n3 25\n4 38\n5 5\n6 6\n7 34\n8 40\n9 21\n10 20\n11 8\n12 48\n13 1\n14 27\n15 7\n16 48\n17 28\n18 22\n19 33\n20 50\n21 49\n22 17\n23 12\n24 8\n25 46\n26 22\n27 17\n28 29\n29 5\n30 32"
}
] |
nCr | Practice | GeeksforGeeks
|
Given two integers n and r, find nCr. Since the answer may be very large, calculate the answer modulo 109+7.
Example 1:
Input: n = 3, r = 2
Output: 3
Explaination: 3C2 = 3.
Example 2:
Input: n = 2, r = 4
Output: 0
Explaination: r is greater than n.
Your Task:
You do not need to take input or print anything. Your task is to complete the function nCr() which takes n and r as input parameters and returns nCr modulo 109+7..
Expected Time Complexity: O(n*r)
Expected Auxiliary Space: O(r)
Constraints:
1 ≤ n ≤ 1000
1 ≤ r ≤ 800
0
bijeshkumarch15 hours ago
#in just 0.3
#store the values of fact_r only and use it for others
if r>n: return 0 if r==0: return 1 arr=[0]*r tmp=1 fact_r=1 while tmp<=r: fact_r*=tmp arr[tmp-1]=fact_r tmp+=1 n_r=n-r fact_n_r=1 if n_r<=r: fact_n_r=arr[n_r-1] else: fact_n_r=fact_r tmp1=r+1 while tmp1<=n_r: fact_n_r*=tmp1 tmp1+=1 fact_n=fact_r tmp1=r+1 while tmp1<=n: fact_n*=tmp1 tmp1+=1 res=(fact_n//(fact_n_r*fact_r))%1000000007 return res
0
18pa1a047716 hours ago
top down
def ncr(self,n,r,dp): if r>n: return 0 if r==n or r==0: return 1 if dp[n][r]!=-1: return dp[n][r] dp[n][r]=self.ncr(n-1,r-1,dp)%(10**9+7)+self.ncr(n-1,r,dp)%(10**9+7) return dp[n][r]%(10**9+7)
0
moaslam8262 days ago
c++ easy soln
const int M=1e9+7;
int fun(int n,int r,vector<vector<int>> &dp){
if(dp[n][r]!=-1) return dp[n][r];
if(n==0) return dp[n][r]=0;
if(r==0) return dp[n][r]=1;
if(r==n) return dp[n][r]=1;
int a=fun(n-1,r-1,dp)%M;
int b=fun(n-1,r,dp)%M;
int ans=a+b;
ans%=M;
return dp[n][r]=ans;
}
int nCr(int n, int r){
vector<vector<int>> dp(n+1,vector<int>(r+1,-1));
return fun(n,r,dp);
}
0
chandankasamsetty4 days ago
class Solution{
int p = 1e9+7;
public:
int helper(int n,int r,vector<vector<int>>&dp)
{
if(r==0|r==n)
return 1;
if(dp[n][r]!=-1)
return dp[n][r];
else
return dp[n][r] = (helper(n-1,r-1,dp)%p+helper(n-1,r,dp)%p)%p;
}
int nCr(int n, int r){
vector<vector<int>>dp(n+1,vector<int>(r+1,-1));
if(n<r)
return 0;
else
return helper(n,r,dp);
}
};
+1
sdmrf3 weeks ago
Python Soln:
from math import factorial as F
class Solution:
def nCr(self, n, r):
return (F(n)//(F(r)*F(abs(n-r))))%(10**9+7)
+1
mailtoamandeepsingh281 month ago
C++ code
int nCr(int n, int r){ if(r>n) return 0; if(r==n) return 1; if((n-r)<r) r=n-r; int mod = 1000000007; vector<int>dp(r+1, 0); dp[0]=1; for(int i=1;i<=n;i++){ for(int j=min(r, i);j>=1;j--){ dp[j] = (dp[j] + dp[j-1])%mod; } } return dp[r]; }
0
ankitghanghas10721 month ago
int inf = 1e9 + 7;
int nCr(int n, int r){ // code here if(r > n) return 0; if(r == n || r == 0) return 1; if(r == 1) return n; if(r > (n-r)) return nCr(n,n-r); long long dp[n+1][r+1]; for(int j = 1; j<=n; j++) dp[j][1] = j; for(int i = 2; i<=n; i++){ for(int j = 2; j<=r && j<=i; j++){ if(i == j) dp[i][j] = 1; else dp[i][j] = (dp[i-1][j-1] + dp[i-1][j])%inf; } } return dp[n][r]; }
0
annanyamathur1 month ago
int approx=1e9+7; int nCr(int n, int r){ vector<int>memo(r+1,0); memo[0]=1; for(int i=1;i<=n;i++) { for(int j=r;j>0;j--) { memo[j]=(memo[j-1]%approx+memo[j]%approx)%approx; } } return memo[r]; }
-1
swapniltayal4222 months ago
class Solution: def nCr(self, n, r): # code here if r > n: return 0 def fact(n): p = 1 for i in range(1, n+1): p = p * i return p return (fact(n)//(fact(r)*fact(n-r)))%1000000007
0
swapniltayal4222 months ago
class Solution: def nCr(self, n, r): # code here if r > n: return 0 def fact(n): p = 1 for i in range(1, n+1): p = p * i return p a = fact(n) b = fact(r) c = fact(n-r) d = b*c s = (a//d)%1000000007 return s
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": 347,
"s": 238,
"text": "Given two integers n and r, find nCr. Since the answer may be very large, calculate the answer modulo 109+7."
},
{
"code": null,
"e": 358,
"s": 347,
"text": "Example 1:"
},
{
"code": null,
"e": 412,
"s": 358,
"text": "Input: n = 3, r = 2\nOutput: 3\nExplaination: 3C2 = 3. "
},
{
"code": null,
"e": 424,
"s": 412,
"text": "\nExample 2:"
},
{
"code": null,
"e": 489,
"s": 424,
"text": "Input: n = 2, r = 4\nOutput: 0\nExplaination: r is greater than n."
},
{
"code": null,
"e": 665,
"s": 489,
"text": "\nYour Task:\nYou do not need to take input or print anything. Your task is to complete the function nCr() which takes n and r as input parameters and returns nCr modulo 109+7.."
},
{
"code": null,
"e": 730,
"s": 665,
"text": "\nExpected Time Complexity: O(n*r)\nExpected Auxiliary Space: O(r)"
},
{
"code": null,
"e": 769,
"s": 730,
"text": "\nConstraints:\n1 ≤ n ≤ 1000\n1 ≤ r ≤ 800"
},
{
"code": null,
"e": 771,
"s": 769,
"text": "0"
},
{
"code": null,
"e": 797,
"s": 771,
"text": "bijeshkumarch15 hours ago"
},
{
"code": null,
"e": 810,
"s": 797,
"text": "#in just 0.3"
},
{
"code": null,
"e": 865,
"s": 810,
"text": "#store the values of fact_r only and use it for others"
},
{
"code": null,
"e": 1434,
"s": 867,
"text": "if r>n: return 0 if r==0: return 1 arr=[0]*r tmp=1 fact_r=1 while tmp<=r: fact_r*=tmp arr[tmp-1]=fact_r tmp+=1 n_r=n-r fact_n_r=1 if n_r<=r: fact_n_r=arr[n_r-1] else: fact_n_r=fact_r tmp1=r+1 while tmp1<=n_r: fact_n_r*=tmp1 tmp1+=1 fact_n=fact_r tmp1=r+1 while tmp1<=n: fact_n*=tmp1 tmp1+=1 res=(fact_n//(fact_n_r*fact_r))%1000000007 return res"
},
{
"code": null,
"e": 1436,
"s": 1434,
"text": "0"
},
{
"code": null,
"e": 1459,
"s": 1436,
"text": "18pa1a047716 hours ago"
},
{
"code": null,
"e": 1468,
"s": 1459,
"text": "top down"
},
{
"code": null,
"e": 1725,
"s": 1468,
"text": " def ncr(self,n,r,dp): if r>n: return 0 if r==n or r==0: return 1 if dp[n][r]!=-1: return dp[n][r] dp[n][r]=self.ncr(n-1,r-1,dp)%(10**9+7)+self.ncr(n-1,r,dp)%(10**9+7) return dp[n][r]%(10**9+7)"
},
{
"code": null,
"e": 1731,
"s": 1729,
"text": "0"
},
{
"code": null,
"e": 1752,
"s": 1731,
"text": "moaslam8262 days ago"
},
{
"code": null,
"e": 1766,
"s": 1752,
"text": "c++ easy soln"
},
{
"code": null,
"e": 2164,
"s": 1766,
"text": "const int M=1e9+7;\nint fun(int n,int r,vector<vector<int>> &dp){\n\tif(dp[n][r]!=-1) return dp[n][r];\n\tif(n==0) return dp[n][r]=0;\n\tif(r==0) return dp[n][r]=1;\n\tif(r==n) return dp[n][r]=1;\n\tint a=fun(n-1,r-1,dp)%M;\n\tint b=fun(n-1,r,dp)%M;\n\tint ans=a+b;\n\tans%=M;\n\treturn dp[n][r]=ans;\n}\n int nCr(int n, int r){\n vector<vector<int>> dp(n+1,vector<int>(r+1,-1));\n\t return fun(n,r,dp);\n }"
},
{
"code": null,
"e": 2166,
"s": 2164,
"text": "0"
},
{
"code": null,
"e": 2194,
"s": 2166,
"text": "chandankasamsetty4 days ago"
},
{
"code": null,
"e": 2640,
"s": 2194,
"text": "class Solution{\nint p = 1e9+7;\npublic:\n int helper(int n,int r,vector<vector<int>>&dp)\n {\n if(r==0|r==n)\n return 1;\n if(dp[n][r]!=-1)\n return dp[n][r];\n else\n return dp[n][r] = (helper(n-1,r-1,dp)%p+helper(n-1,r,dp)%p)%p;\n }\n int nCr(int n, int r){\n vector<vector<int>>dp(n+1,vector<int>(r+1,-1));\n if(n<r)\n return 0;\n else\n return helper(n,r,dp);\n }\n};"
},
{
"code": null,
"e": 2643,
"s": 2640,
"text": "+1"
},
{
"code": null,
"e": 2660,
"s": 2643,
"text": "sdmrf3 weeks ago"
},
{
"code": null,
"e": 2673,
"s": 2660,
"text": "Python Soln:"
},
{
"code": null,
"e": 2798,
"s": 2673,
"text": "from math import factorial as F\nclass Solution:\n def nCr(self, n, r):\n return (F(n)//(F(r)*F(abs(n-r))))%(10**9+7)"
},
{
"code": null,
"e": 2801,
"s": 2798,
"text": "+1"
},
{
"code": null,
"e": 2834,
"s": 2801,
"text": "mailtoamandeepsingh281 month ago"
},
{
"code": null,
"e": 2843,
"s": 2834,
"text": "C++ code"
},
{
"code": null,
"e": 3233,
"s": 2843,
"text": " int nCr(int n, int r){ if(r>n) return 0; if(r==n) return 1; if((n-r)<r) r=n-r; int mod = 1000000007; vector<int>dp(r+1, 0); dp[0]=1; for(int i=1;i<=n;i++){ for(int j=min(r, i);j>=1;j--){ dp[j] = (dp[j] + dp[j-1])%mod; } } return dp[r]; }"
},
{
"code": null,
"e": 3235,
"s": 3233,
"text": "0"
},
{
"code": null,
"e": 3264,
"s": 3235,
"text": "ankitghanghas10721 month ago"
},
{
"code": null,
"e": 3283,
"s": 3264,
"text": "int inf = 1e9 + 7;"
},
{
"code": null,
"e": 3880,
"s": 3283,
"text": "int nCr(int n, int r){ // code here if(r > n) return 0; if(r == n || r == 0) return 1; if(r == 1) return n; if(r > (n-r)) return nCr(n,n-r); long long dp[n+1][r+1]; for(int j = 1; j<=n; j++) dp[j][1] = j; for(int i = 2; i<=n; i++){ for(int j = 2; j<=r && j<=i; j++){ if(i == j) dp[i][j] = 1; else dp[i][j] = (dp[i-1][j-1] + dp[i-1][j])%inf; } } return dp[n][r]; }"
},
{
"code": null,
"e": 3882,
"s": 3880,
"text": "0"
},
{
"code": null,
"e": 3907,
"s": 3882,
"text": "annanyamathur1 month ago"
},
{
"code": null,
"e": 4186,
"s": 3907,
"text": "int approx=1e9+7; int nCr(int n, int r){ vector<int>memo(r+1,0); memo[0]=1; for(int i=1;i<=n;i++) { for(int j=r;j>0;j--) { memo[j]=(memo[j-1]%approx+memo[j]%approx)%approx; } } return memo[r]; }"
},
{
"code": null,
"e": 4189,
"s": 4186,
"text": "-1"
},
{
"code": null,
"e": 4217,
"s": 4189,
"text": "swapniltayal4222 months ago"
},
{
"code": null,
"e": 4476,
"s": 4217,
"text": "class Solution: def nCr(self, n, r): # code here if r > n: return 0 def fact(n): p = 1 for i in range(1, n+1): p = p * i return p return (fact(n)//(fact(r)*fact(n-r)))%1000000007"
},
{
"code": null,
"e": 4480,
"s": 4478,
"text": "0"
},
{
"code": null,
"e": 4508,
"s": 4480,
"text": "swapniltayal4222 months ago"
},
{
"code": null,
"e": 4871,
"s": 4508,
"text": "class Solution: def nCr(self, n, r): # code here if r > n: return 0 def fact(n): p = 1 for i in range(1, n+1): p = p * i return p a = fact(n) b = fact(r) c = fact(n-r) d = b*c s = (a//d)%1000000007 return s"
},
{
"code": null,
"e": 5017,
"s": 4871,
"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": 5053,
"s": 5017,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5063,
"s": 5053,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5073,
"s": 5063,
"text": "\nContest\n"
},
{
"code": null,
"e": 5136,
"s": 5073,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5284,
"s": 5136,
"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": 5492,
"s": 5284,
"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": 5598,
"s": 5492,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to check if two data frames same or not in R?
|
Two data frames can be same if the column names, row names and all the values in the data frame are exactly same. We might to check this for data frames that we expect to be same, for example, if we have two data sets each one of have same number of rows, same number of columns, same data type for each of the columns, and the data view shows that values are same then it is worth checking whether the complete data sets are same or not. To do this checking in R, we can use identical function.
Live Demo
df1<-data.frame(x1=rnorm(20),x2=letters[1:20])
df1
x1 x2
1 -0.09240552 a
2 -0.86521420 b
3 -0.69926988 c
4 1.24016055 d
5 2.75433272 e
6 0.49542119 f
7 2.10237466 g
8 0.41385580 h
9 0.82198425 i
10 0.41587660 j
11 3.32618703 k
12 -0.56282543 l
13 -0.39042007 m
14 0.78080197 n
15 0.23957177 o
16 -1.92511201 p
17 0.57842631 q
18 -0.82922740 r
19 2.04836392 s
20 0.24616976 t
Live Demo
df2<-data.frame(y1=rnorm(20),y2=letters[1:20])
df2
y1 y2
1 0.02352228 a
2 -0.73437399 b
3 -0.64123651 c
4 0.09660536 d
5 -0.52194846 e
6 0.95606767 f
7 -0.37678881 g
8 0.26724937 h
9 -1.13132950 i
10 0.31408454 j
11 0.64873521 k
12 0.33610366 l
13 -1.82775097 m
14 -0.18508915 n
15 0.59403868 o
16 0.21510182 p
17 0.81497239 q
18 0.71799874 r
19 0.22732659 s
20 0.46474950 t
identical(df1,df2)
[1] FALSE
Live Demo
df1<-data.frame(x1=rnorm(20),x2=letters[1:20])
df1
x1 x2
1 0.34718972 a
2 -0.26756669 b
3 0.52007492 c
4 0.06377162 d
5 -0.11679032 e
6 -0.23173790 f
7 -0.53550405 g
8 1.07821494 h
9 -0.02160426 i
10 -0.12502472 j
11 0.27371128 k
12 -0.28931486 l
13 -0.36478099 m
14 0.79732361 n
15 1.24983019 o
16 1.15472390 p
17 0.30553105 q
18 -0.20471787 r
19 -2.28367371 s
20 1.30177853 t
df2<-data.frame(x1=rnorm(20),x2=letters[1:20])
identical(df1,df2)
[1] FALSE
df3<-data.frame(x1=LETTERS[1:20],x2=1:20)
df3
x1 x2
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
6 F 6
7 G 7
8 H 8
9 I 9
10 J 10
11 K 11
12 L 12
13 M 13
14 N 14
15 O 15
16 P 16
17 Q 17
18 R 18
19 S 19
20 T 20
df4<-data.frame(y1=LETTERS[1:20],y2=1:20)
identical(df3,df4)
[1] FALSE
df5<-data.frame(x1=LETTERS[1:20],x2=1:20)
identical(df3,df5)
[1] TRUE
|
[
{
"code": null,
"e": 1558,
"s": 1062,
"text": "Two data frames can be same if the column names, row names and all the values in the data frame are exactly same. We might to check this for data frames that we expect to be same, for example, if we have two data sets each one of have same number of rows, same number of columns, same data type for each of the columns, and the data view shows that values are same then it is worth checking whether the complete data sets are same or not. To do this checking in R, we can use identical function."
},
{
"code": null,
"e": 1569,
"s": 1558,
"text": " Live Demo"
},
{
"code": null,
"e": 1620,
"s": 1569,
"text": "df1<-data.frame(x1=rnorm(20),x2=letters[1:20])\ndf1"
},
{
"code": null,
"e": 1949,
"s": 1620,
"text": " x1 x2\n1 -0.09240552 a\n2 -0.86521420 b\n3 -0.69926988 c\n4 1.24016055 d\n5 2.75433272 e\n6 0.49542119 f\n7 2.10237466 g\n8 0.41385580 h\n9 0.82198425 i\n10 0.41587660 j\n11 3.32618703 k\n12 -0.56282543 l\n13 -0.39042007 m\n14 0.78080197 n\n15 0.23957177 o\n16 -1.92511201 p\n17 0.57842631 q\n18 -0.82922740 r\n19 2.04836392 s\n20 0.24616976 t"
},
{
"code": null,
"e": 1960,
"s": 1949,
"text": " Live Demo"
},
{
"code": null,
"e": 2011,
"s": 1960,
"text": "df2<-data.frame(y1=rnorm(20),y2=letters[1:20])\ndf2"
},
{
"code": null,
"e": 2370,
"s": 2011,
"text": " y1 y2\n1 0.02352228 a\n2 -0.73437399 b\n3 -0.64123651 c\n4 0.09660536 d\n5 -0.52194846 e\n6 0.95606767 f\n7 -0.37678881 g\n8 0.26724937 h\n9 -1.13132950 i\n10 0.31408454 j\n11 0.64873521 k\n12 0.33610366 l\n13 -1.82775097 m\n14 -0.18508915 n\n15 0.59403868 o\n16 0.21510182 p\n17 0.81497239 q\n18 0.71799874 r\n19 0.22732659 s\n20 0.46474950 t\nidentical(df1,df2)\n[1] FALSE"
},
{
"code": null,
"e": 2381,
"s": 2370,
"text": " Live Demo"
},
{
"code": null,
"e": 2432,
"s": 2381,
"text": "df1<-data.frame(x1=rnorm(20),x2=letters[1:20])\ndf1"
},
{
"code": null,
"e": 3176,
"s": 2432,
"text": " x1 x2\n1 0.34718972 a\n2 -0.26756669 b\n3 0.52007492 c\n4 0.06377162 d\n5 -0.11679032 e\n6 -0.23173790 f\n7 -0.53550405 g\n8 1.07821494 h\n9 -0.02160426 i\n10 -0.12502472 j\n11 0.27371128 k\n12 -0.28931486 l\n13 -0.36478099 m\n14 0.79732361 n\n15 1.24983019 o\n16 1.15472390 p\n17 0.30553105 q\n18 -0.20471787 r\n19 -2.28367371 s\n20 1.30177853 t\ndf2<-data.frame(x1=rnorm(20),x2=letters[1:20])\nidentical(df1,df2)\n[1] FALSE\ndf3<-data.frame(x1=LETTERS[1:20],x2=1:20)\ndf3\nx1 x2\n1 A 1\n2 B 2\n3 C 3\n4 D 4\n5 E 5\n6 F 6\n7 G 7\n8 H 8\n9 I 9\n10 J 10\n11 K 11\n12 L 12\n13 M 13\n14 N 14\n15 O 15\n16 P 16\n17 Q 17\n18 R 18\n19 S 19\n20 T 20\ndf4<-data.frame(y1=LETTERS[1:20],y2=1:20)\nidentical(df3,df4)\n[1] FALSE\ndf5<-data.frame(x1=LETTERS[1:20],x2=1:20)\nidentical(df3,df5)\n[1] TRUE"
}
] |
String getBytes(String charsetName)
|
This method encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
Here is the syntax of this method −
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
Here is the detail of parameters −
charsetName − the name of a supported charset.
charsetName − the name of a supported charset.
This method returns the resultant byte array.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to Tutorialspoint.com");
try {
String Str2 = new String(Str1.getBytes( "UTF-8" ));
System.out.println("Returned Value " + Str2 );
Str2 = new String (Str1.getBytes( "ISO-8859-1" ));
System.out.println("Returned Value " + Str2 );
} catch ( UnsupportedEncodingException e) {
System.out.println("Unsupported character set");
}
}
}
This will produce the following result −
Returned Value Welcome to Tutorialspoint.com
Returned Value Welcome to Tutorialspoint.com
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2501,
"s": 2377,
"text": "This method encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array."
},
{
"code": null,
"e": 2537,
"s": 2501,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2617,
"s": 2537,
"text": "public byte[] getBytes(String charsetName) throws UnsupportedEncodingException\n"
},
{
"code": null,
"e": 2652,
"s": 2617,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2699,
"s": 2652,
"text": "charsetName − the name of a supported charset."
},
{
"code": null,
"e": 2746,
"s": 2699,
"text": "charsetName − the name of a supported charset."
},
{
"code": null,
"e": 2792,
"s": 2746,
"text": "This method returns the resultant byte array."
},
{
"code": null,
"e": 3308,
"s": 2792,
"text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str1 = new String(\"Welcome to Tutorialspoint.com\");\n try {\n String Str2 = new String(Str1.getBytes( \"UTF-8\" ));\n System.out.println(\"Returned Value \" + Str2 );\n Str2 = new String (Str1.getBytes( \"ISO-8859-1\" ));\n System.out.println(\"Returned Value \" + Str2 );\n } catch ( UnsupportedEncodingException e) {\n System.out.println(\"Unsupported character set\");\n }\n }\n}"
},
{
"code": null,
"e": 3349,
"s": 3308,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3440,
"s": 3349,
"text": "Returned Value Welcome to Tutorialspoint.com\nReturned Value Welcome to Tutorialspoint.com\n"
},
{
"code": null,
"e": 3473,
"s": 3440,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3489,
"s": 3473,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3522,
"s": 3489,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3538,
"s": 3522,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3573,
"s": 3538,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3587,
"s": 3573,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3621,
"s": 3587,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3635,
"s": 3621,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3672,
"s": 3635,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3687,
"s": 3672,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3720,
"s": 3687,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3739,
"s": 3720,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3746,
"s": 3739,
"text": " Print"
},
{
"code": null,
"e": 3757,
"s": 3746,
"text": " Add Notes"
}
] |
Ruby on Rails - Session and Cookies
|
To save data across multiple requests, you can use either the session or the flash hashes. A flash stores a value (normally text) until the next request, while a session stores data during the complete session.
session[:user] = @user
flash[:message] = "Data was saved successfully"
<%= link_to "login", :action => 'login' unless session[:user] %>
<% if flash[:message] %>
<div><%= h flash[:message] %></div>
<% end %>
It's possible to turn off session management −
session :off # turn session management off
session :off, :only => :action # only for this :action
session :off, :except => :action # except for this action
session :only => :foo, # only for :foo when doing HTTPS
:session_secure => true
session :off, :only=>:foo, # off for foo,if uses as Web Service
:if => Proc.new { |req| req.parameters[:ws] }
Check out link for more detail on Session Management
Following is the syntax for setting cookies −
# Set a simple session cookie
cookies[:user_name] = "david"
# Set a cookie that expires in 1 hour
cookies[:login] = { :value => "XJ12", :expires => Time.now + 3600}
Following is the syntax for reading cookies −
cookies[:user_name] # => "david"
cookies.size # => 2
Following is the syntax for deleting cookies −
cookies.delete :user_name
All the option symbols for setting cookies are −
value − The cookie.s value or list of values (as an array).
value − The cookie.s value or list of values (as an array).
path − The path for which this cookie applies. Defaults to the root of the application.
path − The path for which this cookie applies. Defaults to the root of the application.
domain − The domain for which this cookie applies.
domain − The domain for which this cookie applies.
expires − The time at which this cookie expires, as a +Time+ object.
expires − The time at which this cookie expires, as a +Time+ object.
secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.
secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.
Check out the link on Cookies Management, for more detail.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2314,
"s": 2103,
"text": "To save data across multiple requests, you can use either the session or the flash hashes. A flash stores a value (normally text) until the next request, while a session stores data during the complete session."
},
{
"code": null,
"e": 2522,
"s": 2314,
"text": "session[:user] = @user\nflash[:message] = \"Data was saved successfully\"\n\n<%= link_to \"login\", :action => 'login' unless session[:user] %>\n<% if flash[:message] %>\n<div><%= h flash[:message] %></div>\n<% end %>"
},
{
"code": null,
"e": 2569,
"s": 2522,
"text": "It's possible to turn off session management −"
},
{
"code": null,
"e": 2981,
"s": 2569,
"text": "session :off # turn session management off\nsession :off, :only => :action # only for this :action\nsession :off, :except => :action # except for this action\n\nsession :only => :foo, # only for :foo when doing HTTPS\n :session_secure => true \n\nsession :off, :only=>:foo, # off for foo,if uses as Web Service\n :if => Proc.new { |req| req.parameters[:ws] }"
},
{
"code": null,
"e": 3034,
"s": 2981,
"text": "Check out link for more detail on Session Management"
},
{
"code": null,
"e": 3080,
"s": 3034,
"text": "Following is the syntax for setting cookies −"
},
{
"code": null,
"e": 3247,
"s": 3080,
"text": "# Set a simple session cookie\ncookies[:user_name] = \"david\" \n\n# Set a cookie that expires in 1 hour\ncookies[:login] = { :value => \"XJ12\", :expires => Time.now + 3600}"
},
{
"code": null,
"e": 3293,
"s": 3247,
"text": "Following is the syntax for reading cookies −"
},
{
"code": null,
"e": 3356,
"s": 3293,
"text": "cookies[:user_name] # => \"david\"\ncookies.size # => 2 "
},
{
"code": null,
"e": 3403,
"s": 3356,
"text": "Following is the syntax for deleting cookies −"
},
{
"code": null,
"e": 3430,
"s": 3403,
"text": "cookies.delete :user_name\n"
},
{
"code": null,
"e": 3479,
"s": 3430,
"text": "All the option symbols for setting cookies are −"
},
{
"code": null,
"e": 3539,
"s": 3479,
"text": "value − The cookie.s value or list of values (as an array)."
},
{
"code": null,
"e": 3599,
"s": 3539,
"text": "value − The cookie.s value or list of values (as an array)."
},
{
"code": null,
"e": 3687,
"s": 3599,
"text": "path − The path for which this cookie applies. Defaults to the root of the application."
},
{
"code": null,
"e": 3775,
"s": 3687,
"text": "path − The path for which this cookie applies. Defaults to the root of the application."
},
{
"code": null,
"e": 3826,
"s": 3775,
"text": "domain − The domain for which this cookie applies."
},
{
"code": null,
"e": 3877,
"s": 3826,
"text": "domain − The domain for which this cookie applies."
},
{
"code": null,
"e": 3946,
"s": 3877,
"text": "expires − The time at which this cookie expires, as a +Time+ object."
},
{
"code": null,
"e": 4015,
"s": 3946,
"text": "expires − The time at which this cookie expires, as a +Time+ object."
},
{
"code": null,
"e": 4144,
"s": 4015,
"text": "secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers."
},
{
"code": null,
"e": 4273,
"s": 4144,
"text": "secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers."
},
{
"code": null,
"e": 4332,
"s": 4273,
"text": "Check out the link on Cookies Management, for more detail."
},
{
"code": null,
"e": 4339,
"s": 4332,
"text": " Print"
},
{
"code": null,
"e": 4350,
"s": 4339,
"text": " Add Notes"
}
] |
Writing a custom data augmentation layer in Keras | by Lak Lakshmanan | Towards Data Science
|
Data augmentation can help an image ML model learn to handle variations of the image that are not in the training dataset. For example, it is likely that photographs provided to an ML model (especially if these are photographs by amateur photographers) will vary quite considerably in terms of lighting. We can therefore increase the effective size of the training dataset and make the ML model more resilient if we augment the training dataset by randomly changing the brightness, contrast, saturation, etc. of the training images.
While Keras has several built-in data augmentation layers (like RandomFlip), it doesn’t currently support changing the contrast and brightness. So, let’s implement one.
The class will inherit from a Keras Layer and take two arguments: the range within which to adjust the contrast and the brightness (full code is in GitHub):
class RandomColorDistortion(tf.keras.layers.Layer): def __init__(self, contrast_range=[0.5, 1.5], brightness_delta=[-0.2, 0.2], **kwargs): super(RandomColorDistortion, self).__init__(**kwargs) self.contrast_range = contrast_range self.brightness_delta = brightness_delta
When invoked, this layer will need to behave differently depending on whether it is in training mode or not. If not in training mode, the layer will simply return the original images. If it is in training mode, it will generate two random numbers, one to adjust the contrast within the image and the other to adjust the brightness. The actual adjust is carried out using methods available in the tf.image module:
def call(self, images, training=None): if not training: return images contrast = np.random.uniform( self.contrast_range[0], self.contrast_range[1]) brightness = np.random.uniform( self.brightness_delta[0], self.brightness_delta[1]) images = tf.image.adjust_contrast(images, contrast) images = tf.image.adjust_brightness(images, brightness) images = tf.clip_by_value(images, 0, 1) return images
Note: For efficiency, it is important that the implementation of the layer consist of TensorFlow functions so that they can be implemented efficiently on a GPU.
To test that the layer works, simply create the layer and call it on some images:
layer=RandomColorDistortion()trainds = create_preproc_dataset('gs://practical-ml-vision-book/flowers_tfr/train-*')for (img, label) in trainds.take(3): ... for idx in range(1, 5): aug = layer(img, training=True) ax[rowno, idx].imshow((aug.numpy()));
The result is shown below:
To use the layer, simply insert it into the Keras model layers. The layer will be applied during training and be a no-op during evaluation or prediction:
layers = [ ... tf.keras.layers.experimental.preprocessing.RandomFlip( mode='horizontal', name='random_lr_flip/none' ), RandomColorDistortion(name='random_contrast_brightness/none'), hub.KerasLayer ... ]
The purpose of data augmentation is to improve model accuracy and to reduce overfitting. On that count, this layer works quite well on the flowers dataset.
Compare the training plot without data augmentation:
with the training plot after data augmentation:
We get better accuracy (0.88 instead of 0.85) and the training and validation curves remain totally in-sync indicating that overfitting is under control.
Enjoy!
Try out the notebook. The full code is in GitHub and there are easy links to open the notebook in Colab and in Google Cloud AI Platform Notebooks.This notebook is part of a series of notebooks for a forthcoming O’Reilly book “Practical ML Vision”. Look at the existing notebooks, and watch/star the GitHub repo to keep up with our work.The Keras guide on preprocessing layers is very thorough.
Try out the notebook. The full code is in GitHub and there are easy links to open the notebook in Colab and in Google Cloud AI Platform Notebooks.
This notebook is part of a series of notebooks for a forthcoming O’Reilly book “Practical ML Vision”. Look at the existing notebooks, and watch/star the GitHub repo to keep up with our work.
The Keras guide on preprocessing layers is very thorough.
|
[
{
"code": null,
"e": 705,
"s": 172,
"text": "Data augmentation can help an image ML model learn to handle variations of the image that are not in the training dataset. For example, it is likely that photographs provided to an ML model (especially if these are photographs by amateur photographers) will vary quite considerably in terms of lighting. We can therefore increase the effective size of the training dataset and make the ML model more resilient if we augment the training dataset by randomly changing the brightness, contrast, saturation, etc. of the training images."
},
{
"code": null,
"e": 874,
"s": 705,
"text": "While Keras has several built-in data augmentation layers (like RandomFlip), it doesn’t currently support changing the contrast and brightness. So, let’s implement one."
},
{
"code": null,
"e": 1031,
"s": 874,
"text": "The class will inherit from a Keras Layer and take two arguments: the range within which to adjust the contrast and the brightness (full code is in GitHub):"
},
{
"code": null,
"e": 1343,
"s": 1031,
"text": "class RandomColorDistortion(tf.keras.layers.Layer): def __init__(self, contrast_range=[0.5, 1.5], brightness_delta=[-0.2, 0.2], **kwargs): super(RandomColorDistortion, self).__init__(**kwargs) self.contrast_range = contrast_range self.brightness_delta = brightness_delta"
},
{
"code": null,
"e": 1756,
"s": 1343,
"text": "When invoked, this layer will need to behave differently depending on whether it is in training mode or not. If not in training mode, the layer will simply return the original images. If it is in training mode, it will generate two random numbers, one to adjust the contrast within the image and the other to adjust the brightness. The actual adjust is carried out using methods available in the tf.image module:"
},
{
"code": null,
"e": 2248,
"s": 1756,
"text": "def call(self, images, training=None): if not training: return images contrast = np.random.uniform( self.contrast_range[0], self.contrast_range[1]) brightness = np.random.uniform( self.brightness_delta[0], self.brightness_delta[1]) images = tf.image.adjust_contrast(images, contrast) images = tf.image.adjust_brightness(images, brightness) images = tf.clip_by_value(images, 0, 1) return images"
},
{
"code": null,
"e": 2409,
"s": 2248,
"text": "Note: For efficiency, it is important that the implementation of the layer consist of TensorFlow functions so that they can be implemented efficiently on a GPU."
},
{
"code": null,
"e": 2491,
"s": 2409,
"text": "To test that the layer works, simply create the layer and call it on some images:"
},
{
"code": null,
"e": 2760,
"s": 2491,
"text": "layer=RandomColorDistortion()trainds = create_preproc_dataset('gs://practical-ml-vision-book/flowers_tfr/train-*')for (img, label) in trainds.take(3): ... for idx in range(1, 5): aug = layer(img, training=True) ax[rowno, idx].imshow((aug.numpy()));"
},
{
"code": null,
"e": 2787,
"s": 2760,
"text": "The result is shown below:"
},
{
"code": null,
"e": 2941,
"s": 2787,
"text": "To use the layer, simply insert it into the Keras model layers. The layer will be applied during training and be a no-op during evaluation or prediction:"
},
{
"code": null,
"e": 3190,
"s": 2941,
"text": "layers = [ ... tf.keras.layers.experimental.preprocessing.RandomFlip( mode='horizontal', name='random_lr_flip/none' ), RandomColorDistortion(name='random_contrast_brightness/none'), hub.KerasLayer ... ]"
},
{
"code": null,
"e": 3346,
"s": 3190,
"text": "The purpose of data augmentation is to improve model accuracy and to reduce overfitting. On that count, this layer works quite well on the flowers dataset."
},
{
"code": null,
"e": 3399,
"s": 3346,
"text": "Compare the training plot without data augmentation:"
},
{
"code": null,
"e": 3447,
"s": 3399,
"text": "with the training plot after data augmentation:"
},
{
"code": null,
"e": 3601,
"s": 3447,
"text": "We get better accuracy (0.88 instead of 0.85) and the training and validation curves remain totally in-sync indicating that overfitting is under control."
},
{
"code": null,
"e": 3608,
"s": 3601,
"text": "Enjoy!"
},
{
"code": null,
"e": 4002,
"s": 3608,
"text": "Try out the notebook. The full code is in GitHub and there are easy links to open the notebook in Colab and in Google Cloud AI Platform Notebooks.This notebook is part of a series of notebooks for a forthcoming O’Reilly book “Practical ML Vision”. Look at the existing notebooks, and watch/star the GitHub repo to keep up with our work.The Keras guide on preprocessing layers is very thorough."
},
{
"code": null,
"e": 4149,
"s": 4002,
"text": "Try out the notebook. The full code is in GitHub and there are easy links to open the notebook in Colab and in Google Cloud AI Platform Notebooks."
},
{
"code": null,
"e": 4340,
"s": 4149,
"text": "This notebook is part of a series of notebooks for a forthcoming O’Reilly book “Practical ML Vision”. Look at the existing notebooks, and watch/star the GitHub repo to keep up with our work."
}
] |
Extraction of Tweets using Tweepy - GeeksforGeeks
|
30 May, 2018
Introduction: Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
Steps to obtain keys:– Login to twitter developer section– Go to “Create an App”– Fill the details of the application.– Click on Create your Twitter Application– Details of your new app will be shown along with consumer key and consumer secret.– For access token, click ” Create my access token”. The page will refresh and generate access token.
Tweepy is one of the library that should be installed using pip. Now in order to authorize our app to access Twitter on our behalf, we need to use the OAuth Interface. Tweepy provides the convenient Cursor interface to iterate through different types of objects. Twitter allows a maximum of 3200 tweets for extraction.
These all are the prerequisite that have to be used before getting tweets of a user.
Code(with explanation) :
import tweepy # Fill the X's with the credentials obtained by # following the above mentioned procedure.consumer_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" consumer_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"access_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"access_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" # Function to extract tweetsdef get_tweets(username): # Authorization to consumer key and consumer secret auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # Access to user's access key and access secret auth.set_access_token(access_key, access_secret) # Calling api api = tweepy.API(auth) # 200 tweets to be extracted number_of_tweets=200 tweets = api.user_timeline(screen_name=username) # Empty Array tmp=[] # create array of tweet information: username, # tweet id, date/time, text tweets_for_csv = [tweet.text for tweet in tweets] # CSV file created for j in tweets_for_csv: # Appending tweets to the empty array tmp tmp.append(j) # Printing the tweets print(tmp) # Driver codeif __name__ == '__main__': # Here goes the twitter handle for the user # whose tweets are to be extracted. get_tweets("twitter-handle")
Conclusion :The above script would generate all the tweets of the particular user and would be appended to the empty array tmp. Here Tweepy is introduced as a tool to access Twitter data in a fairly easy way with Python. There are different types of data we can collect, with the obvious focus on the “tweet” object. Once we have collected some data, the possibilities in terms of analytics applications are endless.
One such application of extracting tweets is sentiment or emotion analysis. The emotion of the user can be obtained from the tweets by tokenizing each word and applying machine learning algorithms on that data. Such emotion or sentiment detection is used worldwide and will be broadly used in the future.
This article is contributed by Ayush Govil. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
python-utility
Twitter
GBlog
Python
Web Technologies
Twitter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Supervised and Unsupervised learning
Differences between Procedural and Object Oriented Programming
Introduction to Recurrent Neural Network
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25955,
"s": 25927,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 26369,
"s": 25955,
"text": "Introduction: Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication."
},
{
"code": null,
"e": 26715,
"s": 26369,
"text": "Steps to obtain keys:– Login to twitter developer section– Go to “Create an App”– Fill the details of the application.– Click on Create your Twitter Application– Details of your new app will be shown along with consumer key and consumer secret.– For access token, click ” Create my access token”. The page will refresh and generate access token."
},
{
"code": null,
"e": 27034,
"s": 26715,
"text": "Tweepy is one of the library that should be installed using pip. Now in order to authorize our app to access Twitter on our behalf, we need to use the OAuth Interface. Tweepy provides the convenient Cursor interface to iterate through different types of objects. Twitter allows a maximum of 3200 tweets for extraction."
},
{
"code": null,
"e": 27119,
"s": 27034,
"text": "These all are the prerequisite that have to be used before getting tweets of a user."
},
{
"code": null,
"e": 27144,
"s": 27119,
"text": "Code(with explanation) :"
},
{
"code": "import tweepy # Fill the X's with the credentials obtained by # following the above mentioned procedure.consumer_key = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\" consumer_secret = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"access_key = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"access_secret = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\" # Function to extract tweetsdef get_tweets(username): # Authorization to consumer key and consumer secret auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # Access to user's access key and access secret auth.set_access_token(access_key, access_secret) # Calling api api = tweepy.API(auth) # 200 tweets to be extracted number_of_tweets=200 tweets = api.user_timeline(screen_name=username) # Empty Array tmp=[] # create array of tweet information: username, # tweet id, date/time, text tweets_for_csv = [tweet.text for tweet in tweets] # CSV file created for j in tweets_for_csv: # Appending tweets to the empty array tmp tmp.append(j) # Printing the tweets print(tmp) # Driver codeif __name__ == '__main__': # Here goes the twitter handle for the user # whose tweets are to be extracted. get_tweets(\"twitter-handle\") ",
"e": 28513,
"s": 27144,
"text": null
},
{
"code": null,
"e": 28930,
"s": 28513,
"text": "Conclusion :The above script would generate all the tweets of the particular user and would be appended to the empty array tmp. Here Tweepy is introduced as a tool to access Twitter data in a fairly easy way with Python. There are different types of data we can collect, with the obvious focus on the “tweet” object. Once we have collected some data, the possibilities in terms of analytics applications are endless."
},
{
"code": null,
"e": 29235,
"s": 28930,
"text": "One such application of extracting tweets is sentiment or emotion analysis. The emotion of the user can be obtained from the tweets by tokenizing each word and applying machine learning algorithms on that data. Such emotion or sentiment detection is used worldwide and will be broadly used in the future."
},
{
"code": null,
"e": 29534,
"s": 29235,
"text": "This article is contributed by Ayush Govil. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29659,
"s": 29534,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29674,
"s": 29659,
"text": "python-utility"
},
{
"code": null,
"e": 29682,
"s": 29674,
"text": "Twitter"
},
{
"code": null,
"e": 29688,
"s": 29682,
"text": "GBlog"
},
{
"code": null,
"e": 29695,
"s": 29688,
"text": "Python"
},
{
"code": null,
"e": 29712,
"s": 29695,
"text": "Web Technologies"
},
{
"code": null,
"e": 29720,
"s": 29712,
"text": "Twitter"
},
{
"code": null,
"e": 29818,
"s": 29720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29843,
"s": 29818,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29870,
"s": 29843,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 29907,
"s": 29870,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 29970,
"s": 29907,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 30011,
"s": 29970,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 30039,
"s": 30011,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30089,
"s": 30039,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30111,
"s": 30089,
"text": "Python map() function"
}
] |
C# | Replacing the value at a specific index in a SortedList object - GeeksforGeeks
|
01 Feb, 2019
SortedList.SetByIndex(Int32, Object) Method is used to replace the value at a specific index in a SortedList object.
Syntax:
public virtual void SetByIndex (int index, object value);
Parameters:
index: It is the zero-based index at which to save value.
value: It is the Object to save into the SortedList object. The value can be null.
Exception: This method throws ArgumentOutOfRangeException if the index is outside the range of the valid indexes of the given SortedList Object.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code for replacing the value at a// specific index in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("First", "Ram"); mylist.Add("Second", "Shyam"); mylist.Add("Third", "Mohit"); mylist.Add("Fourth", "Rohit"); mylist.Add("Fifth", "Manish"); // Before replacing the keys // and values of SortedList are Console.WriteLine("----- Before Replacing -----"); Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.WriteLine(); // After replacing the keys // and values of SortedList are Console.WriteLine("----- After Replacing -----"); // Replaces the values at // index 1 and index 3. mylist.SetByIndex(1, "Priyanka"); mylist.SetByIndex(3, "Ritu"); Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } }}
Output:
----- Before Replacing -----
Index Keys Values
[0] Fifth Manish
[1] First Ram
[2] Fourth Rohit
[3] Second Shyam
[4] Third Mohit
----- After Replacing -----
Index Keys Values
[0] Fifth Manish
[1] First Priyanka
[2] Fourth Rohit
[3] Second Ritu
[4] Third Mohit
Example 2: Demonstrating the case where ArgumentOutOfRangeException can occur
// C# code giving ArgumentOutOfRangeException // specific index in a SortedList object// but giving ArgumentOutOfRangeException using System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("h", "Hello"); mylist.Add("g", "Geeks!"); mylist.Add("w", "Welcome"); mylist.Add("t", "to"); mylist.Add("n", "Noida"); // Before replacing the keys // and values of SortedList are Console.WriteLine("----- Before Replacing -----"); Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.WriteLine(); // After replacing the keys // and values of SortedList are Console.WriteLine("----- After Replacing -----"); // Replaces the values at // index 6 which is outside // the range of valid indexes // here it will give an // ArgumentOutOfRangeException mylist.SetByIndex(6, null); Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } }}
Runtime Error:
Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
Note:
The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. So, the index of a specific key/value pair may change after adding and removing the elements from the SortedList object.
This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.setbyindex?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-SortedList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 25664,
"s": 25547,
"text": "SortedList.SetByIndex(Int32, Object) Method is used to replace the value at a specific index in a SortedList object."
},
{
"code": null,
"e": 25672,
"s": 25664,
"text": "Syntax:"
},
{
"code": null,
"e": 25730,
"s": 25672,
"text": "public virtual void SetByIndex (int index, object value);"
},
{
"code": null,
"e": 25742,
"s": 25730,
"text": "Parameters:"
},
{
"code": null,
"e": 25800,
"s": 25742,
"text": "index: It is the zero-based index at which to save value."
},
{
"code": null,
"e": 25883,
"s": 25800,
"text": "value: It is the Object to save into the SortedList object. The value can be null."
},
{
"code": null,
"e": 26028,
"s": 25883,
"text": "Exception: This method throws ArgumentOutOfRangeException if the index is outside the range of the valid indexes of the given SortedList Object."
},
{
"code": null,
"e": 26089,
"s": 26028,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 26100,
"s": 26089,
"text": "Example 1:"
},
{
"code": "// C# code for replacing the value at a// specific index in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"First\", \"Ram\"); mylist.Add(\"Second\", \"Shyam\"); mylist.Add(\"Third\", \"Mohit\"); mylist.Add(\"Fourth\", \"Rohit\"); mylist.Add(\"Fifth\", \"Manish\"); // Before replacing the keys // and values of SortedList are Console.WriteLine(\"----- Before Replacing -----\"); Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.WriteLine(); // After replacing the keys // and values of SortedList are Console.WriteLine(\"----- After Replacing -----\"); // Replaces the values at // index 1 and index 3. mylist.SetByIndex(1, \"Priyanka\"); mylist.SetByIndex(3, \"Ritu\"); Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } }}",
"e": 27551,
"s": 26100,
"text": null
},
{
"code": null,
"e": 27559,
"s": 27551,
"text": "Output:"
},
{
"code": null,
"e": 27994,
"s": 27559,
"text": "----- Before Replacing -----\nIndex Keys Values\n[0] Fifth Manish\n[1] First Ram\n[2] Fourth Rohit\n[3] Second Shyam\n[4] Third Mohit\n\n----- After Replacing -----\nIndex Keys Values\n[0] Fifth Manish\n[1] First Priyanka\n[2] Fourth Rohit\n[3] Second Ritu\n[4] Third Mohit\n"
},
{
"code": null,
"e": 28072,
"s": 27994,
"text": "Example 2: Demonstrating the case where ArgumentOutOfRangeException can occur"
},
{
"code": "// C# code giving ArgumentOutOfRangeException // specific index in a SortedList object// but giving ArgumentOutOfRangeException using System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"h\", \"Hello\"); mylist.Add(\"g\", \"Geeks!\"); mylist.Add(\"w\", \"Welcome\"); mylist.Add(\"t\", \"to\"); mylist.Add(\"n\", \"Noida\"); // Before replacing the keys // and values of SortedList are Console.WriteLine(\"----- Before Replacing -----\"); Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.WriteLine(); // After replacing the keys // and values of SortedList are Console.WriteLine(\"----- After Replacing -----\"); // Replaces the values at // index 6 which is outside // the range of valid indexes // here it will give an // ArgumentOutOfRangeException mylist.SetByIndex(6, null); Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } }}",
"e": 29618,
"s": 28072,
"text": null
},
{
"code": null,
"e": 29633,
"s": 29618,
"text": "Runtime Error:"
},
{
"code": null,
"e": 29797,
"s": 29633,
"text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
},
{
"code": null,
"e": 29803,
"s": 29797,
"text": "Note:"
},
{
"code": null,
"e": 30163,
"s": 29803,
"text": "The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. So, the index of a specific key/value pair may change after adding and removing the elements from the SortedList object."
},
{
"code": null,
"e": 30197,
"s": 30163,
"text": "This method is an O(1) operation."
},
{
"code": null,
"e": 30208,
"s": 30197,
"text": "Reference:"
},
{
"code": null,
"e": 30317,
"s": 30208,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.setbyindex?view=netframework-4.7.2"
},
{
"code": null,
"e": 30346,
"s": 30317,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 30376,
"s": 30346,
"text": "CSharp-Collections-SortedList"
},
{
"code": null,
"e": 30390,
"s": 30376,
"text": "CSharp-method"
},
{
"code": null,
"e": 30393,
"s": 30390,
"text": "C#"
},
{
"code": null,
"e": 30491,
"s": 30393,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30514,
"s": 30491,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30542,
"s": 30514,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 30559,
"s": 30542,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 30581,
"s": 30559,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 30610,
"s": 30581,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 30650,
"s": 30610,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 30673,
"s": 30650,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 30713,
"s": 30673,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 30756,
"s": 30713,
"text": "C# | How to insert an element in an Array?"
}
] |
How to add Matplotlib graph in Kivy ? - GeeksforGeeks
|
05 Apr, 2021
In this article, we will discuss how to add matplotlib graph in the kivy app.
Import matplotlib pyplot
Import numpy
Import FigureCanvas KivyAgg
Import kivy app
Import kivy builder
Create App class
Return builder string
Run an instance of the class
Below is the Implementation.
Python3
# importing pyplot for graph plotting
from matplotlib import pyplot as plt
# importing numpy
import numpy as np
from kivy.garden.matplotlib import FigureCanvasKivyAgg
# importing kivyapp
from kivy.app import App
# importing kivy builder
from kivy.lang import Builder
# this is the main class which will
# render the whole application
class uiApp(App):
def build(self):
self.str = Builder.load_string("""
BoxLayout:
layout:layout
BoxLayout:
id:layout
""")
signal = [7, 89.6, 45.-56.34]
signal = np.array(signal)
# this will plot the signal on graph
plt.plot(signal)
# setting x label
plt.xlabel('Time(s)')
# setting y label
plt.ylabel('signal (norm)')
plt.grid(True, color='lightgray')
# adding plot to kivy boxlayout
self.str.layout.add_widget(FigureCanvasKivyAgg(plt.gcf()))
return self.str
# running the application
uiApp().run()
Output:
Note: When you run the below code this may throw the error given below
What you have to do is open the file given in the white box by clicking on file while holding ctrl key and comment line underlined by green color in that file and hit save now you will be able to run it!!
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25635,
"s": 25604,
"text": " \n05 Apr, 2021\n"
},
{
"code": null,
"e": 25713,
"s": 25635,
"text": "In this article, we will discuss how to add matplotlib graph in the kivy app."
},
{
"code": null,
"e": 25738,
"s": 25713,
"text": "Import matplotlib pyplot"
},
{
"code": null,
"e": 25751,
"s": 25738,
"text": "Import numpy"
},
{
"code": null,
"e": 25779,
"s": 25751,
"text": "Import FigureCanvas KivyAgg"
},
{
"code": null,
"e": 25795,
"s": 25779,
"text": "Import kivy app"
},
{
"code": null,
"e": 25815,
"s": 25795,
"text": "Import kivy builder"
},
{
"code": null,
"e": 25832,
"s": 25815,
"text": "Create App class"
},
{
"code": null,
"e": 25854,
"s": 25832,
"text": "Return builder string"
},
{
"code": null,
"e": 25883,
"s": 25854,
"text": "Run an instance of the class"
},
{
"code": null,
"e": 25912,
"s": 25883,
"text": "Below is the Implementation."
},
{
"code": null,
"e": 25920,
"s": 25912,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# importing pyplot for graph plotting \nfrom matplotlib import pyplot as plt \n \n# importing numpy \nimport numpy as np \nfrom kivy.garden.matplotlib import FigureCanvasKivyAgg \n \n# importing kivyapp \nfrom kivy.app import App \n \n# importing kivy builder \nfrom kivy.lang import Builder \n \n \n# this is the main class which will \n# render the whole application \nclass uiApp(App): \n \n def build(self): \n self.str = Builder.load_string(\"\"\" \n \nBoxLayout: \n layout:layout \n \n BoxLayout: \n \n id:layout \n \n \"\"\") \n \n signal = [7, 89.6, 45.-56.34] \n \n signal = np.array(signal) \n \n # this will plot the signal on graph \n plt.plot(signal) \n \n # setting x label \n plt.xlabel('Time(s)') \n \n # setting y label \n plt.ylabel('signal (norm)') \n plt.grid(True, color='lightgray') \n \n # adding plot to kivy boxlayout \n self.str.layout.add_widget(FigureCanvasKivyAgg(plt.gcf())) \n return self.str\n \n \n# running the application \nuiApp().run() \n\n\n\n\n\n",
"e": 27063,
"s": 25930,
"text": null
},
{
"code": null,
"e": 27071,
"s": 27063,
"text": "Output:"
},
{
"code": null,
"e": 27142,
"s": 27071,
"text": "Note: When you run the below code this may throw the error given below"
},
{
"code": null,
"e": 27347,
"s": 27142,
"text": "What you have to do is open the file given in the white box by clicking on file while holding ctrl key and comment line underlined by green color in that file and hit save now you will be able to run it!!"
},
{
"code": null,
"e": 27361,
"s": 27347,
"text": "\nPython-kivy\n"
},
{
"code": null,
"e": 27370,
"s": 27361,
"text": "\nPython\n"
},
{
"code": null,
"e": 27575,
"s": 27370,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 27607,
"s": 27575,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27649,
"s": 27607,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27691,
"s": 27649,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27718,
"s": 27691,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27774,
"s": 27718,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27796,
"s": 27774,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27835,
"s": 27796,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27866,
"s": 27835,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27895,
"s": 27866,
"text": "Create a directory in Python"
}
] |
GATE CS 2021 | Set 1 - GeeksforGeeks
|
17 Sep, 2021
(i) Everybody in the class is prepared for the exam.
(ii) Babu invited Danish to his home because he enjoys playing chess.
Pillar in Y-axis is longer than pillar in X-axis
Pillar in Y is horizontal and pillar in Y is vertical
Profit% = ((Selling price – Cost)/Cost)×100
Statement 1: All bacteria are microorganisms.
Statement 2: All pathogens are microorganisms.
Conclusion I: Some pathogens are bacteria.
Conclusion II: All pathogens are not bacteria.
Case-1 is counter example of Conclusion II, because of all pathogens are bacteria in this diagram.
Conclusion I would be true in this case, because all so also some.
(So, Conclusion I is true and II is false.).
Case-2 is counter example of Conclusion I, because no pathogens are bacteria.
Conclusion II would be true in this case, because all so also some.
(So, Conclusion II is false and II is true.).
Case-3: Conclusion I is true, and Conclusion II is false as some pathogens are *already* bacteria.
Case-4: Conclusion I is true, and Conclusion II is false as some pathogens are *already* bacteria.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Find size of largest subset with bitwise AND greater than their bitwise XOR
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 28908,
"s": 28855,
"text": "(i) Everybody in the class is prepared for the exam."
},
{
"code": null,
"e": 28978,
"s": 28908,
"text": "(ii) Babu invited Danish to his home because he enjoys playing chess."
},
{
"code": null,
"e": 29027,
"s": 28978,
"text": "Pillar in Y-axis is longer than pillar in X-axis"
},
{
"code": null,
"e": 29081,
"s": 29027,
"text": "Pillar in Y is horizontal and pillar in Y is vertical"
},
{
"code": null,
"e": 29126,
"s": 29081,
"text": "Profit% = ((Selling price – Cost)/Cost)×100 "
},
{
"code": null,
"e": 29172,
"s": 29126,
"text": "Statement 1: All bacteria are microorganisms."
},
{
"code": null,
"e": 29219,
"s": 29172,
"text": "Statement 2: All pathogens are microorganisms."
},
{
"code": null,
"e": 29262,
"s": 29219,
"text": "Conclusion I: Some pathogens are bacteria."
},
{
"code": null,
"e": 29309,
"s": 29262,
"text": "Conclusion II: All pathogens are not bacteria."
},
{
"code": null,
"e": 29520,
"s": 29309,
"text": "Case-1 is counter example of Conclusion II, because of all pathogens are bacteria in this diagram.\nConclusion I would be true in this case, because all so also some.\n(So, Conclusion I is true and II is false.)."
},
{
"code": null,
"e": 29712,
"s": 29520,
"text": "Case-2 is counter example of Conclusion I, because no pathogens are bacteria.\nConclusion II would be true in this case, because all so also some.\n(So, Conclusion II is false and II is true.)."
},
{
"code": null,
"e": 29811,
"s": 29712,
"text": "Case-3: Conclusion I is true, and Conclusion II is false as some pathogens are *already* bacteria."
},
{
"code": null,
"e": 29910,
"s": 29811,
"text": "Case-4: Conclusion I is true, and Conclusion II is false as some pathogens are *already* bacteria."
},
{
"code": null,
"e": 30008,
"s": 29910,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30061,
"s": 30008,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30137,
"s": 30061,
"text": "Find size of largest subset with bitwise AND greater than their bitwise XOR"
},
{
"code": null,
"e": 30199,
"s": 30137,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 30240,
"s": 30199,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30275,
"s": 30240,
"text": "Insert Image in a Jupyter Notebook"
},
{
"code": null,
"e": 30318,
"s": 30275,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 30354,
"s": 30318,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 30392,
"s": 30354,
"text": "How to Compare Two Columns in Pandas?"
},
{
"code": null,
"e": 30430,
"s": 30392,
"text": "Python Data Structures and Algorithms"
}
] |
Repunit numbers - GeeksforGeeks
|
16 Jul, 2021
A number is a Repunit in base B if it can be represented as a string of three or more 1’s in a base >= 2.
Given an integer N, the task is to check if N is a Repunit number in base B.Examples:
Input: N = 31, B = 5 Output: Yes 31 can be written as 111 base in 5Input: N = 5, B = 2 Output: No 5 is 101 in base 2
Approach: We will count the number of one’s in the base B of a given number N and also count the number of digits in the base B of a given number N. If they are same, print “YES” else print “NO”.For Example:
N = 31, B = 5 31 can be written as 111 base in 5, So number of one’s in base B of a given number N = 3 and number of digits in the base B of a given number N = 3 Since both are equal hence 31 is a Repunit number in base 5.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check// if a number is Repunit Number #include <iostream>#include <math.h>using namespace std; // Function to check if a number// contains all the digits 0, 1, .., (b-1)// an equal number of timesbool isRepunitNum(int n, int b){ // to store number of digits of n // in base B int length = 0; // to count frequency of digit 1 int countOne = 0; while (n != 0) { int r = n % b; length++; if (r == 1) countOne++; n = n / b; } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length;} // Driver Codeint main(){ // taking inputs int n = 31; int base = 2; // function to check if (isRepunitNum(n, base)) cout << "Yes"; else cout << "NO"; return 0;}
// Java implementation to check// if a number is Repunit Numberclass GFG{ // Function to check if a number// contains all the digits 0, 1, .., (b-1)// an equal number of timesstatic boolean isRepunitNum(int n, int b){ // to store number of digits of n // in base B int length = 0; // to count frequency of digit 1 int countOne = 0; while (n != 0) { int r = n % b; length++; if (r == 1) countOne++; n = n / b; } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length;} // Driver Codepublic static void main(String[] args){ // taking inputs int n = 31; int base = 2; // function to check if (isRepunitNum(n, base)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by rock_cool
# Python3 implementation to check# if a number is Repunit Number # Function to check if a number# contains all the digits 0, 1, .., (b-1)# an equal number of timesdef isRepunitNum(n, b): # to store number of digits of n # in base B length = 0; # to count frequency of digit 1 countOne = 0; while (n != 0): r = n % b; length += 1; if (r == 1): countOne += 1; n = n // b; # condition to check three or more 1's # and number of ones is equal to number # of digits of n in base B return countOne >= 3 and countOne == length; # Driver Codeif __name__ == '__main__': # taking inputs n = 31; base = 2; # function to check if (isRepunitNum(n, base)): print("Yes"); else: print("No"); # This code is contributed by 29AjayKumar
// C# implementation to check// if a number is Repunit Numberusing System;class GFG{ // Function to check if a number// contains all the digits 0, 1, .., (b-1)// an equal number of timesstatic bool isRepunitNum(int n, int b){ // to store number of digits of n // in base B int length = 0; // to count frequency of digit 1 int countOne = 0; while (n != 0) { int r = n % b; length++; if (r == 1) countOne++; n = n / b; } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length;} // Driver Codepublic static void Main(){ // taking inputs int n = 31; int base1 = 2; // function to check if (isRepunitNum(n, base1)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Code_Mech
<script> // Javascript implementation to check// if a number is Repunit Number // Function to check if a number // contains all the digits 0, 1, .., (b-1) // an equal number of times function isRepunitNum( n ,b) { // to store number of digits of n // in base B let length = 0; // to count frequency of digit 1 let countOne = 0; while (n != 0) { let r = n % b; length++; if (r == 1) countOne++; n = parseInt(n / b); } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length; } // Driver Code // taking inputs let n = 31; let base = 2; // function to check if (isRepunitNum(n, base)) document.write("Yes"); else document.write("No"); // This code contributed by gauravrajput1 </script>
Yes
Time Complexity: O(logbn)
Auxiliary Space: O(1)
Reference: http://www.numbersaplenty.com/set/repunit/
rock_cool
Code_Mech
29AjayKumar
GauravRajput1
souravmahato348
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
|
[
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 26044,
"s": 25937,
"text": "A number is a Repunit in base B if it can be represented as a string of three or more 1’s in a base >= 2. "
},
{
"code": null,
"e": 26132,
"s": 26044,
"text": "Given an integer N, the task is to check if N is a Repunit number in base B.Examples: "
},
{
"code": null,
"e": 26251,
"s": 26132,
"text": "Input: N = 31, B = 5 Output: Yes 31 can be written as 111 base in 5Input: N = 5, B = 2 Output: No 5 is 101 in base 2 "
},
{
"code": null,
"e": 26463,
"s": 26253,
"text": "Approach: We will count the number of one’s in the base B of a given number N and also count the number of digits in the base B of a given number N. If they are same, print “YES” else print “NO”.For Example: "
},
{
"code": null,
"e": 26688,
"s": 26463,
"text": "N = 31, B = 5 31 can be written as 111 base in 5, So number of one’s in base B of a given number N = 3 and number of digits in the base B of a given number N = 3 Since both are equal hence 31 is a Repunit number in base 5. "
},
{
"code": null,
"e": 26741,
"s": 26688,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26745,
"s": 26741,
"text": "C++"
},
{
"code": null,
"e": 26750,
"s": 26745,
"text": "Java"
},
{
"code": null,
"e": 26758,
"s": 26750,
"text": "Python3"
},
{
"code": null,
"e": 26761,
"s": 26758,
"text": "C#"
},
{
"code": null,
"e": 26772,
"s": 26761,
"text": "Javascript"
},
{
"code": "// C++ implementation to check// if a number is Repunit Number #include <iostream>#include <math.h>using namespace std; // Function to check if a number// contains all the digits 0, 1, .., (b-1)// an equal number of timesbool isRepunitNum(int n, int b){ // to store number of digits of n // in base B int length = 0; // to count frequency of digit 1 int countOne = 0; while (n != 0) { int r = n % b; length++; if (r == 1) countOne++; n = n / b; } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length;} // Driver Codeint main(){ // taking inputs int n = 31; int base = 2; // function to check if (isRepunitNum(n, base)) cout << \"Yes\"; else cout << \"NO\"; return 0;}",
"e": 27645,
"s": 26772,
"text": null
},
{
"code": "// Java implementation to check// if a number is Repunit Numberclass GFG{ // Function to check if a number// contains all the digits 0, 1, .., (b-1)// an equal number of timesstatic boolean isRepunitNum(int n, int b){ // to store number of digits of n // in base B int length = 0; // to count frequency of digit 1 int countOne = 0; while (n != 0) { int r = n % b; length++; if (r == 1) countOne++; n = n / b; } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length;} // Driver Codepublic static void main(String[] args){ // taking inputs int n = 31; int base = 2; // function to check if (isRepunitNum(n, base)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by rock_cool",
"e": 28576,
"s": 27645,
"text": null
},
{
"code": "# Python3 implementation to check# if a number is Repunit Number # Function to check if a number# contains all the digits 0, 1, .., (b-1)# an equal number of timesdef isRepunitNum(n, b): # to store number of digits of n # in base B length = 0; # to count frequency of digit 1 countOne = 0; while (n != 0): r = n % b; length += 1; if (r == 1): countOne += 1; n = n // b; # condition to check three or more 1's # and number of ones is equal to number # of digits of n in base B return countOne >= 3 and countOne == length; # Driver Codeif __name__ == '__main__': # taking inputs n = 31; base = 2; # function to check if (isRepunitNum(n, base)): print(\"Yes\"); else: print(\"No\"); # This code is contributed by 29AjayKumar",
"e": 29404,
"s": 28576,
"text": null
},
{
"code": "// C# implementation to check// if a number is Repunit Numberusing System;class GFG{ // Function to check if a number// contains all the digits 0, 1, .., (b-1)// an equal number of timesstatic bool isRepunitNum(int n, int b){ // to store number of digits of n // in base B int length = 0; // to count frequency of digit 1 int countOne = 0; while (n != 0) { int r = n % b; length++; if (r == 1) countOne++; n = n / b; } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length;} // Driver Codepublic static void Main(){ // taking inputs int n = 31; int base1 = 2; // function to check if (isRepunitNum(n, base1)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Code_Mech",
"e": 30326,
"s": 29404,
"text": null
},
{
"code": "<script> // Javascript implementation to check// if a number is Repunit Number // Function to check if a number // contains all the digits 0, 1, .., (b-1) // an equal number of times function isRepunitNum( n ,b) { // to store number of digits of n // in base B let length = 0; // to count frequency of digit 1 let countOne = 0; while (n != 0) { let r = n % b; length++; if (r == 1) countOne++; n = parseInt(n / b); } // condition to check three or more 1's // and number of ones is equal to number // of digits of n in base B return countOne >= 3 && countOne == length; } // Driver Code // taking inputs let n = 31; let base = 2; // function to check if (isRepunitNum(n, base)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by gauravrajput1 </script>",
"e": 31348,
"s": 30326,
"text": null
},
{
"code": null,
"e": 31352,
"s": 31348,
"text": "Yes"
},
{
"code": null,
"e": 31380,
"s": 31354,
"text": "Time Complexity: O(logbn)"
},
{
"code": null,
"e": 31402,
"s": 31380,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31457,
"s": 31402,
"text": "Reference: http://www.numbersaplenty.com/set/repunit/ "
},
{
"code": null,
"e": 31467,
"s": 31457,
"text": "rock_cool"
},
{
"code": null,
"e": 31477,
"s": 31467,
"text": "Code_Mech"
},
{
"code": null,
"e": 31489,
"s": 31477,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31503,
"s": 31489,
"text": "GauravRajput1"
},
{
"code": null,
"e": 31519,
"s": 31503,
"text": "souravmahato348"
},
{
"code": null,
"e": 31526,
"s": 31519,
"text": "series"
},
{
"code": null,
"e": 31539,
"s": 31526,
"text": "Mathematical"
},
{
"code": null,
"e": 31552,
"s": 31539,
"text": "Mathematical"
},
{
"code": null,
"e": 31559,
"s": 31552,
"text": "series"
},
{
"code": null,
"e": 31657,
"s": 31559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31701,
"s": 31657,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 31743,
"s": 31701,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 31774,
"s": 31743,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 31845,
"s": 31774,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 31870,
"s": 31845,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 31902,
"s": 31870,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 31935,
"s": 31902,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 31970,
"s": 31935,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 32016,
"s": 31970,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
Greatest Integer Function - GeeksforGeeks
|
19 May, 2021
The greatest Integer Function [X] indicates an integral part of the real number which is the nearest and smaller integer to . It is also known as the floor of X.[x]=the largest integer that is less than or equal to x.In general: If, <= < . Then, This means if X lies in [n, n+1), then the Greatest Integer Function of X will be n.
In the above figure, we are taking the floor of the values each time. When the intervals are in the form of [n, n+1), the value of the greatest integer function is n, where n is an integer.
0<=x<1 will always lie in the interval [0, 0.9), so here the Greatest Integer Function of X will be 0.1<=x<2 will always lie in the interval [1, 1.9), so here the Greatest Integer Function of X will be 1.2<=x<3 will always lie in the interval [2, 2.9), so here the Greatest Integer Function of X will be 2.
0<=x<1 will always lie in the interval [0, 0.9), so here the Greatest Integer Function of X will be 0.
1<=x<2 will always lie in the interval [1, 1.9), so here the Greatest Integer Function of X will be 1.
2<=x<3 will always lie in the interval [2, 2.9), so here the Greatest Integer Function of X will be 2.
Examples:
Input: X = 2.3
Output: [2.3] = 2
Input: X = -8.0725
Output: [-8.0725] = -9
Input: X = 2
Output: [2] = 2
Number Line RepresentationIf we examine a number line with the integers and plot 2.7 on it, we see:
The largest integer that is less than 2.7 is 2. So [2.7] = 2. If we examine a number line with the integers and plot -1.3 on it, we see:
Since the largest integer that is less than -1.3 is -2, so [-1.3] = 2.Here, f(x)=[X] could be expressed graphically as:
Note: In the above graph, the left endpoint at every step is blocked(dark dot) to show that the point is a member of the graph, and the other right endpoint (open circle) indicates the points that are not part of the graph.
Properties of Greatest Integer Function:
[X]=X holds if X is an integer.
[X+I]=[X]+I, if I is an integer, then we can I separately in the Greatest Integer Function.
[X+Y]>=[X]+[Y], means the greatest integer of the sum of X and Y is the equal sum of the GIF of X and the GIF of Y.
If [f(X)]>=I, then f(X) >= I.
If [f(X)]<=I, then f(X) < I+1.
[-X]= -[X], If XInteger.
[-X]=-[X]-1, If X is not an Integer.
It is also known as the stepwise function or floor of X.The below program shows the implementation of the Greatest Integer Function using floor():
C++
Java
Python3
C#
PHP
Javascript
// CPP program to illustrate// greatest integer Function#include <bits/stdc++.h>using namespace std; // Function to calculate the// GIF value of a numberint GIF(float n){ // GIF is the floor of a number return floor(n);} // Driver codeint main(){ int n = 2.3; cout << GIF(n); return 0;}
// Java program to illustrate// greatest integer Function class GFG{// Function to calculate the// GIF value of a numberstatic int GIF(double n){ // GIF is the floor of a number return (int)Math.floor(n);} // Driver codepublic static void main(String[] args){ double n = 2.3; System.out.println(GIF(n));}}// This code is contributed by mits
# Python3 program to illustrate# greatest integer Functionimport math # Function to calculate the# GIF value of a numberdef GIF(n): # GIF is the floor of a number return int(math.floor(n)); # Driver coden = 2.3; print(GIF(n)); # This code is contributed by mits
// C# program to illustrate// greatest integer Functionusing System; class GFG{// Function to calculate the// GIF value of a numberstatic int GIF(double n){ // GIF is the floor of a number return (int)Math.Floor(n);} // Driver codestatic void Main(){ double n = 2.3; Console.WriteLine(GIF(n));}} // This code is contributed by mits
<?php // PHP program to illustrate// greatest integer Function // Function to calculate the// GIF value of a numberfunction GIF($n){ // GIF is the floor of a number return floor($n);} // Driver code $n = 2.3; echo GIF($n); ?>
<script> // Javascript program to illustrate// greatest integer Function // Function to calculate the// GIF value of a numberfunction GIF(n){ // GIF is the floor of a number return Math.floor(n);} // Driver codevar n = 2.3; document.write(GIF(n)); // This code is contributed by Ankita saini </script>
2
Mithun Kumar
ankita_saini
cpp-math
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
|
[
{
"code": null,
"e": 25962,
"s": 25934,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 26295,
"s": 25962,
"text": "The greatest Integer Function [X] indicates an integral part of the real number which is the nearest and smaller integer to . It is also known as the floor of X.[x]=the largest integer that is less than or equal to x.In general: If, <= < . Then, This means if X lies in [n, n+1), then the Greatest Integer Function of X will be n. "
},
{
"code": null,
"e": 26487,
"s": 26295,
"text": "In the above figure, we are taking the floor of the values each time. When the intervals are in the form of [n, n+1), the value of the greatest integer function is n, where n is an integer. "
},
{
"code": null,
"e": 26794,
"s": 26487,
"text": "0<=x<1 will always lie in the interval [0, 0.9), so here the Greatest Integer Function of X will be 0.1<=x<2 will always lie in the interval [1, 1.9), so here the Greatest Integer Function of X will be 1.2<=x<3 will always lie in the interval [2, 2.9), so here the Greatest Integer Function of X will be 2."
},
{
"code": null,
"e": 26897,
"s": 26794,
"text": "0<=x<1 will always lie in the interval [0, 0.9), so here the Greatest Integer Function of X will be 0."
},
{
"code": null,
"e": 27000,
"s": 26897,
"text": "1<=x<2 will always lie in the interval [1, 1.9), so here the Greatest Integer Function of X will be 1."
},
{
"code": null,
"e": 27103,
"s": 27000,
"text": "2<=x<3 will always lie in the interval [2, 2.9), so here the Greatest Integer Function of X will be 2."
},
{
"code": null,
"e": 27115,
"s": 27103,
"text": "Examples: "
},
{
"code": null,
"e": 27221,
"s": 27115,
"text": "Input: X = 2.3\nOutput: [2.3] = 2\n\nInput: X = -8.0725\nOutput: [-8.0725] = -9\n\nInput: X = 2\nOutput: [2] = 2"
},
{
"code": null,
"e": 27323,
"s": 27221,
"text": "Number Line RepresentationIf we examine a number line with the integers and plot 2.7 on it, we see: "
},
{
"code": null,
"e": 27461,
"s": 27323,
"text": "The largest integer that is less than 2.7 is 2. So [2.7] = 2. If we examine a number line with the integers and plot -1.3 on it, we see: "
},
{
"code": null,
"e": 27581,
"s": 27461,
"text": "Since the largest integer that is less than -1.3 is -2, so [-1.3] = 2.Here, f(x)=[X] could be expressed graphically as:"
},
{
"code": null,
"e": 27805,
"s": 27581,
"text": "Note: In the above graph, the left endpoint at every step is blocked(dark dot) to show that the point is a member of the graph, and the other right endpoint (open circle) indicates the points that are not part of the graph."
},
{
"code": null,
"e": 27847,
"s": 27805,
"text": "Properties of Greatest Integer Function: "
},
{
"code": null,
"e": 27879,
"s": 27847,
"text": "[X]=X holds if X is an integer."
},
{
"code": null,
"e": 27971,
"s": 27879,
"text": "[X+I]=[X]+I, if I is an integer, then we can I separately in the Greatest Integer Function."
},
{
"code": null,
"e": 28087,
"s": 27971,
"text": "[X+Y]>=[X]+[Y], means the greatest integer of the sum of X and Y is the equal sum of the GIF of X and the GIF of Y."
},
{
"code": null,
"e": 28117,
"s": 28087,
"text": "If [f(X)]>=I, then f(X) >= I."
},
{
"code": null,
"e": 28148,
"s": 28117,
"text": "If [f(X)]<=I, then f(X) < I+1."
},
{
"code": null,
"e": 28173,
"s": 28148,
"text": "[-X]= -[X], If XInteger."
},
{
"code": null,
"e": 28210,
"s": 28173,
"text": "[-X]=-[X]-1, If X is not an Integer."
},
{
"code": null,
"e": 28359,
"s": 28210,
"text": "It is also known as the stepwise function or floor of X.The below program shows the implementation of the Greatest Integer Function using floor(): "
},
{
"code": null,
"e": 28363,
"s": 28359,
"text": "C++"
},
{
"code": null,
"e": 28368,
"s": 28363,
"text": "Java"
},
{
"code": null,
"e": 28376,
"s": 28368,
"text": "Python3"
},
{
"code": null,
"e": 28379,
"s": 28376,
"text": "C#"
},
{
"code": null,
"e": 28383,
"s": 28379,
"text": "PHP"
},
{
"code": null,
"e": 28394,
"s": 28383,
"text": "Javascript"
},
{
"code": "// CPP program to illustrate// greatest integer Function#include <bits/stdc++.h>using namespace std; // Function to calculate the// GIF value of a numberint GIF(float n){ // GIF is the floor of a number return floor(n);} // Driver codeint main(){ int n = 2.3; cout << GIF(n); return 0;}",
"e": 28698,
"s": 28394,
"text": null
},
{
"code": "// Java program to illustrate// greatest integer Function class GFG{// Function to calculate the// GIF value of a numberstatic int GIF(double n){ // GIF is the floor of a number return (int)Math.floor(n);} // Driver codepublic static void main(String[] args){ double n = 2.3; System.out.println(GIF(n));}}// This code is contributed by mits",
"e": 29052,
"s": 28698,
"text": null
},
{
"code": "# Python3 program to illustrate# greatest integer Functionimport math # Function to calculate the# GIF value of a numberdef GIF(n): # GIF is the floor of a number return int(math.floor(n)); # Driver coden = 2.3; print(GIF(n)); # This code is contributed by mits",
"e": 29329,
"s": 29052,
"text": null
},
{
"code": "// C# program to illustrate// greatest integer Functionusing System; class GFG{// Function to calculate the// GIF value of a numberstatic int GIF(double n){ // GIF is the floor of a number return (int)Math.Floor(n);} // Driver codestatic void Main(){ double n = 2.3; Console.WriteLine(GIF(n));}} // This code is contributed by mits",
"e": 29674,
"s": 29329,
"text": null
},
{
"code": "<?php // PHP program to illustrate// greatest integer Function // Function to calculate the// GIF value of a numberfunction GIF($n){ // GIF is the floor of a number return floor($n);} // Driver code $n = 2.3; echo GIF($n); ?>",
"e": 29914,
"s": 29674,
"text": null
},
{
"code": "<script> // Javascript program to illustrate// greatest integer Function // Function to calculate the// GIF value of a numberfunction GIF(n){ // GIF is the floor of a number return Math.floor(n);} // Driver codevar n = 2.3; document.write(GIF(n)); // This code is contributed by Ankita saini </script>",
"e": 30222,
"s": 29914,
"text": null
},
{
"code": null,
"e": 30224,
"s": 30222,
"text": "2"
},
{
"code": null,
"e": 30239,
"s": 30226,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30252,
"s": 30239,
"text": "ankita_saini"
},
{
"code": null,
"e": 30261,
"s": 30252,
"text": "cpp-math"
},
{
"code": null,
"e": 30275,
"s": 30261,
"text": "number-theory"
},
{
"code": null,
"e": 30288,
"s": 30275,
"text": "Mathematical"
},
{
"code": null,
"e": 30302,
"s": 30288,
"text": "number-theory"
},
{
"code": null,
"e": 30315,
"s": 30302,
"text": "Mathematical"
},
{
"code": null,
"e": 30413,
"s": 30315,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30457,
"s": 30413,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30499,
"s": 30457,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 30530,
"s": 30499,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30601,
"s": 30530,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 30626,
"s": 30601,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30658,
"s": 30626,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 30691,
"s": 30658,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30726,
"s": 30691,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 30772,
"s": 30726,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
Underscore.js _.union() Function - GeeksforGeeks
|
24 Nov, 2021
The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects.The _.union() function is used to take n number of arrays and return a new array with the unique terms in all those arrays (union of all array). In the new array the order of the elements is same like it is mentioned in all the passed arrays. The first occurrence of each array is only included in the resultant array.
Syntax:
_.union( *arrays )
Parameters: This function accepts single parameter arrays which is the collection of multiple array list. The array list are separated by , operator.
Return value: It returns an array which contains unique elements of all the elements in n passed arrays.
Passing a list of numbers to _.union() function: The ._union() function takes the element from the list one by one checks whether it is already present in the resultant array or not. If it is present then it just ignores it otherwise adds it to the resultant array. The final result contains the union of array.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.union([51, 52, 1, 4], [1, 2, 3, 4], [1, 2])); </script> </body></html>
Output:
Passing a combination of words, false values and numbers to the _.union() function: Passing any kind of elements whether it is a number, word or even false elements like empty strings, null values etc, the _.union() function will not distinguish between them. It will rather treat every element in the same manner. The further process will be the same.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.union(["gfg", 52, " ", 1, "hello"], ['*', 2, undefined, 4], ['', null], ["gfg2", "end"])); </script> </body></html>
Output:
Passing a set of strings to the _.union() function: Pass a set of strings to this function so as to get the common of all the n arrays passed in the result. The processing will occur in the same way. Only the words given in the second parameter will be excluded.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.union(["This", "geeks"], ['for', "geeks2", "is", "amazing"], ["This", "is", "best", "platform"])); </script> </body></html>
Output:
Passing arrays with same elements to the _.union() function: If pass arrays to the _.union() function and they have the same elements then union of all the arrays will be the first array itself. All the elements will be common and hence will be present in the result given after union.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.union([100, 200], [100, 200], [100, 200], [100, 200], [100, 200], [100, 200])); </script> </body></html>
Output:
Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them.
<script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script>
JavaScript - Underscore.js
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 34847,
"s": 34819,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 35321,
"s": 34847,
"text": "The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects.The _.union() function is used to take n number of arrays and return a new array with the unique terms in all those arrays (union of all array). In the new array the order of the elements is same like it is mentioned in all the passed arrays. The first occurrence of each array is only included in the resultant array."
},
{
"code": null,
"e": 35329,
"s": 35321,
"text": "Syntax:"
},
{
"code": null,
"e": 35348,
"s": 35329,
"text": "_.union( *arrays )"
},
{
"code": null,
"e": 35498,
"s": 35348,
"text": "Parameters: This function accepts single parameter arrays which is the collection of multiple array list. The array list are separated by , operator."
},
{
"code": null,
"e": 35603,
"s": 35498,
"text": "Return value: It returns an array which contains unique elements of all the elements in n passed arrays."
},
{
"code": null,
"e": 35915,
"s": 35603,
"text": "Passing a list of numbers to _.union() function: The ._union() function takes the element from the list one by one checks whether it is already present in the resultant array or not. If it is present then it just ignores it otherwise adds it to the resultant array. The final result contains the union of array."
},
{
"code": null,
"e": 35924,
"s": 35915,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.union([51, 52, 1, 4], [1, 2, 3, 4], [1, 2])); </script> </body></html> ",
"e": 36325,
"s": 35924,
"text": null
},
{
"code": null,
"e": 36333,
"s": 36325,
"text": "Output:"
},
{
"code": null,
"e": 36686,
"s": 36333,
"text": "Passing a combination of words, false values and numbers to the _.union() function: Passing any kind of elements whether it is a number, word or even false elements like empty strings, null values etc, the _.union() function will not distinguish between them. It will rather treat every element in the same manner. The further process will be the same."
},
{
"code": null,
"e": 36695,
"s": 36686,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.union([\"gfg\", 52, \" \", 1, \"hello\"], ['*', 2, undefined, 4], ['', null], [\"gfg2\", \"end\"])); </script> </body></html> ",
"e": 37173,
"s": 36695,
"text": null
},
{
"code": null,
"e": 37181,
"s": 37173,
"text": "Output:"
},
{
"code": null,
"e": 37444,
"s": 37181,
"text": "Passing a set of strings to the _.union() function: Pass a set of strings to this function so as to get the common of all the n arrays passed in the result. The processing will occur in the same way. Only the words given in the second parameter will be excluded."
},
{
"code": null,
"e": 37453,
"s": 37444,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.union([\"This\", \"geeks\"], ['for', \"geeks2\", \"is\", \"amazing\"], [\"This\", \"is\", \"best\", \"platform\"])); </script> </body></html> ",
"e": 37906,
"s": 37453,
"text": null
},
{
"code": null,
"e": 37914,
"s": 37906,
"text": "Output:"
},
{
"code": null,
"e": 38200,
"s": 37914,
"text": "Passing arrays with same elements to the _.union() function: If pass arrays to the _.union() function and they have the same elements then union of all the arrays will be the first array itself. All the elements will be common and hence will be present in the result given after union."
},
{
"code": null,
"e": 38209,
"s": 38200,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.union([100, 200], [100, 200], [100, 200], [100, 200], [100, 200], [100, 200])); </script> </body></html> ",
"e": 38740,
"s": 38209,
"text": null
},
{
"code": null,
"e": 38748,
"s": 38740,
"text": "Output:"
},
{
"code": null,
"e": 38953,
"s": 38748,
"text": "Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them."
},
{
"code": "<script type=\"text/javascript\" src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script> ",
"e": 39081,
"s": 38953,
"text": null
},
{
"code": null,
"e": 39108,
"s": 39081,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 39129,
"s": 39108,
"text": "javascript-functions"
},
{
"code": null,
"e": 39140,
"s": 39129,
"text": "JavaScript"
},
{
"code": null,
"e": 39157,
"s": 39140,
"text": "Web Technologies"
},
{
"code": null,
"e": 39255,
"s": 39157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39295,
"s": 39255,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 39340,
"s": 39295,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 39401,
"s": 39340,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 39473,
"s": 39401,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 39542,
"s": 39473,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 39582,
"s": 39542,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 39615,
"s": 39582,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 39660,
"s": 39615,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 39703,
"s": 39660,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Node.js MySQL Insert into Table - GeeksforGeeks
|
07 Oct, 2021
NodeJs: An open-source platform for executing javascript code on the server side. Also, a javascript runtime built on Chrome’s V8 JavaScript engine. It can be downloaded from here. Mysql An open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the most popular language for adding, accessing, and managing content in a database. Here we will use the Mysql as a database for our node application. It can be downloaded from here.
In this article, we are going to learn how to insert rows into an SQL table using Node.js.With the help of SQL INSERT Query.
Initialize Node.js project:
npm init
Installing Modules:
npm install express
npm install mysql
File Structure:
MySQL Database Structure:
gfg_db DATABASE.
gfg_table (id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255), address VARCHAR(255)).
sqlConnection.js
// Importing MySQL moduleconst mysql = require("mysql"); // Creating connectionlet db_con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "gfg_db"}); // Connect to MySQL serverdb_con.connect((err) => { if (err) { console.log("Database Connection Failed !!!", err); } else { console.log("connected to Database"); }}); module.exports = db_con;
Anytime we want to make a query we will import the db_con module in that file. This will increase the modularity of our code.
index.js
const express = require("express");const database = require('./sqlConnection'); const app = express(); app.listen(5000, () => { console.log(`Server is up and running on 5000 ...`);}); // Use Route Function from below Examples Here... app.get("/", (req, res) => { // Call Route Function Here...});
Example:
Inserting Single Row: Below is a Route function to insert single row.
Javascript
// Function to insert single row values in// the databaselet singleRowInsert = () => { let query = `INSERT INTO gfg_table (name, address) VALUES (?, ?);`; // Value to be inserted let userName = "Pratik"; let userAddress = "My Address"; // Creating queries db_con.query(query, [userName, userAddress], (err, rows) => { if (err) throw err; console.log("Row inserted with id = " + rows.insertId); });};
Output:
Console output:
Row inserted with id = 1
Inserting Multiple Rows: Below is a Route function to insert multiple rows.
Javascript
// Function to insert multiple Row in databaselet multipleRowInsert = () => { // Query to insert multiple rows let query = `INSERT INTO gfg_table (name, address) VALUES ?;`; // Values to be inserted let values = [ ['Amit', 'Yellow Park'], ['Rishi', 'Park 38'], ['Akash', 'Central st 954'], ['Pratik', 'Road 989'], ['Mangesh', 'Sideway'] ]; // Executing the query db_con.query(query, [values], (err, rows) => { if (err) throw err; console.log("All Rows Inserted"); });};
Database Output:
Console output:
All Rows Inserted
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 26749,
"s": 26267,
"text": "NodeJs: An open-source platform for executing javascript code on the server side. Also, a javascript runtime built on Chrome’s V8 JavaScript engine. It can be downloaded from here. Mysql An open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the most popular language for adding, accessing, and managing content in a database. Here we will use the Mysql as a database for our node application. It can be downloaded from here."
},
{
"code": null,
"e": 26874,
"s": 26749,
"text": "In this article, we are going to learn how to insert rows into an SQL table using Node.js.With the help of SQL INSERT Query."
},
{
"code": null,
"e": 26902,
"s": 26874,
"text": "Initialize Node.js project:"
},
{
"code": null,
"e": 26911,
"s": 26902,
"text": "npm init"
},
{
"code": null,
"e": 26932,
"s": 26911,
"text": "Installing Modules: "
},
{
"code": null,
"e": 26970,
"s": 26932,
"text": "npm install express\nnpm install mysql"
},
{
"code": null,
"e": 26986,
"s": 26970,
"text": "File Structure:"
},
{
"code": null,
"e": 27012,
"s": 26986,
"text": "MySQL Database Structure:"
},
{
"code": null,
"e": 27120,
"s": 27012,
"text": "gfg_db DATABASE.\ngfg_table (id INT AUTO_INCREMENT PRIMARY KEY, \n name VARCHAR(255), address VARCHAR(255))."
},
{
"code": null,
"e": 27137,
"s": 27120,
"text": "sqlConnection.js"
},
{
"code": "// Importing MySQL moduleconst mysql = require(\"mysql\"); // Creating connectionlet db_con = mysql.createConnection({ host: \"localhost\", user: \"root\", password: \"\", database: \"gfg_db\"}); // Connect to MySQL serverdb_con.connect((err) => { if (err) { console.log(\"Database Connection Failed !!!\", err); } else { console.log(\"connected to Database\"); }}); module.exports = db_con;",
"e": 27531,
"s": 27137,
"text": null
},
{
"code": null,
"e": 27657,
"s": 27531,
"text": "Anytime we want to make a query we will import the db_con module in that file. This will increase the modularity of our code."
},
{
"code": null,
"e": 27666,
"s": 27657,
"text": "index.js"
},
{
"code": "const express = require(\"express\");const database = require('./sqlConnection'); const app = express(); app.listen(5000, () => { console.log(`Server is up and running on 5000 ...`);}); // Use Route Function from below Examples Here... app.get(\"/\", (req, res) => { // Call Route Function Here...});",
"e": 27973,
"s": 27666,
"text": null
},
{
"code": null,
"e": 27982,
"s": 27973,
"text": "Example:"
},
{
"code": null,
"e": 28052,
"s": 27982,
"text": "Inserting Single Row: Below is a Route function to insert single row."
},
{
"code": null,
"e": 28063,
"s": 28052,
"text": "Javascript"
},
{
"code": "// Function to insert single row values in// the databaselet singleRowInsert = () => { let query = `INSERT INTO gfg_table (name, address) VALUES (?, ?);`; // Value to be inserted let userName = \"Pratik\"; let userAddress = \"My Address\"; // Creating queries db_con.query(query, [userName, userAddress], (err, rows) => { if (err) throw err; console.log(\"Row inserted with id = \" + rows.insertId); });};",
"e": 28527,
"s": 28063,
"text": null
},
{
"code": null,
"e": 28535,
"s": 28527,
"text": "Output:"
},
{
"code": null,
"e": 28551,
"s": 28535,
"text": "Console output:"
},
{
"code": null,
"e": 28576,
"s": 28551,
"text": "Row inserted with id = 1"
},
{
"code": null,
"e": 28652,
"s": 28576,
"text": "Inserting Multiple Rows: Below is a Route function to insert multiple rows."
},
{
"code": null,
"e": 28663,
"s": 28652,
"text": "Javascript"
},
{
"code": "// Function to insert multiple Row in databaselet multipleRowInsert = () => { // Query to insert multiple rows let query = `INSERT INTO gfg_table (name, address) VALUES ?;`; // Values to be inserted let values = [ ['Amit', 'Yellow Park'], ['Rishi', 'Park 38'], ['Akash', 'Central st 954'], ['Pratik', 'Road 989'], ['Mangesh', 'Sideway'] ]; // Executing the query db_con.query(query, [values], (err, rows) => { if (err) throw err; console.log(\"All Rows Inserted\"); });};",
"e": 29220,
"s": 28663,
"text": null
},
{
"code": null,
"e": 29237,
"s": 29220,
"text": "Database Output:"
},
{
"code": null,
"e": 29253,
"s": 29237,
"text": "Console output:"
},
{
"code": null,
"e": 29271,
"s": 29253,
"text": "All Rows Inserted"
},
{
"code": null,
"e": 29295,
"s": 29271,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29303,
"s": 29295,
"text": "Node.js"
},
{
"code": null,
"e": 29322,
"s": 29303,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29339,
"s": 29322,
"text": "Web Technologies"
},
{
"code": null,
"e": 29437,
"s": 29339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29467,
"s": 29437,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 29496,
"s": 29467,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 29553,
"s": 29496,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 29607,
"s": 29553,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 29644,
"s": 29607,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 29684,
"s": 29644,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29729,
"s": 29684,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29772,
"s": 29729,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29822,
"s": 29772,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
random.normalvariate() function in Python - GeeksforGeeks
|
26 May, 2020
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
normalvariate() is an inbuilt method of the random module. It is used to return a random floating point number with normal distribution.
Syntax : random.normalvariate(mu, sigma)
Parameters :mu : meansigma : standard deviation
Returns : a random normal distribution floating number
Example 1:
# import the random moduleimport random # determining the values of the parametersmu = 100sigma = 50 # using the normalvariate() methodprint(random.normalvariate(mu, sigma))
Output :
110.86699628241412
Example 2: We can generate the number multiple times and plot a graph to observe the normal distribution.
# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] mu = 100sigma = 50 for i in range(100): temp = random.normalvariate(mu, sigma) nums.append(temp) # plotting a graph plt.plot(nums) plt.show()
Output :
Example 3: We can create a histogram to observe the density of the normal distribution.
# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] mu = 100sigma = 50 for i in range(10000): temp = random.normalvariate(mu, sigma) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show()
Output :
Python-random
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 25047,
"s": 25019,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 25253,
"s": 25047,
"text": "random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined."
},
{
"code": null,
"e": 25390,
"s": 25253,
"text": "normalvariate() is an inbuilt method of the random module. It is used to return a random floating point number with normal distribution."
},
{
"code": null,
"e": 25431,
"s": 25390,
"text": "Syntax : random.normalvariate(mu, sigma)"
},
{
"code": null,
"e": 25479,
"s": 25431,
"text": "Parameters :mu : meansigma : standard deviation"
},
{
"code": null,
"e": 25534,
"s": 25479,
"text": "Returns : a random normal distribution floating number"
},
{
"code": null,
"e": 25545,
"s": 25534,
"text": "Example 1:"
},
{
"code": "# import the random moduleimport random # determining the values of the parametersmu = 100sigma = 50 # using the normalvariate() methodprint(random.normalvariate(mu, sigma))",
"e": 25721,
"s": 25545,
"text": null
},
{
"code": null,
"e": 25730,
"s": 25721,
"text": "Output :"
},
{
"code": null,
"e": 25749,
"s": 25730,
"text": "110.86699628241412"
},
{
"code": null,
"e": 25855,
"s": 25749,
"text": "Example 2: We can generate the number multiple times and plot a graph to observe the normal distribution."
},
{
"code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] mu = 100sigma = 50 for i in range(100): temp = random.normalvariate(mu, sigma) nums.append(temp) # plotting a graph plt.plot(nums) plt.show()",
"e": 26147,
"s": 25855,
"text": null
},
{
"code": null,
"e": 26156,
"s": 26147,
"text": "Output :"
},
{
"code": null,
"e": 26244,
"s": 26156,
"text": "Example 3: We can create a histogram to observe the density of the normal distribution."
},
{
"code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] mu = 100sigma = 50 for i in range(10000): temp = random.normalvariate(mu, sigma) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show()",
"e": 26548,
"s": 26244,
"text": null
},
{
"code": null,
"e": 26557,
"s": 26548,
"text": "Output :"
},
{
"code": null,
"e": 26571,
"s": 26557,
"text": "Python-random"
},
{
"code": null,
"e": 26578,
"s": 26571,
"text": "Python"
},
{
"code": null,
"e": 26676,
"s": 26578,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26704,
"s": 26676,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26754,
"s": 26704,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26776,
"s": 26754,
"text": "Python map() function"
},
{
"code": null,
"e": 26820,
"s": 26776,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 26838,
"s": 26820,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26861,
"s": 26838,
"text": "Taking input in Python"
},
{
"code": null,
"e": 26896,
"s": 26861,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26928,
"s": 26896,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26950,
"s": 26928,
"text": "Enumerate() in Python"
}
] |
Python | List frequency of elements - GeeksforGeeks
|
18 Jan, 2022
Sometimes we have the utility in which we require to find the frequency of elements in the list and the solution to this problem has been discussed many times. But sometimes we come across the task in which we require to find the number of lists that particular elements occur. Let’s discuss certain shorthands in which this can be done.
Method #1 : Using Counter() + set() + list comprehension The combination of the above functions can be used to perform the task. The Counter function does the grouping, set function extracts the distinct elements as keys of dict and list comprehension check for its list occurrences.
Python3
# Python3 code to demonstrate# list frequency of elements# using Counter() + set() + list comprehensionfrom collections import Counter # initializing listtest_list = [[3, 5, 4], [6, 2, 4], [1, 3, 6]] # printing original listprint("The original list : " + str(test_list)) # using Counter() + set() + list comprehension# list frequency of elementsres = dict(Counter(i for sub in test_list for i in set(sub))) # printing resultprint("The list frequency of elements is : " + str(res))
The original list : [[3, 5, 4], [6, 2, 4], [1, 3, 6]]
The list frequency of elements is : {1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 2}
Method #2 : Using Counter() + itertools.chain.from_iterable() + map() + set() The above 4 functionalities can also be combined to achieve this particular task. The set function extracts the dictionary keys formed by the Counter, map function performs the task for all sublists and from_iterable function performs using iterators which is faster than list comprehension.
Python3
# Python3 code to demonstrate# list frequency of elements# using Counter() + itertools.chain.from_iterable() + map() + set()from collections import Counterfrom itertools import chain # initializing listtest_list = [[3, 5, 4], [6, 2, 4], [1, 3, 6]] # printing original listprint("The original list : " + str(test_list)) # using Counter() + itertools.chain.from_iterable() + map() + set()# list frequency of elementsres = dict(Counter(chain.from_iterable(map(set, test_list)))) # printing resultprint("The list frequency of elements is : " + str(res))
The original list : [[3, 5, 4], [6, 2, 4], [1, 3, 6]]
The list frequency of elements is : {1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 2}
Method #3: Using python dictionary + get() method
Python dictionary provides a get method which returns the value corresponding to the key and if the key does not exist in the dictionary then it provides functionality to create the key and assign it a default value. We will use this functionality of a dictionary.
Python3
d = {} test_list = [[3, 5, 4], [6, 2, 4], [1, 3, 6]] for x in test_list: for i in x: d[i] = d.get(i,0) + 1 # Original listprint(f"The original list : {test_list}" ) # printing resultprint(f"The list frequency of elements is : {d}" )
Output:
The original list : [[3, 5, 4], [6, 2, 4], [1, 3, 6]]
The list frequency of elements is : {3: 2, 5: 1, 4: 2, 6: 2, 2: 1, 1: 1}
Method #4: Using Pandas
In this method we will use a python module named pandas(You can know more about pandas in this article) to find the frequency of the given data, here below is the code for it.
Python3
import pandas as pd test_list = [3,5,4,3,3,4,5,2] df1 = pd.Series(test_list).value_counts().sort_index().reset_index().reset_index(drop=True)df1.columns = ['Element', 'Frequency'] # Original listprint(f"The original list : {test_list}" ) # printing resultprint(f"The list frequency of elements is :\n {df1.to_string(index=False)}" )
Output:
The original list : [3, 5, 4, 3, 3, 4, 5, 2]
The list frequency of elements is :
Element Frequency
2 1
3 3
4 2
5 2
UnworthyProgrammer
sagartomar9927
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 26093,
"s": 26065,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 26432,
"s": 26093,
"text": "Sometimes we have the utility in which we require to find the frequency of elements in the list and the solution to this problem has been discussed many times. But sometimes we come across the task in which we require to find the number of lists that particular elements occur. Let’s discuss certain shorthands in which this can be done. "
},
{
"code": null,
"e": 26717,
"s": 26432,
"text": "Method #1 : Using Counter() + set() + list comprehension The combination of the above functions can be used to perform the task. The Counter function does the grouping, set function extracts the distinct elements as keys of dict and list comprehension check for its list occurrences. "
},
{
"code": null,
"e": 26725,
"s": 26717,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# list frequency of elements# using Counter() + set() + list comprehensionfrom collections import Counter # initializing listtest_list = [[3, 5, 4], [6, 2, 4], [1, 3, 6]] # printing original listprint(\"The original list : \" + str(test_list)) # using Counter() + set() + list comprehension# list frequency of elementsres = dict(Counter(i for sub in test_list for i in set(sub))) # printing resultprint(\"The list frequency of elements is : \" + str(res))",
"e": 27230,
"s": 26725,
"text": null
},
{
"code": null,
"e": 27357,
"s": 27230,
"text": "The original list : [[3, 5, 4], [6, 2, 4], [1, 3, 6]]\nThe list frequency of elements is : {1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 2}"
},
{
"code": null,
"e": 27731,
"s": 27359,
"text": " Method #2 : Using Counter() + itertools.chain.from_iterable() + map() + set() The above 4 functionalities can also be combined to achieve this particular task. The set function extracts the dictionary keys formed by the Counter, map function performs the task for all sublists and from_iterable function performs using iterators which is faster than list comprehension. "
},
{
"code": null,
"e": 27739,
"s": 27731,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# list frequency of elements# using Counter() + itertools.chain.from_iterable() + map() + set()from collections import Counterfrom itertools import chain # initializing listtest_list = [[3, 5, 4], [6, 2, 4], [1, 3, 6]] # printing original listprint(\"The original list : \" + str(test_list)) # using Counter() + itertools.chain.from_iterable() + map() + set()# list frequency of elementsres = dict(Counter(chain.from_iterable(map(set, test_list)))) # printing resultprint(\"The list frequency of elements is : \" + str(res))",
"e": 28313,
"s": 27739,
"text": null
},
{
"code": null,
"e": 28440,
"s": 28313,
"text": "The original list : [[3, 5, 4], [6, 2, 4], [1, 3, 6]]\nThe list frequency of elements is : {1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 2}"
},
{
"code": null,
"e": 28492,
"s": 28442,
"text": "Method #3: Using python dictionary + get() method"
},
{
"code": null,
"e": 28757,
"s": 28492,
"text": "Python dictionary provides a get method which returns the value corresponding to the key and if the key does not exist in the dictionary then it provides functionality to create the key and assign it a default value. We will use this functionality of a dictionary."
},
{
"code": null,
"e": 28765,
"s": 28757,
"text": "Python3"
},
{
"code": "d = {} test_list = [[3, 5, 4], [6, 2, 4], [1, 3, 6]] for x in test_list: for i in x: d[i] = d.get(i,0) + 1 # Original listprint(f\"The original list : {test_list}\" ) # printing resultprint(f\"The list frequency of elements is : {d}\" )",
"e": 29026,
"s": 28765,
"text": null
},
{
"code": null,
"e": 29034,
"s": 29026,
"text": "Output:"
},
{
"code": null,
"e": 29161,
"s": 29034,
"text": "The original list : [[3, 5, 4], [6, 2, 4], [1, 3, 6]]\nThe list frequency of elements is : {3: 2, 5: 1, 4: 2, 6: 2, 2: 1, 1: 1}"
},
{
"code": null,
"e": 29186,
"s": 29161,
"text": "Method #4: Using Pandas "
},
{
"code": null,
"e": 29362,
"s": 29186,
"text": "In this method we will use a python module named pandas(You can know more about pandas in this article) to find the frequency of the given data, here below is the code for it."
},
{
"code": null,
"e": 29370,
"s": 29362,
"text": "Python3"
},
{
"code": "import pandas as pd test_list = [3,5,4,3,3,4,5,2] df1 = pd.Series(test_list).value_counts().sort_index().reset_index().reset_index(drop=True)df1.columns = ['Element', 'Frequency'] # Original listprint(f\"The original list : {test_list}\" ) # printing resultprint(f\"The list frequency of elements is :\\n {df1.to_string(index=False)}\" )",
"e": 29703,
"s": 29370,
"text": null
},
{
"code": null,
"e": 29711,
"s": 29703,
"text": "Output:"
},
{
"code": null,
"e": 29878,
"s": 29711,
"text": "The original list : [3, 5, 4, 3, 3, 4, 5, 2]\nThe list frequency of elements is :\nElement Frequency\n 2 1\n 3 3 \n 4 2\n 5 2"
},
{
"code": null,
"e": 29897,
"s": 29878,
"text": "UnworthyProgrammer"
},
{
"code": null,
"e": 29912,
"s": 29897,
"text": "sagartomar9927"
},
{
"code": null,
"e": 29933,
"s": 29912,
"text": "Python list-programs"
},
{
"code": null,
"e": 29940,
"s": 29933,
"text": "Python"
},
{
"code": null,
"e": 29956,
"s": 29940,
"text": "Python Programs"
},
{
"code": null,
"e": 30054,
"s": 29956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30072,
"s": 30054,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30104,
"s": 30072,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30126,
"s": 30104,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30168,
"s": 30126,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30194,
"s": 30168,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30216,
"s": 30194,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30262,
"s": 30216,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 30300,
"s": 30262,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 30340,
"s": 30300,
"text": "How to print without newline in Python?"
}
] |
Sum of fourth powers of the first n natural numbers - GeeksforGeeks
|
31 Mar, 2021
Write a program to find the sum of fourth powers of the first n natural numbers 14 + 24 + 34 + 44 + .......+ n4 till n-th term.Examples :
Input : 4
Output : 354
14 + 24 + 34 + 44 = 354
Input : 6
Output : 2275
14 + 24 + 34 + 44+ 54+ 64 = 2275
Naive Approach :- Simple finding the fourth powers of the first n natural numbers is iterate a loop from 1 to n time. like suppose n=4. (1*1*1*1)+(2*2*2*2)+(3*3*3*3)+(4*4*4*4) = 354
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the sum of forth powers// of first n natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of forth power of first n// natural numberslong long int fourthPowerSum(int n){ long long int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum;} // Driven Programint main(){ int n = 6; cout << fourthPowerSum(n) << endl; return 0;}
// Java Program to find the// sum of forth powers of// first n natural numbersimport java.io.*;import java.util.*; class GFG { // Return the sum of forth // power of first n natural // numbers static long fourthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum; } public static void main (String[] args) { int n = 6; System.out.println(fourthPowerSum(n)); }} // This code is contributed by Gitanjali.
# Python3 Program to find the# sum of forth powers of first# n natural numbersimport math # Return the sum of forth power of# first n natural numbersdef fourthPowerSum( n): sum = 0 for i in range(1, n+1) : sum = sum + (i * i * i * i) return sum# Driver methodn=6print (fourthPowerSum(n)) # This code is contributed by Gitanjali.
// C# program to find the// sum of forth powers of// first n natural numbersusing System; class GFG { // Return the sum of forth power // of first n natural numbers static long fourthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum; } public static void Main () { int n = 6; Console.WriteLine(fourthPowerSum(n)); }} // This code is contributed by vt_m.
<?php// PHP Program to find th// sum of fourth powers// of first n natural numbers // Return the sum of fourth// power of first n// natural numbersfunction fourthPowerSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + ($i * $i * $i * $i); return $sum;} // Driver Code$n = 6;echo(fourthPowerSum($n)); // This code is contributed by Ajit.?>
<script> // javascript Program to find the sum of forth powers// of first n natural numbers // Return the sum of forth power of first n// natural numbersfunction fourthPowerSum( n){ let sum = 0; for (let i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum;}// Driven Program let n = 6; document.write(fourthPowerSum(n)); // This code contributed by aashish1995 </script>
Output:
2275
Time Complexity : O(n)Efficient Approach :- An efficient solution is to use direct mathematical formula which is 1/30n(n+1)(2n+1)(3n2+3n+1) or it is also write (1/5)n5 + (1/2)n4 + (1/3)n3 – (1/30)n. This solution take O(1) time.
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the sum of forth power of first// n natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of forth power of first n natural// numberslong long int fourthPowerSum(int n){ return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30;} // Driven Programint main(){ int n = 6; cout << fourthPowerSum(n) << endl; return 0;}
// Java Program to find the// sum of forth powers of// first n natural numbersimport java.io.*;import java.util.*; class GFG { // Return the sum of // forth power of first // n natural numbers static long fourthPowerSum(int n) { return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30; } public static void main (String[] args) { int n = 6; System.out.println(fourthPowerSum(n)); }} // This code is contributed by Gitanjali.
# Python3 Program to# find the sum of# forth powers of# first n natural numbersimport math # Return the sum of# forth power of# first n natural# numbersdef fourthPowerSum(n): return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30 # Driver methodn=6print (fourthPowerSum(n)) # This code is contributed by Gitanjali.
// C# Program to find the// sum of forth powers of// first n natural numbersusing System; class GFG { // Return the sum of // forth power of first // n natural numbers static long fourthPowerSum(int n) { return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30; } public static void Main () { int n = 6; Console.Write(fourthPowerSum(n)); }} // This code is contributed by vt_m.
<?php// PHP Program to find the sum// of fourth power of first// n natural numbers // Return the sum of fourth// power of first n natural// numbersfunction fourthPowerSum($n){ return ((6 * $n * $n * $n * $n * $n) + (15 * $n * $n * $n * $n) + (10 * $n * $n * $n) - $n) / 30;} // Driver Code$n = 6;echo(fourthPowerSum($n)); // This code is contributed by Ajit.?>
<script> // javascript Program to find the// sum of forth powers of// first n natural numbers // Return the sum of// forth power of first// n natural numbersfunction fourthPowerSum(n){ return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30;} var n = 6; document.write(fourthPowerSum(n)); // This code is contributed by 29AjayKumar </script>
Output:
2275
Time Complexity : O(1)
jit_t
aashish1995
29AjayKumar
number-theory
series
series-sum
Mathematical
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
|
[
{
"code": null,
"e": 26771,
"s": 26743,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 26911,
"s": 26771,
"text": "Write a program to find the sum of fourth powers of the first n natural numbers 14 + 24 + 34 + 44 + .......+ n4 till n-th term.Examples : "
},
{
"code": null,
"e": 27018,
"s": 26911,
"text": "Input : 4\nOutput : 354\n14 + 24 + 34 + 44 = 354\n\nInput : 6\nOutput : 2275\n14 + 24 + 34 + 44+ 54+ 64 = 2275"
},
{
"code": null,
"e": 27204,
"s": 27020,
"text": "Naive Approach :- Simple finding the fourth powers of the first n natural numbers is iterate a loop from 1 to n time. like suppose n=4. (1*1*1*1)+(2*2*2*2)+(3*3*3*3)+(4*4*4*4) = 354 "
},
{
"code": null,
"e": 27208,
"s": 27204,
"text": "C++"
},
{
"code": null,
"e": 27213,
"s": 27208,
"text": "Java"
},
{
"code": null,
"e": 27221,
"s": 27213,
"text": "Python3"
},
{
"code": null,
"e": 27224,
"s": 27221,
"text": "C#"
},
{
"code": null,
"e": 27228,
"s": 27224,
"text": "PHP"
},
{
"code": null,
"e": 27239,
"s": 27228,
"text": "Javascript"
},
{
"code": "// CPP Program to find the sum of forth powers// of first n natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of forth power of first n// natural numberslong long int fourthPowerSum(int n){ long long int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum;} // Driven Programint main(){ int n = 6; cout << fourthPowerSum(n) << endl; return 0;}",
"e": 27662,
"s": 27239,
"text": null
},
{
"code": "// Java Program to find the// sum of forth powers of// first n natural numbersimport java.io.*;import java.util.*; class GFG { // Return the sum of forth // power of first n natural // numbers static long fourthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum; } public static void main (String[] args) { int n = 6; System.out.println(fourthPowerSum(n)); }} // This code is contributed by Gitanjali.",
"e": 28220,
"s": 27662,
"text": null
},
{
"code": "# Python3 Program to find the# sum of forth powers of first# n natural numbersimport math # Return the sum of forth power of# first n natural numbersdef fourthPowerSum( n): sum = 0 for i in range(1, n+1) : sum = sum + (i * i * i * i) return sum# Driver methodn=6print (fourthPowerSum(n)) # This code is contributed by Gitanjali.",
"e": 28566,
"s": 28220,
"text": null
},
{
"code": "// C# program to find the// sum of forth powers of// first n natural numbersusing System; class GFG { // Return the sum of forth power // of first n natural numbers static long fourthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum; } public static void Main () { int n = 6; Console.WriteLine(fourthPowerSum(n)); }} // This code is contributed by vt_m.",
"e": 29074,
"s": 28566,
"text": null
},
{
"code": "<?php// PHP Program to find th// sum of fourth powers// of first n natural numbers // Return the sum of fourth// power of first n// natural numbersfunction fourthPowerSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + ($i * $i * $i * $i); return $sum;} // Driver Code$n = 6;echo(fourthPowerSum($n)); // This code is contributed by Ajit.?>",
"e": 29440,
"s": 29074,
"text": null
},
{
"code": "<script> // javascript Program to find the sum of forth powers// of first n natural numbers // Return the sum of forth power of first n// natural numbersfunction fourthPowerSum( n){ let sum = 0; for (let i = 1; i <= n; i++) sum = sum + (i * i * i * i); return sum;}// Driven Program let n = 6; document.write(fourthPowerSum(n)); // This code contributed by aashish1995 </script>",
"e": 29843,
"s": 29440,
"text": null
},
{
"code": null,
"e": 29851,
"s": 29843,
"text": "Output:"
},
{
"code": null,
"e": 29856,
"s": 29851,
"text": "2275"
},
{
"code": null,
"e": 30087,
"s": 29856,
"text": "Time Complexity : O(n)Efficient Approach :- An efficient solution is to use direct mathematical formula which is 1/30n(n+1)(2n+1)(3n2+3n+1) or it is also write (1/5)n5 + (1/2)n4 + (1/3)n3 – (1/30)n. This solution take O(1) time. "
},
{
"code": null,
"e": 30091,
"s": 30087,
"text": "C++"
},
{
"code": null,
"e": 30096,
"s": 30091,
"text": "Java"
},
{
"code": null,
"e": 30104,
"s": 30096,
"text": "Python3"
},
{
"code": null,
"e": 30107,
"s": 30104,
"text": "C#"
},
{
"code": null,
"e": 30111,
"s": 30107,
"text": "PHP"
},
{
"code": null,
"e": 30122,
"s": 30111,
"text": "Javascript"
},
{
"code": "// CPP Program to find the sum of forth power of first// n natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of forth power of first n natural// numberslong long int fourthPowerSum(int n){ return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30;} // Driven Programint main(){ int n = 6; cout << fourthPowerSum(n) << endl; return 0;}",
"e": 30545,
"s": 30122,
"text": null
},
{
"code": "// Java Program to find the// sum of forth powers of// first n natural numbersimport java.io.*;import java.util.*; class GFG { // Return the sum of // forth power of first // n natural numbers static long fourthPowerSum(int n) { return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30; } public static void main (String[] args) { int n = 6; System.out.println(fourthPowerSum(n)); }} // This code is contributed by Gitanjali.",
"e": 31100,
"s": 30545,
"text": null
},
{
"code": "# Python3 Program to# find the sum of# forth powers of# first n natural numbersimport math # Return the sum of# forth power of# first n natural# numbersdef fourthPowerSum(n): return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30 # Driver methodn=6print (fourthPowerSum(n)) # This code is contributed by Gitanjali.",
"e": 31474,
"s": 31100,
"text": null
},
{
"code": "// C# Program to find the// sum of forth powers of// first n natural numbersusing System; class GFG { // Return the sum of // forth power of first // n natural numbers static long fourthPowerSum(int n) { return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30; } public static void Main () { int n = 6; Console.Write(fourthPowerSum(n)); }} // This code is contributed by vt_m.",
"e": 31981,
"s": 31474,
"text": null
},
{
"code": "<?php// PHP Program to find the sum// of fourth power of first// n natural numbers // Return the sum of fourth// power of first n natural// numbersfunction fourthPowerSum($n){ return ((6 * $n * $n * $n * $n * $n) + (15 * $n * $n * $n * $n) + (10 * $n * $n * $n) - $n) / 30;} // Driver Code$n = 6;echo(fourthPowerSum($n)); // This code is contributed by Ajit.?>",
"e": 32367,
"s": 31981,
"text": null
},
{
"code": "<script> // javascript Program to find the// sum of forth powers of// first n natural numbers // Return the sum of// forth power of first// n natural numbersfunction fourthPowerSum(n){ return ((6 * n * n * n * n * n) + (15 * n * n * n * n) + (10 * n * n * n) - n) / 30;} var n = 6; document.write(fourthPowerSum(n)); // This code is contributed by 29AjayKumar </script>",
"e": 32766,
"s": 32367,
"text": null
},
{
"code": null,
"e": 32775,
"s": 32766,
"text": "Output: "
},
{
"code": null,
"e": 32780,
"s": 32775,
"text": "2275"
},
{
"code": null,
"e": 32804,
"s": 32780,
"text": "Time Complexity : O(1) "
},
{
"code": null,
"e": 32810,
"s": 32804,
"text": "jit_t"
},
{
"code": null,
"e": 32822,
"s": 32810,
"text": "aashish1995"
},
{
"code": null,
"e": 32834,
"s": 32822,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32848,
"s": 32834,
"text": "number-theory"
},
{
"code": null,
"e": 32855,
"s": 32848,
"text": "series"
},
{
"code": null,
"e": 32866,
"s": 32855,
"text": "series-sum"
},
{
"code": null,
"e": 32879,
"s": 32866,
"text": "Mathematical"
},
{
"code": null,
"e": 32893,
"s": 32879,
"text": "number-theory"
},
{
"code": null,
"e": 32906,
"s": 32893,
"text": "Mathematical"
},
{
"code": null,
"e": 32913,
"s": 32906,
"text": "series"
},
{
"code": null,
"e": 33011,
"s": 32913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33035,
"s": 33011,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33078,
"s": 33035,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33092,
"s": 33078,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33134,
"s": 33092,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 33156,
"s": 33134,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 33229,
"s": 33156,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 33270,
"s": 33229,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 33313,
"s": 33270,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 33334,
"s": 33313,
"text": "Operators in C / C++"
}
] |
C Program for Naive algorithm for Pattern Searching - GeeksforGeeks
|
11 Dec, 2018
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Input: txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.
C
// C program for Naive Pattern Searching algorithm#include <stdio.h>#include <string.h> void search(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { int j; /* For current index i, check for pattern match */ for (j = 0; j < M; j++) if (txt[i + j] != pat[j]) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] printf("Pattern found at index %d \n", i); }} /* Driver program to test above function */int main(){ char txt[] = "AABAACAADAABAAABAA"; char pat[] = "AABA"; search(pat, txt); return 0;}
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13
Please refer complete article on Naive algorithm for Pattern Searching for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
C program to sort an array in ascending order
time() function in C
C Program to Swap two Numbers
Producer Consumer Problem in C
Program to find Prime Numbers Between given Interval
|
[
{
"code": null,
"e": 25839,
"s": 25811,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 26013,
"s": 25839,
"text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m."
},
{
"code": null,
"e": 26023,
"s": 26013,
"text": "Examples:"
},
{
"code": null,
"e": 26281,
"s": 26023,
"text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12\n\n"
},
{
"code": null,
"e": 26486,
"s": 26281,
"text": "Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results."
},
{
"code": null,
"e": 26488,
"s": 26486,
"text": "C"
},
{
"code": "// C program for Naive Pattern Searching algorithm#include <stdio.h>#include <string.h> void search(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { int j; /* For current index i, check for pattern match */ for (j = 0; j < M; j++) if (txt[i + j] != pat[j]) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] printf(\"Pattern found at index %d \\n\", i); }} /* Driver program to test above function */int main(){ char txt[] = \"AABAACAADAABAAABAA\"; char pat[] = \"AABA\"; search(pat, txt); return 0;}",
"e": 27183,
"s": 26488,
"text": null
},
{
"code": null,
"e": 27262,
"s": 27183,
"text": "Pattern found at index 0 \nPattern found at index 9 \nPattern found at index 13\n"
},
{
"code": null,
"e": 27351,
"s": 27262,
"text": "Please refer complete article on Naive algorithm for Pattern Searching for more details!"
},
{
"code": null,
"e": 27362,
"s": 27351,
"text": "C Programs"
},
{
"code": null,
"e": 27460,
"s": 27362,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27501,
"s": 27460,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27536,
"s": 27501,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27580,
"s": 27536,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 27639,
"s": 27580,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27682,
"s": 27639,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 27728,
"s": 27682,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 27749,
"s": 27728,
"text": "time() function in C"
},
{
"code": null,
"e": 27779,
"s": 27749,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 27810,
"s": 27779,
"text": "Producer Consumer Problem in C"
}
] |
R - Check if a Directory Exists and Create if It does not - GeeksforGeeks
|
30 Apr, 2021
Directories and sub-directories are accessed by their corresponding paths in R Programming Language. It is easy to work with these in R and perform operations related to the creation, copy, and movement of folders and sub-folders within the system. In this article, we will see how to check if a directory exists and how to create a new directory if it does not exist using R Programming Language.
Directory in use:
The path corresponding to the main directory can be first stored in the working space. We can check if this directory exists, using the file.exists() method. This method returns a logical vector depicting whether the files specified by its argument exist in the space or not. If the file exists, it returns TRUE, otherwise FALSE is returned.
Syntax: dir.exists(paths)
Parameter:
path – a character vector containing a single path name.
Example:
R
sub_dir<-"test1" file.exists(sub_dir)
Output:
TRUE
If the file exists the working directory is set to the path formed by the concatenation of the main and subdirectories respectively. Otherwise, the directory is created using the dir.create() method. This method returns a logical vector describing if the creation of the file succeeded for each of the files for which it was attempted. dir.create indicates failure if the directory already exists.
Syntax: dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = “0777”)
Parameter :
path – a character vector containing a single path name.
showWarnings – logical; should the warnings on failure be shown?
mode – the mode to be used on Unix-alikes.
Example:
R
# setting up the main directorymain_dir <- "C:\\Users\\Vanshi\\Desktop\\gfg\\test" # setting up the sub directorysub_dir <- "abc" # check if sub directory exists if (file.exists(sub_dir)){ # specifying the working directory setwd(file.path(main_dir, sub_dir))} else { # create a new sub directory inside # the main path dir.create(file.path(main_dir, sub_dir)) # specifying the working directory setwd(file.path(main_dir, sub_dir))}
Output:
Picked
R-FileHandling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Creating a Data Frame from Vectors in R Programming
|
[
{
"code": null,
"e": 25883,
"s": 25855,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 26281,
"s": 25883,
"text": "Directories and sub-directories are accessed by their corresponding paths in R Programming Language. It is easy to work with these in R and perform operations related to the creation, copy, and movement of folders and sub-folders within the system. In this article, we will see how to check if a directory exists and how to create a new directory if it does not exist using R Programming Language."
},
{
"code": null,
"e": 26299,
"s": 26281,
"text": "Directory in use:"
},
{
"code": null,
"e": 26642,
"s": 26299,
"text": "The path corresponding to the main directory can be first stored in the working space. We can check if this directory exists, using the file.exists() method. This method returns a logical vector depicting whether the files specified by its argument exist in the space or not. If the file exists, it returns TRUE, otherwise FALSE is returned. "
},
{
"code": null,
"e": 26668,
"s": 26642,
"text": "Syntax: dir.exists(paths)"
},
{
"code": null,
"e": 26679,
"s": 26668,
"text": "Parameter:"
},
{
"code": null,
"e": 26736,
"s": 26679,
"text": "path – a character vector containing a single path name."
},
{
"code": null,
"e": 26745,
"s": 26736,
"text": "Example:"
},
{
"code": null,
"e": 26747,
"s": 26745,
"text": "R"
},
{
"code": "sub_dir<-\"test1\" file.exists(sub_dir)",
"e": 26786,
"s": 26747,
"text": null
},
{
"code": null,
"e": 26794,
"s": 26786,
"text": "Output:"
},
{
"code": null,
"e": 26799,
"s": 26794,
"text": "TRUE"
},
{
"code": null,
"e": 27198,
"s": 26799,
"text": "If the file exists the working directory is set to the path formed by the concatenation of the main and subdirectories respectively. Otherwise, the directory is created using the dir.create() method. This method returns a logical vector describing if the creation of the file succeeded for each of the files for which it was attempted. dir.create indicates failure if the directory already exists."
},
{
"code": null,
"e": 27278,
"s": 27198,
"text": "Syntax: dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = “0777”)"
},
{
"code": null,
"e": 27291,
"s": 27278,
"text": "Parameter : "
},
{
"code": null,
"e": 27348,
"s": 27291,
"text": "path – a character vector containing a single path name."
},
{
"code": null,
"e": 27413,
"s": 27348,
"text": "showWarnings – logical; should the warnings on failure be shown?"
},
{
"code": null,
"e": 27456,
"s": 27413,
"text": "mode – the mode to be used on Unix-alikes."
},
{
"code": null,
"e": 27465,
"s": 27456,
"text": "Example:"
},
{
"code": null,
"e": 27467,
"s": 27465,
"text": "R"
},
{
"code": "# setting up the main directorymain_dir <- \"C:\\\\Users\\\\Vanshi\\\\Desktop\\\\gfg\\\\test\" # setting up the sub directorysub_dir <- \"abc\" # check if sub directory exists if (file.exists(sub_dir)){ # specifying the working directory setwd(file.path(main_dir, sub_dir))} else { # create a new sub directory inside # the main path dir.create(file.path(main_dir, sub_dir)) # specifying the working directory setwd(file.path(main_dir, sub_dir))}",
"e": 27981,
"s": 27467,
"text": null
},
{
"code": null,
"e": 27989,
"s": 27981,
"text": "Output:"
},
{
"code": null,
"e": 27996,
"s": 27989,
"text": "Picked"
},
{
"code": null,
"e": 28011,
"s": 27996,
"text": "R-FileHandling"
},
{
"code": null,
"e": 28022,
"s": 28011,
"text": "R Language"
},
{
"code": null,
"e": 28120,
"s": 28022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28178,
"s": 28120,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28230,
"s": 28178,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 28262,
"s": 28230,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 28306,
"s": 28262,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28358,
"s": 28306,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28393,
"s": 28358,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28431,
"s": 28393,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28489,
"s": 28431,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28525,
"s": 28489,
"text": "K-Means Clustering in R Programming"
}
] |
Matplotlib.axes.Axes.get_xscale() in Python - GeeksforGeeks
|
19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.get_xscale() function in axes module of matplotlib library is used to return the x-axis scale as string.
Syntax: Axes.get_xscale(self)
Parameters: This method does not accepts any parameters.
Return: This function return the x-axis scale as a string.
Below examples illustrate the matplotlib.axes.Axes.set_yscale() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots() ax.plot([1, 2, 3]) w = ax.get_xscale() ax.set_title("xscale property : "+ str(w), fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_xscale()\ function Example\n', fontweight ="bold") fig.canvas.draw()plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.ticker import EngFormatter val = np.random.RandomState(19680801)xs = np.logspace(1, 9, 100)ys = (0.8 + 4 * val.uniform(size = 100)) * np.log10(xs)**2 fig, ax0 = plt.subplots()ax0.set_xscale('log')formatter0 = EngFormatter(unit ='Hz')ax0.xaxis.set_major_formatter(formatter0)ax0.plot(xs, ys)ax0.set_xlabel('Frequency') w = ax0.get_xscale() ax0.set_title("xscale property : "+ str(w), fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_xscale()\ function Example\n', fontweight ="bold") fig.canvas.draw()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 25837,
"s": 25537,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 25951,
"s": 25837,
"text": "The Axes.get_xscale() function in axes module of matplotlib library is used to return the x-axis scale as string."
},
{
"code": null,
"e": 25981,
"s": 25951,
"text": "Syntax: Axes.get_xscale(self)"
},
{
"code": null,
"e": 26038,
"s": 25981,
"text": "Parameters: This method does not accepts any parameters."
},
{
"code": null,
"e": 26097,
"s": 26038,
"text": "Return: This function return the x-axis scale as a string."
},
{
"code": null,
"e": 26190,
"s": 26097,
"text": "Below examples illustrate the matplotlib.axes.Axes.set_yscale() function in matplotlib.axes:"
},
{
"code": null,
"e": 26201,
"s": 26190,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots() ax.plot([1, 2, 3]) w = ax.get_xscale() ax.set_title(\"xscale property : \"+ str(w), fontweight =\"bold\")fig.suptitle('matplotlib.axes.Axes.get_xscale()\\ function Example\\n', fontweight =\"bold\") fig.canvas.draw()plt.show()",
"e": 26559,
"s": 26201,
"text": null
},
{
"code": null,
"e": 26567,
"s": 26559,
"text": "Output:"
},
{
"code": null,
"e": 26578,
"s": 26567,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.ticker import EngFormatter val = np.random.RandomState(19680801)xs = np.logspace(1, 9, 100)ys = (0.8 + 4 * val.uniform(size = 100)) * np.log10(xs)**2 fig, ax0 = plt.subplots()ax0.set_xscale('log')formatter0 = EngFormatter(unit ='Hz')ax0.xaxis.set_major_formatter(formatter0)ax0.plot(xs, ys)ax0.set_xlabel('Frequency') w = ax0.get_xscale() ax0.set_title(\"xscale property : \"+ str(w), fontweight =\"bold\")fig.suptitle('matplotlib.axes.Axes.get_xscale()\\ function Example\\n', fontweight =\"bold\") fig.canvas.draw()plt.show()",
"e": 27223,
"s": 26578,
"text": null
},
{
"code": null,
"e": 27231,
"s": 27223,
"text": "Output:"
},
{
"code": null,
"e": 27249,
"s": 27231,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27256,
"s": 27249,
"text": "Python"
},
{
"code": null,
"e": 27354,
"s": 27256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27386,
"s": 27354,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27428,
"s": 27386,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27470,
"s": 27428,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27497,
"s": 27470,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27553,
"s": 27497,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27592,
"s": 27553,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27614,
"s": 27592,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27645,
"s": 27614,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27674,
"s": 27645,
"text": "Create a directory in Python"
}
] |
Implementing PCA in Python with scikit-learn - GeeksforGeeks
|
23 Sep, 2021
In this article, we will learn about PCA (Principal Component Analysis) in Python with scikit-learn. Let’s start our learning step by step.
WHY PCA?
When there are many input attributes, it is difficult to visualize the data. There is a very famous term ‘Curse of dimensionality in the machine learning domain.
Basically, it refers to the fact that a higher number of attributes in a dataset adversely affects the accuracy and training time of the machine learning model.
Principal Component Analysis (PCA) is a way to address this issue and is used for better data visualization and improving accuracy.
How does PCA work?
PCA is an unsupervised pre-processing task that is carried out before applying any ML algorithm. PCA is based on “orthogonal linear transformation” which is a mathematical technique to project the attributes of a data set onto a new coordinate system. The attribute which describes the most variance is called the first principal component and is placed at the first coordinate.
Similarly, the attribute which stands second in describing variance is called a second principal component and so on. In short, the complete dataset can be expressed in terms of principal components. Usually, more than 90% of the variance is explained by two/three principal components.
Principal component analysis, or PCA, thus converts data from high dimensional space to low dimensional space by selecting the most important attributes that capture maximum information about the dataset.
Python Implementation:
To implement PCA in Scikit learn, it is essential to standardize/normalize the data before applying PCA.
PCA is imported from sklearn.decomposition. We need to select the required number of principal components.
Usually, n_components is chosen to be 2 for better visualization but it matters and depends on data.
By the fit and transform method, the attributes are passed.
The values of principal components can be checked using components_ while the variance explained by each principal component can be calculated using explained_variance_ratio.
1. Import all the libraries
Python3
# import all librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.decomposition import PCAfrom sklearn.preprocessing import StandardScaler
2. Loading Data
Load the breast_cancer dataset from sklearn.datasets. It is clear that the dataset has 569 data items with 30 input attributes. There are two output classes-benign and malignant. Due to 30 input features, it is impossible to visualize this data
Python3
#import the breast _cancer datasetfrom sklearn.datasets import load_breast_cancerdata=load_breast_cancer()data.keys() # Check the output classesprint(data['target_names']) # Check the input attributesprint(data['feature_names'])
Output:
3. Apply PCA
Standardize the dataset prior to PCA.
Import PCA from sklearn.decomposition.
Choose the number of principal components.
Let us select it to 3. After executing this code, we get to know that the dimensions of x are (569,3) while the dimension of actual data is (569,30). Thus, it is clear that with PCA, the number of dimensions has reduced to 3 from 30. If we choose n_components=2, the dimensions would be reduced to 2.
Python3
# construct a dataframe using pandasdf1=pd.DataFrame(data['data'],columns=data['feature_names']) # Scale data before applying PCAscaling=StandardScaler() # Use fit and transform methodscaling.fit(df1)Scaled_data=scaling.transform(df1) # Set the n_components=3principal=PCA(n_components=3)principal.fit(Scaled_data)x=principal.transform(Scaled_data) # Check the dimensions of data after PCAprint(x.shape)
Output:
(569,3)
4. Check Components
The principal.components_ provide an array in which the number of rows tells the number of principal components while the number of columns is equal to the number of features in actual data. We can easily see that there are three rows as n_components was chosen to be 3. However, each row has 30 columns as in actual data.
Python3
# Check the values of eigen vectors# prodeced by principal componentsprincipal.components_
5. Plot the components (Visualization)
Plot the principal components for better data visualization. Though we had taken n_components =3, here we are plotting a 2d graph as well as 3d using first two principal components and 3 principal components respectively. For three principal components, we need to plot a 3d graph. The colors show the 2 output classes of the original dataset-benign and malignant. It is clear that principal components show clear separation between two output classes.
Python3
plt.figure(figsize=(10,10))plt.scatter(x[:,0],x[:,1],c=data['target'],cmap='plasma')plt.xlabel('pc1')plt.ylabel('pc2')
Output:
For three principal components, we need to plot a 3d graph. x[:,0] signifies the first principal component. Similarly, x[:,1] and x[:,2] represent the second and the third principal component.
Python3
# import relevant libraries for 3d graphfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(10,10)) # choose projection 3d for creating a 3d graphaxis = fig.add_subplot(111, projection='3d') # x[:,0]is pc1,x[:,1] is pc2 while x[:,2] is pc3axis.scatter(x[:,0],x[:,1],x[:,2], c=data['target'],cmap='plasma')axis.set_xlabel("PC1", fontsize=10)axis.set_ylabel("PC2", fontsize=10)axis.set_zlabel("PC3", fontsize=10)
Output:
6. Calculate variance ratio
Explained_variance_ratio provides an idea of how much variation is explained by principal components.
Python3
# check how much variance is explained by each principal componentprint(principal.explained_variance_ratio_)
Output:
array([0.44272026, 0.18971182, 0.09393163])
anikakapoor
sweetyty
Picked
Technical Scripter 2020
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25615,
"s": 25587,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 25755,
"s": 25615,
"text": "In this article, we will learn about PCA (Principal Component Analysis) in Python with scikit-learn. Let’s start our learning step by step."
},
{
"code": null,
"e": 25764,
"s": 25755,
"text": "WHY PCA?"
},
{
"code": null,
"e": 25926,
"s": 25764,
"text": "When there are many input attributes, it is difficult to visualize the data. There is a very famous term ‘Curse of dimensionality in the machine learning domain."
},
{
"code": null,
"e": 26087,
"s": 25926,
"text": "Basically, it refers to the fact that a higher number of attributes in a dataset adversely affects the accuracy and training time of the machine learning model."
},
{
"code": null,
"e": 26219,
"s": 26087,
"text": "Principal Component Analysis (PCA) is a way to address this issue and is used for better data visualization and improving accuracy."
},
{
"code": null,
"e": 26238,
"s": 26219,
"text": "How does PCA work?"
},
{
"code": null,
"e": 26617,
"s": 26238,
"text": "PCA is an unsupervised pre-processing task that is carried out before applying any ML algorithm. PCA is based on “orthogonal linear transformation” which is a mathematical technique to project the attributes of a data set onto a new coordinate system. The attribute which describes the most variance is called the first principal component and is placed at the first coordinate."
},
{
"code": null,
"e": 26904,
"s": 26617,
"text": "Similarly, the attribute which stands second in describing variance is called a second principal component and so on. In short, the complete dataset can be expressed in terms of principal components. Usually, more than 90% of the variance is explained by two/three principal components."
},
{
"code": null,
"e": 27109,
"s": 26904,
"text": "Principal component analysis, or PCA, thus converts data from high dimensional space to low dimensional space by selecting the most important attributes that capture maximum information about the dataset."
},
{
"code": null,
"e": 27132,
"s": 27109,
"text": "Python Implementation:"
},
{
"code": null,
"e": 27237,
"s": 27132,
"text": "To implement PCA in Scikit learn, it is essential to standardize/normalize the data before applying PCA."
},
{
"code": null,
"e": 27344,
"s": 27237,
"text": "PCA is imported from sklearn.decomposition. We need to select the required number of principal components."
},
{
"code": null,
"e": 27445,
"s": 27344,
"text": "Usually, n_components is chosen to be 2 for better visualization but it matters and depends on data."
},
{
"code": null,
"e": 27505,
"s": 27445,
"text": "By the fit and transform method, the attributes are passed."
},
{
"code": null,
"e": 27680,
"s": 27505,
"text": "The values of principal components can be checked using components_ while the variance explained by each principal component can be calculated using explained_variance_ratio."
},
{
"code": null,
"e": 27708,
"s": 27680,
"text": "1. Import all the libraries"
},
{
"code": null,
"e": 27716,
"s": 27708,
"text": "Python3"
},
{
"code": "# import all librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.decomposition import PCAfrom sklearn.preprocessing import StandardScaler",
"e": 27910,
"s": 27716,
"text": null
},
{
"code": null,
"e": 27926,
"s": 27910,
"text": "2. Loading Data"
},
{
"code": null,
"e": 28171,
"s": 27926,
"text": "Load the breast_cancer dataset from sklearn.datasets. It is clear that the dataset has 569 data items with 30 input attributes. There are two output classes-benign and malignant. Due to 30 input features, it is impossible to visualize this data"
},
{
"code": null,
"e": 28179,
"s": 28171,
"text": "Python3"
},
{
"code": "#import the breast _cancer datasetfrom sklearn.datasets import load_breast_cancerdata=load_breast_cancer()data.keys() # Check the output classesprint(data['target_names']) # Check the input attributesprint(data['feature_names'])",
"e": 28408,
"s": 28179,
"text": null
},
{
"code": null,
"e": 28416,
"s": 28408,
"text": "Output:"
},
{
"code": null,
"e": 28430,
"s": 28416,
"text": "3. Apply PCA "
},
{
"code": null,
"e": 28468,
"s": 28430,
"text": "Standardize the dataset prior to PCA."
},
{
"code": null,
"e": 28507,
"s": 28468,
"text": "Import PCA from sklearn.decomposition."
},
{
"code": null,
"e": 28550,
"s": 28507,
"text": "Choose the number of principal components."
},
{
"code": null,
"e": 28851,
"s": 28550,
"text": "Let us select it to 3. After executing this code, we get to know that the dimensions of x are (569,3) while the dimension of actual data is (569,30). Thus, it is clear that with PCA, the number of dimensions has reduced to 3 from 30. If we choose n_components=2, the dimensions would be reduced to 2."
},
{
"code": null,
"e": 28859,
"s": 28851,
"text": "Python3"
},
{
"code": "# construct a dataframe using pandasdf1=pd.DataFrame(data['data'],columns=data['feature_names']) # Scale data before applying PCAscaling=StandardScaler() # Use fit and transform methodscaling.fit(df1)Scaled_data=scaling.transform(df1) # Set the n_components=3principal=PCA(n_components=3)principal.fit(Scaled_data)x=principal.transform(Scaled_data) # Check the dimensions of data after PCAprint(x.shape)",
"e": 29263,
"s": 28859,
"text": null
},
{
"code": null,
"e": 29271,
"s": 29263,
"text": "Output:"
},
{
"code": null,
"e": 29279,
"s": 29271,
"text": "(569,3)"
},
{
"code": null,
"e": 29299,
"s": 29279,
"text": "4. Check Components"
},
{
"code": null,
"e": 29623,
"s": 29299,
"text": "The principal.components_ provide an array in which the number of rows tells the number of principal components while the number of columns is equal to the number of features in actual data. We can easily see that there are three rows as n_components was chosen to be 3. However, each row has 30 columns as in actual data."
},
{
"code": null,
"e": 29631,
"s": 29623,
"text": "Python3"
},
{
"code": "# Check the values of eigen vectors# prodeced by principal componentsprincipal.components_",
"e": 29722,
"s": 29631,
"text": null
},
{
"code": null,
"e": 29762,
"s": 29722,
"text": "5. Plot the components (Visualization) "
},
{
"code": null,
"e": 30217,
"s": 29762,
"text": "Plot the principal components for better data visualization. Though we had taken n_components =3, here we are plotting a 2d graph as well as 3d using first two principal components and 3 principal components respectively. For three principal components, we need to plot a 3d graph. The colors show the 2 output classes of the original dataset-benign and malignant. It is clear that principal components show clear separation between two output classes. "
},
{
"code": null,
"e": 30225,
"s": 30217,
"text": "Python3"
},
{
"code": "plt.figure(figsize=(10,10))plt.scatter(x[:,0],x[:,1],c=data['target'],cmap='plasma')plt.xlabel('pc1')plt.ylabel('pc2')",
"e": 30344,
"s": 30225,
"text": null
},
{
"code": null,
"e": 30352,
"s": 30344,
"text": "Output:"
},
{
"code": null,
"e": 30545,
"s": 30352,
"text": "For three principal components, we need to plot a 3d graph. x[:,0] signifies the first principal component. Similarly, x[:,1] and x[:,2] represent the second and the third principal component."
},
{
"code": null,
"e": 30553,
"s": 30545,
"text": "Python3"
},
{
"code": "# import relevant libraries for 3d graphfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(10,10)) # choose projection 3d for creating a 3d graphaxis = fig.add_subplot(111, projection='3d') # x[:,0]is pc1,x[:,1] is pc2 while x[:,2] is pc3axis.scatter(x[:,0],x[:,1],x[:,2], c=data['target'],cmap='plasma')axis.set_xlabel(\"PC1\", fontsize=10)axis.set_ylabel(\"PC2\", fontsize=10)axis.set_zlabel(\"PC3\", fontsize=10)",
"e": 30977,
"s": 30553,
"text": null
},
{
"code": null,
"e": 30985,
"s": 30977,
"text": "Output:"
},
{
"code": null,
"e": 31013,
"s": 30985,
"text": "6. Calculate variance ratio"
},
{
"code": null,
"e": 31116,
"s": 31013,
"text": "Explained_variance_ratio provides an idea of how much variation is explained by principal components. "
},
{
"code": null,
"e": 31124,
"s": 31116,
"text": "Python3"
},
{
"code": "# check how much variance is explained by each principal componentprint(principal.explained_variance_ratio_)",
"e": 31233,
"s": 31124,
"text": null
},
{
"code": null,
"e": 31241,
"s": 31233,
"text": "Output:"
},
{
"code": null,
"e": 31285,
"s": 31241,
"text": "array([0.44272026, 0.18971182, 0.09393163])"
},
{
"code": null,
"e": 31299,
"s": 31287,
"text": "anikakapoor"
},
{
"code": null,
"e": 31308,
"s": 31299,
"text": "sweetyty"
},
{
"code": null,
"e": 31315,
"s": 31308,
"text": "Picked"
},
{
"code": null,
"e": 31339,
"s": 31315,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31356,
"s": 31339,
"text": "Machine Learning"
},
{
"code": null,
"e": 31363,
"s": 31356,
"text": "Python"
},
{
"code": null,
"e": 31382,
"s": 31363,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31399,
"s": 31382,
"text": "Machine Learning"
},
{
"code": null,
"e": 31497,
"s": 31399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31538,
"s": 31497,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 31571,
"s": 31538,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 31599,
"s": 31571,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 31635,
"s": 31599,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 31690,
"s": 31635,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 31718,
"s": 31690,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 31768,
"s": 31718,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 31790,
"s": 31768,
"text": "Python map() function"
}
] |
How to Check if the Battery is Charging or Not in Android Programmatically? - GeeksforGeeks
|
23 Feb, 2021
The charging status can change as quickly as a device can be plugged in, so it’s crucial to monitor the charging state for changes and alter your refresh rate accordingly. The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It is important to receive these events even while the app isn’t running significantly. Such events should impact how often you start the app to initiate a background update. So you should register a BroadcastReceiver in the manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter (filter). A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Keep an eye on the battery status in the status bar.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file, which represents the UI of the project. Add a Button, so whenever the user will click on the Button a Toast message with battery state (charging or not) will be popped up on the screen. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Click" /> </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Finally, go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intentimport android.content.IntentFilterimport android.os.BatteryManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Button onclick will display the status of charging val btn = findViewById<Button>(R.id.btn) btn.setOnClickListener { // Intent to check the actions on battery val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter -> applicationContext.registerReceiver(null, ifilter) } // isCharging if true indicates charging is ongoing and vice-versa val status: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1 val isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL // Display whatever the state in the form of a Toast if(isCharging) { Toast.makeText(applicationContext, "Charging", Toast.LENGTH_LONG).show() } else { Toast.makeText(applicationContext,"Not Charging", Toast.LENGTH_LONG).show() } } }}
Keep an eye on the battery status in the status bar.
Android-Misc
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 27236,
"s": 26381,
"text": "The charging status can change as quickly as a device can be plugged in, so it’s crucial to monitor the charging state for changes and alter your refresh rate accordingly. The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It is important to receive these events even while the app isn’t running significantly. Such events should impact how often you start the app to initiate a background update. So you should register a BroadcastReceiver in the manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter (filter). A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Keep an eye on the battery status in the status bar."
},
{
"code": null,
"e": 27265,
"s": 27236,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27429,
"s": 27265,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 27477,
"s": 27429,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27747,
"s": 27477,
"text": "Go to the activity_main.xml file, which represents the UI of the project. Add a Button, so whenever the user will click on the Button a Toast message with battery state (charging or not) will be popped up on the screen. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 27751,
"s": 27747,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\"> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Click\" /> </RelativeLayout>",
"e": 28316,
"s": 27751,
"text": null
},
{
"code": null,
"e": 28362,
"s": 28316,
"text": "Step 3: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 28555,
"s": 28362,
"text": "Finally, go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 28562,
"s": 28555,
"text": "Kotlin"
},
{
"code": "import android.content.Intentimport android.content.IntentFilterimport android.os.BatteryManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Button onclick will display the status of charging val btn = findViewById<Button>(R.id.btn) btn.setOnClickListener { // Intent to check the actions on battery val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter -> applicationContext.registerReceiver(null, ifilter) } // isCharging if true indicates charging is ongoing and vice-versa val status: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1 val isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL // Display whatever the state in the form of a Toast if(isCharging) { Toast.makeText(applicationContext, \"Charging\", Toast.LENGTH_LONG).show() } else { Toast.makeText(applicationContext,\"Not Charging\", Toast.LENGTH_LONG).show() } } }}",
"e": 30014,
"s": 28562,
"text": null
},
{
"code": null,
"e": 30067,
"s": 30014,
"text": "Keep an eye on the battery status in the status bar."
},
{
"code": null,
"e": 30080,
"s": 30067,
"text": "Android-Misc"
},
{
"code": null,
"e": 30088,
"s": 30080,
"text": "Android"
},
{
"code": null,
"e": 30095,
"s": 30088,
"text": "Kotlin"
},
{
"code": null,
"e": 30103,
"s": 30095,
"text": "Android"
},
{
"code": null,
"e": 30201,
"s": 30103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30239,
"s": 30201,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 30278,
"s": 30239,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30328,
"s": 30278,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 30370,
"s": 30328,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30421,
"s": 30370,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 30440,
"s": 30421,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 30453,
"s": 30440,
"text": "Kotlin Array"
},
{
"code": null,
"e": 30495,
"s": 30453,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30535,
"s": 30495,
"text": "How to Get Current Location in Android?"
}
] |
PHP | Reverse a String
|
31 Dec, 2017
PHP serves us with many built-in methods which can be used to manipulate strings. In this article, we will learn about how to reverse a string using various methods available in PHP.
Examples:
Input : GeeksforGeeks
Output : skeeGrofskeeG
Input : 12485
Output : 58421
Below we have discussed about three basic and most commonly used methods of reversing strings in PHP:
Reversing string using strrev(): The strrev() function is a built-in function available in PHP and is used to reverse strings. This function takes a string as argument and returns a reversed string.Syntax:strrev($string)Below is the implementation of program to reverse a string using strrev():<?php// PHP program to reverse a string using strrev() function Reverse($str){ return strrev($str);} // Driver Code$str = "GeeksforGeeks";echo Reverse($str)?>Output:skeeGrofskeeG
Reversing string using recursion and substr(): We can also reverse a string using recursion and substr() function. The substr() function is used to get a substring of the original string. Here we have defined a function Reverse() with the string passed as argument. During every recursive call, we have used the substr() method to extract the first character of argument string and called the Reverse() function again by passing remaining part of string as argument and concatenated the first character at the end of the string returned from current call.Below is the implementation of above idea:<?php // PHP function to reverse a string using // recursion and substr()function Reverse($str){ // strlen() used to calculate the // length of the string $len = strlen($str); // Base case for recursion if($len == 1){ return $str; } else{ $len--; // extract first character and concatenate // at end of string returned from recursive // call on remaining string return Reverse(substr($str,1, $len)) . substr($str, 0, 1); }} // Driver Code$str = "GeeksforGeeks";print_r(Reverse($str)); ?>Output:skeeGrofskeeG
In-place reversing a string without using library functions: In-place reversal of string means to reverse the string by doing modification in the original string itself and not making any copy of the original string. We can reverse a string in-place and without using any library function in PHP. The idea to do so is to traverse the original string from both sides, i.e. from both left and right until we reach the middle of the string. And keep swapping the characters while traversing. So, we will simply swap the characters, starting with the first and last, then second-first and second-last and so on, till we reach the middle of the string.Below is the implementation of above idea:<?php// PHP function to in place reverse a string // without using library functions function Reverse($str){ for($i=strlen($str)-1, $j=0; $j<$i; $i--, $j++) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } return $str;} // Driver Code$str = "GeeksforGeeks";print_r(Reverse($str));?>Output:skeeGrofskeeG
Reversing string using strrev(): The strrev() function is a built-in function available in PHP and is used to reverse strings. This function takes a string as argument and returns a reversed string.Syntax:strrev($string)Below is the implementation of program to reverse a string using strrev():<?php// PHP program to reverse a string using strrev() function Reverse($str){ return strrev($str);} // Driver Code$str = "GeeksforGeeks";echo Reverse($str)?>Output:skeeGrofskeeG
Syntax:
strrev($string)
Below is the implementation of program to reverse a string using strrev():
<?php// PHP program to reverse a string using strrev() function Reverse($str){ return strrev($str);} // Driver Code$str = "GeeksforGeeks";echo Reverse($str)?>
Output:
skeeGrofskeeG
Reversing string using recursion and substr(): We can also reverse a string using recursion and substr() function. The substr() function is used to get a substring of the original string. Here we have defined a function Reverse() with the string passed as argument. During every recursive call, we have used the substr() method to extract the first character of argument string and called the Reverse() function again by passing remaining part of string as argument and concatenated the first character at the end of the string returned from current call.Below is the implementation of above idea:<?php // PHP function to reverse a string using // recursion and substr()function Reverse($str){ // strlen() used to calculate the // length of the string $len = strlen($str); // Base case for recursion if($len == 1){ return $str; } else{ $len--; // extract first character and concatenate // at end of string returned from recursive // call on remaining string return Reverse(substr($str,1, $len)) . substr($str, 0, 1); }} // Driver Code$str = "GeeksforGeeks";print_r(Reverse($str)); ?>Output:skeeGrofskeeG
Below is the implementation of above idea:
<?php // PHP function to reverse a string using // recursion and substr()function Reverse($str){ // strlen() used to calculate the // length of the string $len = strlen($str); // Base case for recursion if($len == 1){ return $str; } else{ $len--; // extract first character and concatenate // at end of string returned from recursive // call on remaining string return Reverse(substr($str,1, $len)) . substr($str, 0, 1); }} // Driver Code$str = "GeeksforGeeks";print_r(Reverse($str)); ?>
Output:
skeeGrofskeeG
In-place reversing a string without using library functions: In-place reversal of string means to reverse the string by doing modification in the original string itself and not making any copy of the original string. We can reverse a string in-place and without using any library function in PHP. The idea to do so is to traverse the original string from both sides, i.e. from both left and right until we reach the middle of the string. And keep swapping the characters while traversing. So, we will simply swap the characters, starting with the first and last, then second-first and second-last and so on, till we reach the middle of the string.Below is the implementation of above idea:<?php// PHP function to in place reverse a string // without using library functions function Reverse($str){ for($i=strlen($str)-1, $j=0; $j<$i; $i--, $j++) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } return $str;} // Driver Code$str = "GeeksforGeeks";print_r(Reverse($str));?>Output:skeeGrofskeeG
Below is the implementation of above idea:
<?php// PHP function to in place reverse a string // without using library functions function Reverse($str){ for($i=strlen($str)-1, $j=0; $j<$i; $i--, $j++) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } return $str;} // Driver Code$str = "GeeksforGeeks";print_r(Reverse($str));?>
Output:
skeeGrofskeeG
C-String-Question
Reverse
PHP
Web technologies Questions
Reverse
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2017"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "PHP serves us with many built-in methods which can be used to manipulate strings. In this article, we will learn about how to reverse a string using various methods available in PHP."
},
{
"code": null,
"e": 221,
"s": 211,
"text": "Examples:"
},
{
"code": null,
"e": 297,
"s": 221,
"text": "Input : GeeksforGeeks\nOutput : skeeGrofskeeG\n\nInput : 12485\nOutput : 58421\n"
},
{
"code": null,
"e": 399,
"s": 297,
"text": "Below we have discussed about three basic and most commonly used methods of reversing strings in PHP:"
},
{
"code": null,
"e": 3135,
"s": 399,
"text": "Reversing string using strrev(): The strrev() function is a built-in function available in PHP and is used to reverse strings. This function takes a string as argument and returns a reversed string.Syntax:strrev($string)Below is the implementation of program to reverse a string using strrev():<?php// PHP program to reverse a string using strrev() function Reverse($str){ return strrev($str);} // Driver Code$str = \"GeeksforGeeks\";echo Reverse($str)?>Output:skeeGrofskeeG\nReversing string using recursion and substr(): We can also reverse a string using recursion and substr() function. The substr() function is used to get a substring of the original string. Here we have defined a function Reverse() with the string passed as argument. During every recursive call, we have used the substr() method to extract the first character of argument string and called the Reverse() function again by passing remaining part of string as argument and concatenated the first character at the end of the string returned from current call.Below is the implementation of above idea:<?php // PHP function to reverse a string using // recursion and substr()function Reverse($str){ // strlen() used to calculate the // length of the string $len = strlen($str); // Base case for recursion if($len == 1){ return $str; } else{ $len--; // extract first character and concatenate // at end of string returned from recursive // call on remaining string return Reverse(substr($str,1, $len)) . substr($str, 0, 1); }} // Driver Code$str = \"GeeksforGeeks\";print_r(Reverse($str)); ?>Output:skeeGrofskeeG\nIn-place reversing a string without using library functions: In-place reversal of string means to reverse the string by doing modification in the original string itself and not making any copy of the original string. We can reverse a string in-place and without using any library function in PHP. The idea to do so is to traverse the original string from both sides, i.e. from both left and right until we reach the middle of the string. And keep swapping the characters while traversing. So, we will simply swap the characters, starting with the first and last, then second-first and second-last and so on, till we reach the middle of the string.Below is the implementation of above idea:<?php// PHP function to in place reverse a string // without using library functions function Reverse($str){ for($i=strlen($str)-1, $j=0; $j<$i; $i--, $j++) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } return $str;} // Driver Code$str = \"GeeksforGeeks\";print_r(Reverse($str));?>Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 3614,
"s": 3135,
"text": "Reversing string using strrev(): The strrev() function is a built-in function available in PHP and is used to reverse strings. This function takes a string as argument and returns a reversed string.Syntax:strrev($string)Below is the implementation of program to reverse a string using strrev():<?php// PHP program to reverse a string using strrev() function Reverse($str){ return strrev($str);} // Driver Code$str = \"GeeksforGeeks\";echo Reverse($str)?>Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 3622,
"s": 3614,
"text": "Syntax:"
},
{
"code": null,
"e": 3638,
"s": 3622,
"text": "strrev($string)"
},
{
"code": null,
"e": 3713,
"s": 3638,
"text": "Below is the implementation of program to reverse a string using strrev():"
},
{
"code": "<?php// PHP program to reverse a string using strrev() function Reverse($str){ return strrev($str);} // Driver Code$str = \"GeeksforGeeks\";echo Reverse($str)?>",
"e": 3877,
"s": 3713,
"text": null
},
{
"code": null,
"e": 3885,
"s": 3877,
"text": "Output:"
},
{
"code": null,
"e": 3900,
"s": 3885,
"text": "skeeGrofskeeG\n"
},
{
"code": null,
"e": 5118,
"s": 3900,
"text": "Reversing string using recursion and substr(): We can also reverse a string using recursion and substr() function. The substr() function is used to get a substring of the original string. Here we have defined a function Reverse() with the string passed as argument. During every recursive call, we have used the substr() method to extract the first character of argument string and called the Reverse() function again by passing remaining part of string as argument and concatenated the first character at the end of the string returned from current call.Below is the implementation of above idea:<?php // PHP function to reverse a string using // recursion and substr()function Reverse($str){ // strlen() used to calculate the // length of the string $len = strlen($str); // Base case for recursion if($len == 1){ return $str; } else{ $len--; // extract first character and concatenate // at end of string returned from recursive // call on remaining string return Reverse(substr($str,1, $len)) . substr($str, 0, 1); }} // Driver Code$str = \"GeeksforGeeks\";print_r(Reverse($str)); ?>Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 5161,
"s": 5118,
"text": "Below is the implementation of above idea:"
},
{
"code": "<?php // PHP function to reverse a string using // recursion and substr()function Reverse($str){ // strlen() used to calculate the // length of the string $len = strlen($str); // Base case for recursion if($len == 1){ return $str; } else{ $len--; // extract first character and concatenate // at end of string returned from recursive // call on remaining string return Reverse(substr($str,1, $len)) . substr($str, 0, 1); }} // Driver Code$str = \"GeeksforGeeks\";print_r(Reverse($str)); ?>",
"e": 5761,
"s": 5161,
"text": null
},
{
"code": null,
"e": 5769,
"s": 5761,
"text": "Output:"
},
{
"code": null,
"e": 5784,
"s": 5769,
"text": "skeeGrofskeeG\n"
},
{
"code": null,
"e": 6825,
"s": 5784,
"text": "In-place reversing a string without using library functions: In-place reversal of string means to reverse the string by doing modification in the original string itself and not making any copy of the original string. We can reverse a string in-place and without using any library function in PHP. The idea to do so is to traverse the original string from both sides, i.e. from both left and right until we reach the middle of the string. And keep swapping the characters while traversing. So, we will simply swap the characters, starting with the first and last, then second-first and second-last and so on, till we reach the middle of the string.Below is the implementation of above idea:<?php// PHP function to in place reverse a string // without using library functions function Reverse($str){ for($i=strlen($str)-1, $j=0; $j<$i; $i--, $j++) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } return $str;} // Driver Code$str = \"GeeksforGeeks\";print_r(Reverse($str));?>Output:skeeGrofskeeG\n"
},
{
"code": null,
"e": 6868,
"s": 6825,
"text": "Below is the implementation of above idea:"
},
{
"code": "<?php// PHP function to in place reverse a string // without using library functions function Reverse($str){ for($i=strlen($str)-1, $j=0; $j<$i; $i--, $j++) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } return $str;} // Driver Code$str = \"GeeksforGeeks\";print_r(Reverse($str));?>",
"e": 7199,
"s": 6868,
"text": null
},
{
"code": null,
"e": 7207,
"s": 7199,
"text": "Output:"
},
{
"code": null,
"e": 7222,
"s": 7207,
"text": "skeeGrofskeeG\n"
},
{
"code": null,
"e": 7240,
"s": 7222,
"text": "C-String-Question"
},
{
"code": null,
"e": 7248,
"s": 7240,
"text": "Reverse"
},
{
"code": null,
"e": 7252,
"s": 7248,
"text": "PHP"
},
{
"code": null,
"e": 7279,
"s": 7252,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 7287,
"s": 7279,
"text": "Reverse"
},
{
"code": null,
"e": 7291,
"s": 7287,
"text": "PHP"
}
] |
How to Create Options Menu for RecyclerView in Android using Kotlin?
|
24 Mar, 2021
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item that can be customized vastly while improving the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the memory to reduce memory consumption. In this article, we will explain how to use the Options menu in each item of the RecyclerView. Below is the sample video to show what we are going to build. Note that we are going to implement this project using the Kotlin language.
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add view binding dependency
Go to build.gradle(app) and the following dependency inside the android tag and click sync now.
buildFeatures {
viewBinding true
}
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a single Recycler view which we will use to show our data.
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:background="#F5F8FD" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Add recycler view to main activity--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rv_list" android:layout_width="match_parent" android:layout_height="match_parent" tools:listitem="@layout/single_item" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Create a new layout file and name it a single_item.xml file
Go to the single_item.xml file and refer to the following code. Below is the code for the single_item.xml file. It is the single item layout that we will use in RecyclerView.
XML
<?xml version="1.0" encoding="utf-8"?><com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_marginBottom="10dp" android:layout_marginStart="5dp" android:layout_marginEnd="5dp" android:layout_height="110dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!--Add image view, We will not set any data here.--> <ImageView android:id="@+id/iv_language" android:layout_width="90dp" android:layout_height="90dp" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:scaleType="fitCenter" android:src="@mipmap/ic_launcher" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--Text view for showing the language name--> <TextView android:id="@+id/tv_lang_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="30dp" android:layout_marginTop="20dp" android:text="Language" android:textSize="20sp" android:textColor="@color/black" android:textStyle="bold" app:layout_constraintLeft_toRightOf="@id/iv_language" app:layout_constraintTop_toTopOf="parent" /> <!--Text view fr showing exp--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@id/tv_lang_name" app:layout_constraintLeft_toLeftOf="@id/tv_lang_name" android:text="1 Year exp" android:id="@+id/tv_exp" android:textSize="16sp" android:layout_marginTop="15dp"/> <!--Text view for showing the options menu--> <TextView android:id="@+id/textViewOptions" android:layout_width="20dp" android:gravity="center" android:layout_height="30dp" android:layout_alignParentTop="true" android:textStyle="bold" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" android:layout_margin="20dp" android:text="⋮" android:textAppearance="?android:textAppearanceLarge" /> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView>
Step 5: Create a new model class
Create a new class Language.kt we will use data of custom generic “Language” to pass in the list that will be shown in recycler view.
Kotlin
// this is the Language model classclass Language( val name : String ="", val exp : String = "")
Step 6: Working with the adapter class
Create a new class RvAdapter.kt this will act as an Adapter class for the recycler view. Comments are added before the code for better understanding.
Kotlin
import android.view.LayoutInflaterimport android.view.ViewGroupimport androidx.recyclerview.widget.RecyclerViewimport com.geeksforgeeks.rvadapterviewbinding.databinding.SingleItemBinding class RvAdapter( private var languageList: List<Language>, private var optionsMenuClickListener: OptionsMenuClickListener) : RecyclerView.Adapter<RvAdapter.ViewHolder>() { // create an interface for onClickListener // so that we can handle data most effectively in MainActivity.kt interface OptionsMenuClickListener { fun onOptionsMenuClicked(position: Int) } // create an inner class with name ViewHolder // It takes a view argument, in which pass the generated class of single_item.xml // ie SingleItemBinding and in the RecyclerView.ViewHolder(binding.root) pass it like this inner class ViewHolder(val binding: SingleItemBinding) : RecyclerView.ViewHolder(binding.root) // inside the onCreateViewHolder inflate the view of SingleItemBinding // and return new ViewHolder object containing this layout override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = SingleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } // bind the items with each item of the list languageList which than will be // shown in recycler view // to keep it simple we are not setting any image data to view override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder){ with(languageList[position]){ // set text to language name binding.tvLangName.text = this.name // set exp binding.tvExp.text = this.exp // implement on clickListener and pass position of the item // rest we will handle in MainActivity.kt binding.textViewOptions.setOnClickListener { optionsMenuClickListener.onOptionsMenuClicked(position) } } } } // return the size of languageList override fun getItemCount(): Int { return languageList.size }}
Step 7: Working with MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.MenuItemimport android.widget.PopupMenuimport android.widget.Toastimport androidx.core.view.getimport androidx.recyclerview.widget.LinearLayoutManagerimport com.geeksforgeeks.rvadapterviewbinding.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // view binding for the activity private var _binding: ActivityMainBinding? = null private val binding get() = _binding!! // get reference to the adapter class private var languageList = ArrayList<Language>() private lateinit var rvAdapter: RvAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // define layout manager for the Recycler view binding.rvList.layoutManager = LinearLayoutManager(this) // attach adapter to the recycler view and also handle item click rvAdapter = RvAdapter(languageList , object : RvAdapter.OptionsMenuClickListener{ // implement the required method override fun onOptionsMenuClicked(position: Int) { // this method will handle the onclick options click // it is defined below performOptionsMenuClick(position) } }) // add adapter to the recycler view binding.rvList.adapter = rvAdapter // create objects of Language // create some row data val language1 = Language("Java" , "3 Year exp" ) val language2 = Language("Kotlin" , "2 Year exp" ) val language3 = Language("Python" , "1 Year exp" ) val language4 = Language("CPP" , "5 Year exp" ) val language5 = Language("PHP" , "No exp" ) // pass raw data t rhe list languageList.add(language1) languageList.add(language2) languageList.add(language3) languageList.add(language4) languageList.add(language5) rvAdapter.notifyDataSetChanged() } // this method will handle the onclick options click private fun performOptionsMenuClick(position: Int) { // create object of PopupMenu and pass context and view where we want // to show the popup menu val popupMenu = PopupMenu(this , binding.rvList[position].findViewById(R.id.textViewOptions)) // add the menu popupMenu.inflate(R.menu.options_menu) // implement on menu item click Listener popupMenu.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener{ override fun onMenuItemClick(item: MenuItem?): Boolean { when(item?.itemId){ R.id.delete -> { // here are the logic to delete an item from the list val tempLang = languageList[position] languageList.remove(tempLang) rvAdapter.notifyDataSetChanged() return true } // in the same way you can implement others R.id.item2 -> { // define Toast.makeText(this@MainActivity , "Item 2 clicked" , Toast.LENGTH_SHORT).show() return true } R.id.item3 -> { // define Toast.makeText(this@MainActivity , "Item 3 clicked" , Toast.LENGTH_SHORT).show() return true } } return false } }) popupMenu.show() } // on destroy of view make the binding reference to null override fun onDestroy() { super.onDestroy() _binding = null }}
Output:
Github repo here.
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 895,
"s": 28,
"text": "RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item that can be customized vastly while improving the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the memory to reduce memory consumption. In this article, we will explain how to use the Options menu in each item of the RecyclerView. Below is the sample video to show what we are going to build. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 924,
"s": 895,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 1088,
"s": 924,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 1124,
"s": 1088,
"text": "Step 2: Add view binding dependency"
},
{
"code": null,
"e": 1220,
"s": 1124,
"text": "Go to build.gradle(app) and the following dependency inside the android tag and click sync now."
},
{
"code": null,
"e": 1236,
"s": 1220,
"text": "buildFeatures {"
},
{
"code": null,
"e": 1259,
"s": 1236,
"text": " viewBinding true"
},
{
"code": null,
"e": 1263,
"s": 1259,
"text": " }"
},
{
"code": null,
"e": 1311,
"s": 1263,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1498,
"s": 1311,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a single Recycler view which we will use to show our data."
},
{
"code": null,
"e": 1502,
"s": 1498,
"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:background=\"#F5F8FD\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Add recycler view to main activity--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/rv_list\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:listitem=\"@layout/single_item\" app:layoutManager=\"androidx.recyclerview.widget.LinearLayoutManager\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2298,
"s": 1502,
"text": null
},
{
"code": null,
"e": 2366,
"s": 2298,
"text": "Step 4: Create a new layout file and name it a single_item.xml file"
},
{
"code": null,
"e": 2541,
"s": 2366,
"text": "Go to the single_item.xml file and refer to the following code. Below is the code for the single_item.xml file. It is the single item layout that we will use in RecyclerView."
},
{
"code": null,
"e": 2545,
"s": 2541,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><com.google.android.material.card.MaterialCardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_marginBottom=\"10dp\" android:layout_marginStart=\"5dp\" android:layout_marginEnd=\"5dp\" android:layout_height=\"110dp\"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--Add image view, We will not set any data here.--> <ImageView android:id=\"@+id/iv_language\" android:layout_width=\"90dp\" android:layout_height=\"90dp\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:scaleType=\"fitCenter\" android:src=\"@mipmap/ic_launcher\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--Text view for showing the language name--> <TextView android:id=\"@+id/tv_lang_name\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"30dp\" android:layout_marginTop=\"20dp\" android:text=\"Language\" android:textSize=\"20sp\" android:textColor=\"@color/black\" android:textStyle=\"bold\" app:layout_constraintLeft_toRightOf=\"@id/iv_language\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--Text view fr showing exp--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintTop_toBottomOf=\"@id/tv_lang_name\" app:layout_constraintLeft_toLeftOf=\"@id/tv_lang_name\" android:text=\"1 Year exp\" android:id=\"@+id/tv_exp\" android:textSize=\"16sp\" android:layout_marginTop=\"15dp\"/> <!--Text view for showing the options menu--> <TextView android:id=\"@+id/textViewOptions\" android:layout_width=\"20dp\" android:gravity=\"center\" android:layout_height=\"30dp\" android:layout_alignParentTop=\"true\" android:textStyle=\"bold\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" android:layout_margin=\"20dp\" android:text=\"⋮\" android:textAppearance=\"?android:textAppearanceLarge\" /> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView>",
"e": 5275,
"s": 2545,
"text": null
},
{
"code": null,
"e": 5308,
"s": 5275,
"text": "Step 5: Create a new model class"
},
{
"code": null,
"e": 5442,
"s": 5308,
"text": "Create a new class Language.kt we will use data of custom generic “Language” to pass in the list that will be shown in recycler view."
},
{
"code": null,
"e": 5449,
"s": 5442,
"text": "Kotlin"
},
{
"code": "// this is the Language model classclass Language( val name : String =\"\", val exp : String = \"\")",
"e": 5552,
"s": 5449,
"text": null
},
{
"code": null,
"e": 5591,
"s": 5552,
"text": "Step 6: Working with the adapter class"
},
{
"code": null,
"e": 5741,
"s": 5591,
"text": "Create a new class RvAdapter.kt this will act as an Adapter class for the recycler view. Comments are added before the code for better understanding."
},
{
"code": null,
"e": 5748,
"s": 5741,
"text": "Kotlin"
},
{
"code": "import android.view.LayoutInflaterimport android.view.ViewGroupimport androidx.recyclerview.widget.RecyclerViewimport com.geeksforgeeks.rvadapterviewbinding.databinding.SingleItemBinding class RvAdapter( private var languageList: List<Language>, private var optionsMenuClickListener: OptionsMenuClickListener) : RecyclerView.Adapter<RvAdapter.ViewHolder>() { // create an interface for onClickListener // so that we can handle data most effectively in MainActivity.kt interface OptionsMenuClickListener { fun onOptionsMenuClicked(position: Int) } // create an inner class with name ViewHolder // It takes a view argument, in which pass the generated class of single_item.xml // ie SingleItemBinding and in the RecyclerView.ViewHolder(binding.root) pass it like this inner class ViewHolder(val binding: SingleItemBinding) : RecyclerView.ViewHolder(binding.root) // inside the onCreateViewHolder inflate the view of SingleItemBinding // and return new ViewHolder object containing this layout override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = SingleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } // bind the items with each item of the list languageList which than will be // shown in recycler view // to keep it simple we are not setting any image data to view override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder){ with(languageList[position]){ // set text to language name binding.tvLangName.text = this.name // set exp binding.tvExp.text = this.exp // implement on clickListener and pass position of the item // rest we will handle in MainActivity.kt binding.textViewOptions.setOnClickListener { optionsMenuClickListener.onOptionsMenuClicked(position) } } } } // return the size of languageList override fun getItemCount(): Int { return languageList.size }}",
"e": 7912,
"s": 5748,
"text": null
},
{
"code": null,
"e": 7949,
"s": 7912,
"text": "Step 7: Working with MainActivity.kt"
},
{
"code": null,
"e": 8135,
"s": 7949,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 8142,
"s": 8135,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.MenuItemimport android.widget.PopupMenuimport android.widget.Toastimport androidx.core.view.getimport androidx.recyclerview.widget.LinearLayoutManagerimport com.geeksforgeeks.rvadapterviewbinding.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // view binding for the activity private var _binding: ActivityMainBinding? = null private val binding get() = _binding!! // get reference to the adapter class private var languageList = ArrayList<Language>() private lateinit var rvAdapter: RvAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // define layout manager for the Recycler view binding.rvList.layoutManager = LinearLayoutManager(this) // attach adapter to the recycler view and also handle item click rvAdapter = RvAdapter(languageList , object : RvAdapter.OptionsMenuClickListener{ // implement the required method override fun onOptionsMenuClicked(position: Int) { // this method will handle the onclick options click // it is defined below performOptionsMenuClick(position) } }) // add adapter to the recycler view binding.rvList.adapter = rvAdapter // create objects of Language // create some row data val language1 = Language(\"Java\" , \"3 Year exp\" ) val language2 = Language(\"Kotlin\" , \"2 Year exp\" ) val language3 = Language(\"Python\" , \"1 Year exp\" ) val language4 = Language(\"CPP\" , \"5 Year exp\" ) val language5 = Language(\"PHP\" , \"No exp\" ) // pass raw data t rhe list languageList.add(language1) languageList.add(language2) languageList.add(language3) languageList.add(language4) languageList.add(language5) rvAdapter.notifyDataSetChanged() } // this method will handle the onclick options click private fun performOptionsMenuClick(position: Int) { // create object of PopupMenu and pass context and view where we want // to show the popup menu val popupMenu = PopupMenu(this , binding.rvList[position].findViewById(R.id.textViewOptions)) // add the menu popupMenu.inflate(R.menu.options_menu) // implement on menu item click Listener popupMenu.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener{ override fun onMenuItemClick(item: MenuItem?): Boolean { when(item?.itemId){ R.id.delete -> { // here are the logic to delete an item from the list val tempLang = languageList[position] languageList.remove(tempLang) rvAdapter.notifyDataSetChanged() return true } // in the same way you can implement others R.id.item2 -> { // define Toast.makeText(this@MainActivity , \"Item 2 clicked\" , Toast.LENGTH_SHORT).show() return true } R.id.item3 -> { // define Toast.makeText(this@MainActivity , \"Item 3 clicked\" , Toast.LENGTH_SHORT).show() return true } } return false } }) popupMenu.show() } // on destroy of view make the binding reference to null override fun onDestroy() { super.onDestroy() _binding = null }}",
"e": 11968,
"s": 8142,
"text": null
},
{
"code": null,
"e": 11976,
"s": 11968,
"text": "Output:"
},
{
"code": null,
"e": 11995,
"s": 11976,
"text": "Github repo here. "
},
{
"code": null,
"e": 12010,
"s": 11995,
"text": "Kotlin Android"
},
{
"code": null,
"e": 12018,
"s": 12010,
"text": "Android"
},
{
"code": null,
"e": 12025,
"s": 12018,
"text": "Kotlin"
},
{
"code": null,
"e": 12033,
"s": 12025,
"text": "Android"
},
{
"code": null,
"e": 12131,
"s": 12033,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12163,
"s": 12131,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 12202,
"s": 12163,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 12271,
"s": 12202,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 12313,
"s": 12271,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 12364,
"s": 12313,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 12383,
"s": 12364,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 12396,
"s": 12383,
"text": "Kotlin Array"
},
{
"code": null,
"e": 12465,
"s": 12396,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
}
] |
Python – Sympy Polygon.intersection() Method
|
01 Aug, 2020
In Sympy, the function Polygon.intersection() is used to get the intersection of a given polygon and the given geometry entity. The geometry entity can be a point, line, polygon, or other geometric figures. The intersection may be empty if the polygon and the given geometry entity are not intersected anywhere. But can contain individual Points or complete Line Segments if intersection exists.
Syntax: Polygon.intersection(o)
Parameters: Geometry Entity
Returns: The list of Segments or Points of intersection.
Example #1:
Python3
# import Point, Polygonfrom sympy import Point, Polygon # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)]) # creating polygons using Polygon()poly1 = Polygon(p1, p2, p3, p4)poly2 = Polygon(p5, p6, p7) # using intersection()isIntersection = poly1.intersection(poly2) print(isIntersection)
Output:
[Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)]
Example #2:
Python3
# import Point, Polygonfrom sympy import Point, Polygon # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) # creating polygon using Polygon()poly1 = Polygon(p1, p2, p3, p4) # using intersection()isIntersection = poly1.intersection(Line(p1, Point(3, 2))) print(isIntersection)
Output:
[Point2D(0, 0), Point2D(3/2, 1)]
Python SymPy-Geometry
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 424,
"s": 28,
"text": "In Sympy, the function Polygon.intersection() is used to get the intersection of a given polygon and the given geometry entity. The geometry entity can be a point, line, polygon, or other geometric figures. The intersection may be empty if the polygon and the given geometry entity are not intersected anywhere. But can contain individual Points or complete Line Segments if intersection exists."
},
{
"code": null,
"e": 544,
"s": 424,
"text": "Syntax: Polygon.intersection(o)\n\nParameters: Geometry Entity\n\nReturns: The list of Segments or Points of intersection.\n"
},
{
"code": null,
"e": 556,
"s": 544,
"text": "Example #1:"
},
{
"code": null,
"e": 564,
"s": 556,
"text": "Python3"
},
{
"code": "# import Point, Polygonfrom sympy import Point, Polygon # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)]) # creating polygons using Polygon()poly1 = Polygon(p1, p2, p3, p4)poly2 = Polygon(p5, p6, p7) # using intersection()isIntersection = poly1.intersection(poly2) print(isIntersection)",
"e": 948,
"s": 564,
"text": null
},
{
"code": null,
"e": 956,
"s": 948,
"text": "Output:"
},
{
"code": null,
"e": 1027,
"s": 956,
"text": "[Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)]"
},
{
"code": null,
"e": 1039,
"s": 1027,
"text": "Example #2:"
},
{
"code": null,
"e": 1047,
"s": 1039,
"text": "Python3"
},
{
"code": "# import Point, Polygonfrom sympy import Point, Polygon # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) # creating polygon using Polygon()poly1 = Polygon(p1, p2, p3, p4) # using intersection()isIntersection = poly1.intersection(Line(p1, Point(3, 2))) print(isIntersection)",
"e": 1405,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1413,
"s": 1405,
"text": "Output:"
},
{
"code": null,
"e": 1446,
"s": 1413,
"text": "[Point2D(0, 0), Point2D(3/2, 1)]"
},
{
"code": null,
"e": 1468,
"s": 1446,
"text": "Python SymPy-Geometry"
},
{
"code": null,
"e": 1474,
"s": 1468,
"text": "SymPy"
},
{
"code": null,
"e": 1481,
"s": 1474,
"text": "Python"
}
] |
Program to get the Sum of series: 1 – x^2/2! + x^4/4! -.... upto nth term
|
03 Jun, 2022
This is a mathematical series program where a user must enter the number of terms up to which the sum of the series is to be found. Following this, we also need the value of x, which forms the base of the series.
Examples:
Input : x = 9, n = 10
Output : -5.1463
Input : x = 5, n = 15
Output : 0.2837
Simple approach : We use two nested loops to compute factorial and use power function to compute power.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to get the sum of the series#include <bits/stdc++.h>using namespace std; // Function to get the seriesdouble Series(double x, int n){ double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = term * pow(x, y) / fct; sum = sum + m; y += 2; } return sum;} // Driver Codeint main(){ double x = 9; int n = 10; cout << Series(x, n); return 0;}// This code is contributed by Samim Hossain Mondal.
// C program to get the sum of the series#include <math.h>#include <stdio.h> // Function to get the seriesdouble Series(double x, int n){ double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = term * pow(x, y) / fct; sum = sum + m; y += 2; } return sum;} // Driver Codeint main(){ double x = 9; int n = 10; printf("%.4f", Series(x, n)); return 0;}
// Java program to get the sum of the seriesimport java.io.*; class MathSeries { // Function to get the series static double Series(double x, int n) { double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = Math.pow(x, y) / fct; m = m * term; sum = sum + m; y += 2; } return sum; } // Driver Code public static void main(String[] args) { double x = 3; int n = 4; System.out.println(Math.round(Series(x, n) * 10000.0) / 10000.0); }}
# Python3 code to get the sum of the seriesimport math # Function to get the seriesdef Series( x , n ): sum = 1 term = 1 y = 2 # Sum of n-1 terms starting from 2nd term for i in range(1,n): fct = 1 for j in range(1,y+1): fct = fct * j term = term * (-1) m = term * math.pow(x, y) / fct sum = sum + m y += 2 return sum # Driver Codex = 9n = 10print('%.4f'% Series(x, n)) # This code is contributed by "Sharad_Bhardwaj".
// C# program to get the sum of the seriesusing System; class GFG { // Function to get the series static double Series(double x, int n) { double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = Math.Pow(x, y) / fct; m = m * term; sum = sum + m; y += 2; } return sum; } // Driver Code public static void Main() { double x = 9; int n = 10; Console.Write(Series(x, n) * 10000.0 / 10000.0); }} // This code is contributed by vt_m.
<?php// PHP program to get the// sum of the series // Function to get the seriesfunction Series($x, $n){ $sum = 1; $term = 1; $fct; $j; $y = 2; $m; // Sum of n-1 terms starting // from 2nd term for ($i = 1; $i < $n; $i++) { $fct = 1; for ($j = 1; $j <= $y; $j++) { $fct = $fct * $j; } $term = $term * (-1); $m = $term * pow($x, $y) / $fct; $sum = $sum + $m; $y += 2; } return $sum;} // Driver Code$x = 9;$n = 10;$precision = 4;echo substr(number_format(Series($x, $n), $precision + 1, '.', ''), 0, -1); // This code is contributed by Ajit.?>
<script> // Javascript program to get the sum of the series // Function to get the seriesfunction Series(x, n){ let sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term let i; for(i = 1; i < n; i++) { fct = 1; for(j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = term * Math.pow(x, y) / fct; sum = sum + m; y += 2; } return sum;} // Driver Codelet x = 9;let n = 10; document.write(Series(x, n).toFixed(4)); // This code is contributed by Surbhi Tyagi. </script>
-5.1463
Time Complexity: O(n * y)
Auxiliary Space: O(1)
Efficient approach : We can avoid inner loop and use of power function by using values computed in previous iteration.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to get the sum of the series#include <math.h>#include <stdio.h> // Function to get the seriesdouble Series(double x, int n){ double sum = 1, term = 1, fct = 1, p = 1, multi = 1; // Computing sum of remaining n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi+1); p = p*x*x; term = (-1) * term; multi += 2; sum = sum + (term * p)/fct; } return sum;} // Driver Codeint main(){ double x = 9; int n = 10; printf("%.4f", Series(x, n)); return 0;}
#include <stdio.h>#include <stdlib.h>#include <limits.h>#include <limits.h> double Series(double x, int n){ double sum = 1, term = 1, fct = 1, p = 1, multi = 1; // Computing sum of remaining n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return sum;} int main(){ double x = 9; int n = 10; printf("%.4f", Series(x, n)); return 0;} // This code is contributed by abhinavprkash.
// Java program to get// the sum of the seriesimport java.io.*; class GFG { // Function to get // the series static double Series(double x, int n) { double sum = 1, term = 1, fct = 1; double p = 1, multi = 1; // Computing sum of remaining // n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return sum; } // Driver Code public static void main(String args[]) { double x = 9; int n = 10; System.out.printf("%.4f", Series(x, n)); }} // This code is contributed by Nikita Tiwari.
# Python3 code to get the sum of the series # Function to get the seriesdef Series(x, n): sum = 1 term = 1 fct = 1 p = 1 multi = 1 # Computing sum of remaining n-1 terms. for i in range(1, n): fct = fct * multi * (multi+1) p = p*x*x term = (-1) * term multi += 2 sum = sum + (term * p)/fct return sum # Driver Codex = 9n = 10print('%.4f'% Series(x, n)) # This code is contributed by "Sharad_Bhardwaj".
// C# program to get// the sum of the seriesusing System; class GFG { // Function to get // the series static float Series(double x, int n) { double sum = 1, term = 1, fct = 1; double p = 1, multi = 1; // Computing sum of remaining // n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return (float)sum; } // Driver Code public static void Main() { double x = 9; int n = 10; Console.Write(Series(x, n)); }} // This code is contributed by vt_m.
<?php// PHP program to get// the sum of the series // Function to get the seriesfunction Series($x, $n){ $sum = 1; $term = 1; $fct = 1; $p = 1; $multi = 1; // Computing sum of // remaining n-1 terms. for ($i = 1; $i < $n; $i++) { $fct = $fct * $multi * ($multi + 1); $p = $p * $x * $x; $term = (-1) * $term; $multi += 2; $sum = $sum + ($term * $p) / $fct; } return $sum;} // Driver Code$x = 9;$n = 10;$precision = 4;echo substr(number_format(Series($x, $n), $precision + 1, '.', ''), 0, -1); // This code is contributed by Ajit.?>
<script>// Javascript program to get// the sum of the series // Function to get // the series function Series(x , n) { var sum = 1, term = 1, fct = 1; var p = 1, multi = 1; // Computing sum of remaining // n-1 terms. for (let i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return sum; } // Driver Code var x = 9; var n = 10; document.write(Series(x, n).toFixed(4)); // This code is contributed by Amit Katiyar</script>
-5.1463
Time Complexity: O(n)
Auxiliary Space: O(1)
jit_t
amit143katiyar
surbhityagi15
samim2000
abhinavprkash
factorial
series
Mathematical
Mathematical
series
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Modulo Operator (%) in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Program for factorial of a number
Program to print prime numbers from 1 to N.
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 267,
"s": 53,
"text": "This is a mathematical series program where a user must enter the number of terms up to which the sum of the series is to be found. Following this, we also need the value of x, which forms the base of the series. "
},
{
"code": null,
"e": 278,
"s": 267,
"text": "Examples: "
},
{
"code": null,
"e": 356,
"s": 278,
"text": "Input : x = 9, n = 10\nOutput : -5.1463\n\nInput : x = 5, n = 15\nOutput : 0.2837"
},
{
"code": null,
"e": 460,
"s": 356,
"text": "Simple approach : We use two nested loops to compute factorial and use power function to compute power."
},
{
"code": null,
"e": 464,
"s": 460,
"text": "C++"
},
{
"code": null,
"e": 466,
"s": 464,
"text": "C"
},
{
"code": null,
"e": 471,
"s": 466,
"text": "Java"
},
{
"code": null,
"e": 479,
"s": 471,
"text": "Python3"
},
{
"code": null,
"e": 482,
"s": 479,
"text": "C#"
},
{
"code": null,
"e": 486,
"s": 482,
"text": "PHP"
},
{
"code": null,
"e": 497,
"s": 486,
"text": "Javascript"
},
{
"code": "// C++ program to get the sum of the series#include <bits/stdc++.h>using namespace std; // Function to get the seriesdouble Series(double x, int n){ double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = term * pow(x, y) / fct; sum = sum + m; y += 2; } return sum;} // Driver Codeint main(){ double x = 9; int n = 10; cout << Series(x, n); return 0;}// This code is contributed by Samim Hossain Mondal.",
"e": 1133,
"s": 497,
"text": null
},
{
"code": "// C program to get the sum of the series#include <math.h>#include <stdio.h> // Function to get the seriesdouble Series(double x, int n){ double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = term * pow(x, y) / fct; sum = sum + m; y += 2; } return sum;} // Driver Codeint main(){ double x = 9; int n = 10; printf(\"%.4f\", Series(x, n)); return 0;}",
"e": 1714,
"s": 1133,
"text": null
},
{
"code": "// Java program to get the sum of the seriesimport java.io.*; class MathSeries { // Function to get the series static double Series(double x, int n) { double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = Math.pow(x, y) / fct; m = m * term; sum = sum + m; y += 2; } return sum; } // Driver Code public static void main(String[] args) { double x = 3; int n = 4; System.out.println(Math.round(Series(x, n) * 10000.0) / 10000.0); }}",
"e": 2510,
"s": 1714,
"text": null
},
{
"code": "# Python3 code to get the sum of the seriesimport math # Function to get the seriesdef Series( x , n ): sum = 1 term = 1 y = 2 # Sum of n-1 terms starting from 2nd term for i in range(1,n): fct = 1 for j in range(1,y+1): fct = fct * j term = term * (-1) m = term * math.pow(x, y) / fct sum = sum + m y += 2 return sum # Driver Codex = 9n = 10print('%.4f'% Series(x, n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 3019,
"s": 2510,
"text": null
},
{
"code": "// C# program to get the sum of the seriesusing System; class GFG { // Function to get the series static double Series(double x, int n) { double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term int i; for (i = 1; i < n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = Math.Pow(x, y) / fct; m = m * term; sum = sum + m; y += 2; } return sum; } // Driver Code public static void Main() { double x = 9; int n = 10; Console.Write(Series(x, n) * 10000.0 / 10000.0); }} // This code is contributed by vt_m.",
"e": 3803,
"s": 3019,
"text": null
},
{
"code": "<?php// PHP program to get the// sum of the series // Function to get the seriesfunction Series($x, $n){ $sum = 1; $term = 1; $fct; $j; $y = 2; $m; // Sum of n-1 terms starting // from 2nd term for ($i = 1; $i < $n; $i++) { $fct = 1; for ($j = 1; $j <= $y; $j++) { $fct = $fct * $j; } $term = $term * (-1); $m = $term * pow($x, $y) / $fct; $sum = $sum + $m; $y += 2; } return $sum;} // Driver Code$x = 9;$n = 10;$precision = 4;echo substr(number_format(Series($x, $n), $precision + 1, '.', ''), 0, -1); // This code is contributed by Ajit.?>",
"e": 4448,
"s": 3803,
"text": null
},
{
"code": "<script> // Javascript program to get the sum of the series // Function to get the seriesfunction Series(x, n){ let sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term let i; for(i = 1; i < n; i++) { fct = 1; for(j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = term * Math.pow(x, y) / fct; sum = sum + m; y += 2; } return sum;} // Driver Codelet x = 9;let n = 10; document.write(Series(x, n).toFixed(4)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 5040,
"s": 4448,
"text": null
},
{
"code": null,
"e": 5048,
"s": 5040,
"text": "-5.1463"
},
{
"code": null,
"e": 5074,
"s": 5048,
"text": "Time Complexity: O(n * y)"
},
{
"code": null,
"e": 5096,
"s": 5074,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5215,
"s": 5096,
"text": "Efficient approach : We can avoid inner loop and use of power function by using values computed in previous iteration."
},
{
"code": null,
"e": 5219,
"s": 5215,
"text": "C++"
},
{
"code": null,
"e": 5221,
"s": 5219,
"text": "C"
},
{
"code": null,
"e": 5226,
"s": 5221,
"text": "Java"
},
{
"code": null,
"e": 5234,
"s": 5226,
"text": "Python3"
},
{
"code": null,
"e": 5237,
"s": 5234,
"text": "C#"
},
{
"code": null,
"e": 5241,
"s": 5237,
"text": "PHP"
},
{
"code": null,
"e": 5252,
"s": 5241,
"text": "Javascript"
},
{
"code": "// C++ program to get the sum of the series#include <math.h>#include <stdio.h> // Function to get the seriesdouble Series(double x, int n){ double sum = 1, term = 1, fct = 1, p = 1, multi = 1; // Computing sum of remaining n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi+1); p = p*x*x; term = (-1) * term; multi += 2; sum = sum + (term * p)/fct; } return sum;} // Driver Codeint main(){ double x = 9; int n = 10; printf(\"%.4f\", Series(x, n)); return 0;}",
"e": 5800,
"s": 5252,
"text": null
},
{
"code": "#include <stdio.h>#include <stdlib.h>#include <limits.h>#include <limits.h> double Series(double x, int n){ double sum = 1, term = 1, fct = 1, p = 1, multi = 1; // Computing sum of remaining n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return sum;} int main(){ double x = 9; int n = 10; printf(\"%.4f\", Series(x, n)); return 0;} // This code is contributed by abhinavprkash.",
"e": 6308,
"s": 5800,
"text": null
},
{
"code": "// Java program to get// the sum of the seriesimport java.io.*; class GFG { // Function to get // the series static double Series(double x, int n) { double sum = 1, term = 1, fct = 1; double p = 1, multi = 1; // Computing sum of remaining // n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return sum; } // Driver Code public static void main(String args[]) { double x = 9; int n = 10; System.out.printf(\"%.4f\", Series(x, n)); }} // This code is contributed by Nikita Tiwari.",
"e": 7071,
"s": 6308,
"text": null
},
{
"code": "# Python3 code to get the sum of the series # Function to get the seriesdef Series(x, n): sum = 1 term = 1 fct = 1 p = 1 multi = 1 # Computing sum of remaining n-1 terms. for i in range(1, n): fct = fct * multi * (multi+1) p = p*x*x term = (-1) * term multi += 2 sum = sum + (term * p)/fct return sum # Driver Codex = 9n = 10print('%.4f'% Series(x, n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 7542,
"s": 7071,
"text": null
},
{
"code": "// C# program to get// the sum of the seriesusing System; class GFG { // Function to get // the series static float Series(double x, int n) { double sum = 1, term = 1, fct = 1; double p = 1, multi = 1; // Computing sum of remaining // n-1 terms. for (int i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return (float)sum; } // Driver Code public static void Main() { double x = 9; int n = 10; Console.Write(Series(x, n)); }} // This code is contributed by vt_m.",
"e": 8267,
"s": 7542,
"text": null
},
{
"code": "<?php// PHP program to get// the sum of the series // Function to get the seriesfunction Series($x, $n){ $sum = 1; $term = 1; $fct = 1; $p = 1; $multi = 1; // Computing sum of // remaining n-1 terms. for ($i = 1; $i < $n; $i++) { $fct = $fct * $multi * ($multi + 1); $p = $p * $x * $x; $term = (-1) * $term; $multi += 2; $sum = $sum + ($term * $p) / $fct; } return $sum;} // Driver Code$x = 9;$n = 10;$precision = 4;echo substr(number_format(Series($x, $n), $precision + 1, '.', ''), 0, -1); // This code is contributed by Ajit.?>",
"e": 8915,
"s": 8267,
"text": null
},
{
"code": "<script>// Javascript program to get// the sum of the series // Function to get // the series function Series(x , n) { var sum = 1, term = 1, fct = 1; var p = 1, multi = 1; // Computing sum of remaining // n-1 terms. for (let i = 1; i < n; i++) { fct = fct * multi * (multi + 1); p = p * x * x; term = (-1) * term; multi += 2; sum = sum + (term * p) / fct; } return sum; } // Driver Code var x = 9; var n = 10; document.write(Series(x, n).toFixed(4)); // This code is contributed by Amit Katiyar</script>",
"e": 9569,
"s": 8915,
"text": null
},
{
"code": null,
"e": 9577,
"s": 9569,
"text": "-5.1463"
},
{
"code": null,
"e": 9599,
"s": 9577,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 9621,
"s": 9599,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9627,
"s": 9621,
"text": "jit_t"
},
{
"code": null,
"e": 9642,
"s": 9627,
"text": "amit143katiyar"
},
{
"code": null,
"e": 9656,
"s": 9642,
"text": "surbhityagi15"
},
{
"code": null,
"e": 9666,
"s": 9656,
"text": "samim2000"
},
{
"code": null,
"e": 9680,
"s": 9666,
"text": "abhinavprkash"
},
{
"code": null,
"e": 9690,
"s": 9680,
"text": "factorial"
},
{
"code": null,
"e": 9697,
"s": 9690,
"text": "series"
},
{
"code": null,
"e": 9710,
"s": 9697,
"text": "Mathematical"
},
{
"code": null,
"e": 9723,
"s": 9710,
"text": "Mathematical"
},
{
"code": null,
"e": 9730,
"s": 9723,
"text": "series"
},
{
"code": null,
"e": 9740,
"s": 9730,
"text": "factorial"
},
{
"code": null,
"e": 9838,
"s": 9740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9859,
"s": 9838,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9912,
"s": 9859,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 9949,
"s": 9912,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 9981,
"s": 9949,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 10024,
"s": 9981,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 10067,
"s": 10024,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 10094,
"s": 10067,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 10128,
"s": 10094,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 10172,
"s": 10128,
"text": "Program to print prime numbers from 1 to N."
}
] |
How to reload the current page without losing any form data with HTML?
|
The easiest way to reload the current page without losing form data, use WebStorage where you have -persistent storage (localStorage) or session-based (sessionStorage) which remains in memory until your web browser is closed.
Try this when the page is about to reload,
window.onbeforeunload = function() {
localStorage.setItem(name, $('#inputName').val());
localStorage.setItem(phone, $('#inputPhone').val());
localStorage.setItem(subject, $('#inputAddress').val());
}
Now check it like −
window.onload = function() {
var name = localStorage.getItem(name);
var phone = localStorage.getItem(phone);
if (name !== null) $('#inputName').val(name); if (phone !== null) $('#inputPhone').val(phone);
// ...
}
|
[
{
"code": null,
"e": 1413,
"s": 1187,
"text": "The easiest way to reload the current page without losing form data, use WebStorage where you have -persistent storage (localStorage) or session-based (sessionStorage) which remains in memory until your web browser is closed."
},
{
"code": null,
"e": 1456,
"s": 1413,
"text": "Try this when the page is about to reload,"
},
{
"code": null,
"e": 1665,
"s": 1456,
"text": "window.onbeforeunload = function() {\n localStorage.setItem(name, $('#inputName').val());\n localStorage.setItem(phone, $('#inputPhone').val());\n localStorage.setItem(subject, $('#inputAddress').val());\n}"
},
{
"code": null,
"e": 1685,
"s": 1665,
"text": "Now check it like −"
},
{
"code": null,
"e": 1910,
"s": 1685,
"text": "window.onload = function() {\n var name = localStorage.getItem(name);\n var phone = localStorage.getItem(phone);\n if (name !== null) $('#inputName').val(name); if (phone !== null) $('#inputPhone').val(phone);\n // ...\n}"
}
] |
Maximum absolute difference between distinct elements in an Array
|
18 May, 2021
Given an array arr[] of N integers, the task is to find the maximum absolute difference between distinct elements of the array.Examples:
Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10} Output: 10 Explanation: Distinct elements of given array are 12, 9, 2. Therefore, the maximum absolute difference between them is (12 – 2) = 10.
Input: arr[] = {2, -1, 10, 3, -2, -1, 10} Output: 5 Explanation: Distinct elements of given array are 2, 3, -2. Therefore, the maximum absolute difference between them is (3 – (-2)) = 5.
Naive Approach: The naive approach is to store the distinct element in the given array in an array temp[] and print the difference of maximum and minimum element of the array temp[].
Time Complexity: O(N2) Auxiliary Space: O(N)
Efficient Approach: The above naive approach can be optimized using Hashing. Below are the steps:
Store the frequency of each element of the array arr[] in a HashMap.Now find the maximum and minimum value of the array whose frequency is 1 using the above HashMap created.Print the difference between the maximum and minimum value obtained in the above step.
Store the frequency of each element of the array arr[] in a HashMap.
Now find the maximum and minimum value of the array whose frequency is 1 using the above HashMap created.
Print the difference between the maximum and minimum value obtained in the above step.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum// absolute difference between// distinct elements in arr[]int MaxAbsDiff(int arr[], int n){ // Map to store each element // with their occurrence in array unordered_map<int, int> map; // maxElement and minElement to // store maximum and minimum // distinct element in arr[] int maxElement = INT_MIN; int minElement = INT_MAX; // Traverse arr[] and update each // element frequency in Map for(int i = 0; i < n; i++) { map[arr[i]]++; } // Traverse Map and check if // value of any key appears 1 // then update maxElement and // minElement by that key for(auto itr = map.begin(); itr != map.end(); itr++) { if (itr -> second == 1) { maxElement = max(maxElement, itr -> first); minElement = min(minElement, itr -> first); } } // Return absolute difference of // maxElement and minElement return abs(maxElement - minElement);} // Driver Codeint main(){ // Given array arr[] int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45, 10 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << MaxAbsDiff(arr, n) << "\n"; return 0;} // This code is contributed by akhilsaini
// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum // absolute difference between // distinct elements in arr[] static int MaxAbsDiff(int[] arr, int n) { // HashMap to store each element // with their occurrence in array Map<Integer, Integer> map = new HashMap<>(); // maxElement and minElement to // store maximum and minimum // distinct element in arr[] int maxElement = Integer.MIN_VALUE; int minElement = Integer.MAX_VALUE; // Traverse arr[] and update each // element frequency in HashMap for (int i = 0; i < n; i++) { map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); } // Traverse HashMap and check if // value of any key appears 1 // then update maxElement and // minElement by that key for (Map.Entry<Integer, Integer> k : map.entrySet()) { if (k.getValue() == 1) { maxElement = Math.max(maxElement, k.getKey()); minElement = Math.min(minElement, k.getKey()); } } // Return absolute difference of // maxElement and minElement return Math.abs(maxElement - minElement); } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 12, 10, 9, 45, 2, 10, 10, 45, 10 }; int n = arr.length; // Function Call System.out.println(MaxAbsDiff(arr, n)); }}
# Python3 program for# the above approachimport sysfrom collections import defaultdict # Function to find the maximum# absolute difference between# distinct elements in arr[]def MaxAbsDiff(arr, n): # HashMap to store each element # with their occurrence in array map = defaultdict (int) # maxElement and minElement to # store maximum and minimum # distinct element in arr[] maxElement = -sys.maxsize - 1 minElement = sys.maxsize # Traverse arr[] and update each # element frequency in HashMap for i in range (n): map[arr[i]] += 1 # Traverse HashMap and check if # value of any key appears 1 # then update maxElement and # minElement by that key for k in map: if (map[k] == 1): maxElement = max(maxElement, k) minElement = min(minElement, k) # Return absolute difference of # maxElement and minElement return abs(maxElement - minElement) # Driver Codeif __name__ == "__main__": # Given array arr[] arr = [12, 10, 9, 45, 2, 10, 10, 45, 10] n = len( arr) # Function Call print(MaxAbsDiff(arr, n)) # This code is contributed by Chitranayal
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the maximum// absolute difference between// distinct elements in []arrstatic int MaxAbsDiff(int[] arr, int n){ // Dictionary to store each element // with their occurrence in array Dictionary<int, int> map = new Dictionary<int, int>(); // maxElement and minElement to // store maximum and minimum // distinct element in []arr int maxElement = int.MinValue; int minElement = int.MaxValue; // Traverse []arr and update each // element frequency in Dictionary for(int i = 0; i < n; i++) { if(map.ContainsKey(arr[i])) map[arr[i]] = map[arr[i]] + 1; else map.Add(arr[i], 1); } // Traverse Dictionary and check if // value of any key appears 1 // then update maxElement and // minElement by that key foreach (KeyValuePair<int, int> k in map) { if (k.Value == 1) { maxElement = Math.Max(maxElement, k.Key); minElement = Math.Min(minElement, k.Key); } } // Return absolute difference of // maxElement and minElement return Math.Abs(maxElement - minElement);} // Driver Codepublic static void Main(String[] args){ // Given array []arr int[] arr = { 12, 10, 9, 45, 2, 10, 10, 45, 10 }; int n = arr.Length; // Function call Console.WriteLine(MaxAbsDiff(arr, n));}} // This code is contributed by Princi Singh
<script>// Javascript program for the above approach // Function to find the maximum// absolute difference between// distinct elements in arr[]function MaxAbsDiff(arr, n){ // Map to store each element // with their occurrence in array var map = new Map(); // maxElement and minElement to // store maximum and minimum // distinct element in arr[] var maxElement = -1000000000; var minElement = 1000000000; // Traverse arr[] and update each // element frequency in Map for(var i = 0; i < n; i++) { if(map.has(arr[i])) map.set(arr[i], map.get(arr[i])+1) else map.set(arr[i], 1); } // Traverse Map and check if // value of any key appears 1 // then update maxElement and // minElement by that key map.forEach((value, key) => { if (value == 1) { maxElement = Math.max(maxElement, key); minElement = Math.min(minElement, key); } }); // Return absolute difference of // maxElement and minElement return Math.abs(maxElement - minElement);} // Driver Code // Given array arr[]var arr = [12, 10, 9, 45, 2, 10, 10, 45, 10 ];var n = arr.length;// Function calldocument.write( MaxAbsDiff(arr, n)); // This code is contributed by famously.</script>
10
Time Complexity: O(N) Auxiliary Space: O(N)
princi singh
nidhi_biet
ukasp
akhilsaini
famously
Data Structures-Hash
Java-HashMap
Arrays
Data Structures
Hash
School Programming
Data Structures
Arrays
Hash
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
Next Greater Element
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion)
What is Hashing | A Complete Tutorial
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "Given an array arr[] of N integers, the task is to find the maximum absolute difference between distinct elements of the array.Examples: "
},
{
"code": null,
"e": 361,
"s": 166,
"text": "Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10} Output: 10 Explanation: Distinct elements of given array are 12, 9, 2. Therefore, the maximum absolute difference between them is (12 – 2) = 10."
},
{
"code": null,
"e": 550,
"s": 361,
"text": "Input: arr[] = {2, -1, 10, 3, -2, -1, 10} Output: 5 Explanation: Distinct elements of given array are 2, 3, -2. Therefore, the maximum absolute difference between them is (3 – (-2)) = 5. "
},
{
"code": null,
"e": 733,
"s": 550,
"text": "Naive Approach: The naive approach is to store the distinct element in the given array in an array temp[] and print the difference of maximum and minimum element of the array temp[]."
},
{
"code": null,
"e": 778,
"s": 733,
"text": "Time Complexity: O(N2) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 877,
"s": 778,
"text": "Efficient Approach: The above naive approach can be optimized using Hashing. Below are the steps: "
},
{
"code": null,
"e": 1137,
"s": 877,
"text": "Store the frequency of each element of the array arr[] in a HashMap.Now find the maximum and minimum value of the array whose frequency is 1 using the above HashMap created.Print the difference between the maximum and minimum value obtained in the above step."
},
{
"code": null,
"e": 1206,
"s": 1137,
"text": "Store the frequency of each element of the array arr[] in a HashMap."
},
{
"code": null,
"e": 1312,
"s": 1206,
"text": "Now find the maximum and minimum value of the array whose frequency is 1 using the above HashMap created."
},
{
"code": null,
"e": 1399,
"s": 1312,
"text": "Print the difference between the maximum and minimum value obtained in the above step."
},
{
"code": null,
"e": 1450,
"s": 1399,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1454,
"s": 1450,
"text": "C++"
},
{
"code": null,
"e": 1459,
"s": 1454,
"text": "Java"
},
{
"code": null,
"e": 1467,
"s": 1459,
"text": "Python3"
},
{
"code": null,
"e": 1470,
"s": 1467,
"text": "C#"
},
{
"code": null,
"e": 1481,
"s": 1470,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum// absolute difference between// distinct elements in arr[]int MaxAbsDiff(int arr[], int n){ // Map to store each element // with their occurrence in array unordered_map<int, int> map; // maxElement and minElement to // store maximum and minimum // distinct element in arr[] int maxElement = INT_MIN; int minElement = INT_MAX; // Traverse arr[] and update each // element frequency in Map for(int i = 0; i < n; i++) { map[arr[i]]++; } // Traverse Map and check if // value of any key appears 1 // then update maxElement and // minElement by that key for(auto itr = map.begin(); itr != map.end(); itr++) { if (itr -> second == 1) { maxElement = max(maxElement, itr -> first); minElement = min(minElement, itr -> first); } } // Return absolute difference of // maxElement and minElement return abs(maxElement - minElement);} // Driver Codeint main(){ // Given array arr[] int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45, 10 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << MaxAbsDiff(arr, n) << \"\\n\"; return 0;} // This code is contributed by akhilsaini",
"e": 2901,
"s": 1481,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum // absolute difference between // distinct elements in arr[] static int MaxAbsDiff(int[] arr, int n) { // HashMap to store each element // with their occurrence in array Map<Integer, Integer> map = new HashMap<>(); // maxElement and minElement to // store maximum and minimum // distinct element in arr[] int maxElement = Integer.MIN_VALUE; int minElement = Integer.MAX_VALUE; // Traverse arr[] and update each // element frequency in HashMap for (int i = 0; i < n; i++) { map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); } // Traverse HashMap and check if // value of any key appears 1 // then update maxElement and // minElement by that key for (Map.Entry<Integer, Integer> k : map.entrySet()) { if (k.getValue() == 1) { maxElement = Math.max(maxElement, k.getKey()); minElement = Math.min(minElement, k.getKey()); } } // Return absolute difference of // maxElement and minElement return Math.abs(maxElement - minElement); } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 12, 10, 9, 45, 2, 10, 10, 45, 10 }; int n = arr.length; // Function Call System.out.println(MaxAbsDiff(arr, n)); }}",
"e": 4628,
"s": 2901,
"text": null
},
{
"code": "# Python3 program for# the above approachimport sysfrom collections import defaultdict # Function to find the maximum# absolute difference between# distinct elements in arr[]def MaxAbsDiff(arr, n): # HashMap to store each element # with their occurrence in array map = defaultdict (int) # maxElement and minElement to # store maximum and minimum # distinct element in arr[] maxElement = -sys.maxsize - 1 minElement = sys.maxsize # Traverse arr[] and update each # element frequency in HashMap for i in range (n): map[arr[i]] += 1 # Traverse HashMap and check if # value of any key appears 1 # then update maxElement and # minElement by that key for k in map: if (map[k] == 1): maxElement = max(maxElement, k) minElement = min(minElement, k) # Return absolute difference of # maxElement and minElement return abs(maxElement - minElement) # Driver Codeif __name__ == \"__main__\": # Given array arr[] arr = [12, 10, 9, 45, 2, 10, 10, 45, 10] n = len( arr) # Function Call print(MaxAbsDiff(arr, n)) # This code is contributed by Chitranayal",
"e": 5791,
"s": 4628,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the maximum// absolute difference between// distinct elements in []arrstatic int MaxAbsDiff(int[] arr, int n){ // Dictionary to store each element // with their occurrence in array Dictionary<int, int> map = new Dictionary<int, int>(); // maxElement and minElement to // store maximum and minimum // distinct element in []arr int maxElement = int.MinValue; int minElement = int.MaxValue; // Traverse []arr and update each // element frequency in Dictionary for(int i = 0; i < n; i++) { if(map.ContainsKey(arr[i])) map[arr[i]] = map[arr[i]] + 1; else map.Add(arr[i], 1); } // Traverse Dictionary and check if // value of any key appears 1 // then update maxElement and // minElement by that key foreach (KeyValuePair<int, int> k in map) { if (k.Value == 1) { maxElement = Math.Max(maxElement, k.Key); minElement = Math.Min(minElement, k.Key); } } // Return absolute difference of // maxElement and minElement return Math.Abs(maxElement - minElement);} // Driver Codepublic static void Main(String[] args){ // Given array []arr int[] arr = { 12, 10, 9, 45, 2, 10, 10, 45, 10 }; int n = arr.Length; // Function call Console.WriteLine(MaxAbsDiff(arr, n));}} // This code is contributed by Princi Singh",
"e": 7412,
"s": 5791,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find the maximum// absolute difference between// distinct elements in arr[]function MaxAbsDiff(arr, n){ // Map to store each element // with their occurrence in array var map = new Map(); // maxElement and minElement to // store maximum and minimum // distinct element in arr[] var maxElement = -1000000000; var minElement = 1000000000; // Traverse arr[] and update each // element frequency in Map for(var i = 0; i < n; i++) { if(map.has(arr[i])) map.set(arr[i], map.get(arr[i])+1) else map.set(arr[i], 1); } // Traverse Map and check if // value of any key appears 1 // then update maxElement and // minElement by that key map.forEach((value, key) => { if (value == 1) { maxElement = Math.max(maxElement, key); minElement = Math.min(minElement, key); } }); // Return absolute difference of // maxElement and minElement return Math.abs(maxElement - minElement);} // Driver Code // Given array arr[]var arr = [12, 10, 9, 45, 2, 10, 10, 45, 10 ];var n = arr.length;// Function calldocument.write( MaxAbsDiff(arr, n)); // This code is contributed by famously.</script>",
"e": 8775,
"s": 7412,
"text": null
},
{
"code": null,
"e": 8778,
"s": 8775,
"text": "10"
},
{
"code": null,
"e": 8825,
"s": 8780,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 8838,
"s": 8825,
"text": "princi singh"
},
{
"code": null,
"e": 8849,
"s": 8838,
"text": "nidhi_biet"
},
{
"code": null,
"e": 8855,
"s": 8849,
"text": "ukasp"
},
{
"code": null,
"e": 8866,
"s": 8855,
"text": "akhilsaini"
},
{
"code": null,
"e": 8875,
"s": 8866,
"text": "famously"
},
{
"code": null,
"e": 8896,
"s": 8875,
"text": "Data Structures-Hash"
},
{
"code": null,
"e": 8909,
"s": 8896,
"text": "Java-HashMap"
},
{
"code": null,
"e": 8916,
"s": 8909,
"text": "Arrays"
},
{
"code": null,
"e": 8932,
"s": 8916,
"text": "Data Structures"
},
{
"code": null,
"e": 8937,
"s": 8932,
"text": "Hash"
},
{
"code": null,
"e": 8956,
"s": 8937,
"text": "School Programming"
},
{
"code": null,
"e": 8972,
"s": 8956,
"text": "Data Structures"
},
{
"code": null,
"e": 8979,
"s": 8972,
"text": "Arrays"
},
{
"code": null,
"e": 8984,
"s": 8979,
"text": "Hash"
},
{
"code": null,
"e": 9082,
"s": 8984,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9114,
"s": 9082,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9139,
"s": 9114,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9186,
"s": 9139,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 9250,
"s": 9186,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9271,
"s": 9250,
"text": "Next Greater Element"
},
{
"code": null,
"e": 9296,
"s": 9271,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 9345,
"s": 9296,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 9377,
"s": 9345,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9433,
"s": 9377,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
Python | Pandas Timestamp.to_julian_date
|
27 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.to_julian_date() function convert the given TimeStamp to a Julian Date. The value for 0 Julian date is noon January 1, 4713 BC.
Syntax :Timestamp.to_julian_date()
Parameters : None
Return : julian date
Example #1: Use Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# convert to julian datets.to_julian_date()
Output :
As we can see in the output, the Timestamp.to_julian_date() function has converted the given Timestamp into the julian date. Example #2: Use Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# convert to julian datets.to_julian_date()
Output :
As we can see in the output, the Timestamp.to_julian_date() function has converted the given Timestamp into the julian date.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 387,
"s": 242,
"text": "Pandas Timestamp.to_julian_date() function convert the given TimeStamp to a Julian Date. The value for 0 Julian date is noon January 1, 4713 BC."
},
{
"code": null,
"e": 422,
"s": 387,
"text": "Syntax :Timestamp.to_julian_date()"
},
{
"code": null,
"e": 440,
"s": 422,
"text": "Parameters : None"
},
{
"code": null,
"e": 461,
"s": 440,
"text": "Return : julian date"
},
{
"code": null,
"e": 560,
"s": 461,
"text": "Example #1: Use Timestamp.to_julian_date() function to convert the given Timestamp to julian date."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)",
"e": 789,
"s": 560,
"text": null
},
{
"code": null,
"e": 798,
"s": 789,
"text": "Output :"
},
{
"code": null,
"e": 901,
"s": 798,
"text": "Now we will use the Timestamp.to_julian_date() function to convert the given Timestamp to julian date."
},
{
"code": "# convert to julian datets.to_julian_date()",
"e": 945,
"s": 901,
"text": null
},
{
"code": null,
"e": 954,
"s": 945,
"text": "Output :"
},
{
"code": null,
"e": 1178,
"s": 954,
"text": "As we can see in the output, the Timestamp.to_julian_date() function has converted the given Timestamp into the julian date. Example #2: Use Timestamp.to_julian_date() function to convert the given Timestamp to julian date."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)",
"e": 1406,
"s": 1178,
"text": null
},
{
"code": null,
"e": 1415,
"s": 1406,
"text": "Output :"
},
{
"code": null,
"e": 1518,
"s": 1415,
"text": "Now we will use the Timestamp.to_julian_date() function to convert the given Timestamp to julian date."
},
{
"code": "# convert to julian datets.to_julian_date()",
"e": 1562,
"s": 1518,
"text": null
},
{
"code": null,
"e": 1571,
"s": 1562,
"text": "Output :"
},
{
"code": null,
"e": 1696,
"s": 1571,
"text": "As we can see in the output, the Timestamp.to_julian_date() function has converted the given Timestamp into the julian date."
},
{
"code": null,
"e": 1720,
"s": 1696,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 1734,
"s": 1720,
"text": "Python-pandas"
},
{
"code": null,
"e": 1741,
"s": 1734,
"text": "Python"
},
{
"code": null,
"e": 1839,
"s": 1741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1871,
"s": 1839,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1898,
"s": 1871,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1929,
"s": 1898,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1950,
"s": 1929,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2006,
"s": 1950,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2029,
"s": 2006,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2071,
"s": 2029,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2113,
"s": 2071,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2152,
"s": 2113,
"text": "Python | datetime.timedelta() function"
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 65
|
02 May, 2019
A computer system implements a 40 bit virtual address, page size of 8 kilobytes, and a 128-entry translation look-aside buffer (TLB) organized into 32 sets each having four ways. Assume that the TLB tag does not store any process id. Theminimum length of the TLB tag in bits is _________(A) 20(B) 10(C) 11(D) 22Answer: (D)Explanation:
Total virtual address size = 40
Since there are 32 sets, set offset = 5
Since page size is 8kilobytes, word offset = 13
Minimum tag size = 40 - 5- 13 = 22
Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File Allocation Methods
Memory Management in Operating System
Logical and Physical Address in Operating System
Different approaches or Structures of Operating Systems
Segmentation in Operating System
Structures of Directory in Operating System
Difference between Internal and External fragmentation
File Access Methods in Operating System
Process Table and Process Control Block (PCB)
Introduction of System Call
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 May, 2019"
},
{
"code": null,
"e": 389,
"s": 54,
"text": "A computer system implements a 40 bit virtual address, page size of 8 kilobytes, and a 128-entry translation look-aside buffer (TLB) organized into 32 sets each having four ways. Assume that the TLB tag does not store any process id. Theminimum length of the TLB tag in bits is _________(A) 20(B) 10(C) 11(D) 22Answer: (D)Explanation:"
},
{
"code": null,
"e": 547,
"s": 389,
"text": "Total virtual address size = 40\n\nSince there are 32 sets, set offset = 5\n\nSince page size is 8kilobytes, word offset = 13\n\nMinimum tag size = 40 - 5- 13 = 22"
},
{
"code": null,
"e": 569,
"s": 547,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 590,
"s": 569,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 616,
"s": 590,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 634,
"s": 616,
"text": "Operating Systems"
},
{
"code": null,
"e": 652,
"s": 634,
"text": "Operating Systems"
},
{
"code": null,
"e": 750,
"s": 652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 774,
"s": 750,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 812,
"s": 774,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 861,
"s": 812,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 917,
"s": 861,
"text": "Different approaches or Structures of Operating Systems"
},
{
"code": null,
"e": 950,
"s": 917,
"text": "Segmentation in Operating System"
},
{
"code": null,
"e": 994,
"s": 950,
"text": "Structures of Directory in Operating System"
},
{
"code": null,
"e": 1049,
"s": 994,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 1089,
"s": 1049,
"text": "File Access Methods in Operating System"
},
{
"code": null,
"e": 1135,
"s": 1089,
"text": "Process Table and Process Control Block (PCB)"
}
] |
Method Hiding in C#
|
19 Mar, 2019
As we already know about polymorphism and method overriding in C#. C# also provides a concept to hide the methods of the base class from derived class, this concept is known as Method Hiding. It is also known as Method Shadowing. In method hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword.
Example:
// C# program to illustrate the// concept of method hidingusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 3"); }} // Derived Classpublic class My_Member : My_Family { // Reimplement the method of the base class // Using new keyword // It hides the method of the base class public new void member() { Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya, "+ "Age: 39 \nName: Rohan, Age: 20 "); }} // Driver Classclass GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}
Output:
Name: Rakesh, Age: 40
Name: Somya, Age: 39
Name: Rohan, Age: 20
Explanation: In the above example, My_Family is the base class and My_Member is a derived class. In both the classes we have the same name method, i.e. member() method. But in the derived class, the member() method is declared with the new keyword. When this method is called, it prints the name and the age of the family members not the total number of family members. Which means when we call the member() method with the help of the derived class object, it hides the same name method present in the base class due to the presence of the new keyword.
Now we will see what will happen if we do not use the new keyword to hide the method of a base class from the derived class. As shown in the below example, when we do not use new keyword compiler will give run the code without giving an error, but it will give warning that if you want to hide a method then uses the new keyword.
Example:
// C# program to illustrate the// concept of method hiding// without using the new keywordusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 3"); }} // Derived Classpublic class My_Member : My_Family { public void member() { Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya, "+ "Age: 39 \nName: Rohan, Age: 20 "); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}
Warning:
prog.cs(18,14): warning CS0108: `My_Member.member()’ hides inherited member `My_Family.member()’. Use the new keyword if hiding was intendedprog.cs(9,14): (Location of the symbol related to previous warning)
Output:
Name: Rakesh, Age: 40
Name: Somya, Age: 39
Name: Rohan, Age: 20
In method hiding, you can also call the hidden method of the base class in the derived class using three different ways and the ways are:
By using the base keyword you can call the hidden method of the base class in your derived class shown in the below example:Example:// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 3"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { // Calling the hidden method of the // base class in a derived class // Using base keyword base.member(); Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya,"+ " Age: 39 \nName: Rohan, Age: 20"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}Output:Total number of family members: 3
Name: Rakesh, Age: 40
Name: Somya, Age: 39
Name: Rohan, Age: 20
Example:
// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 3"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { // Calling the hidden method of the // base class in a derived class // Using base keyword base.member(); Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya,"+ " Age: 39 \nName: Rohan, Age: 20"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}
Output:
Total number of family members: 3
Name: Rakesh, Age: 40
Name: Somya, Age: 39
Name: Rohan, Age: 20
By casting the derived class type to base class type you can invoke the hidden method. As shown in the below example. We know that in inheritance the derived class has all the capabilities of the base class so we can easily cast the object of a derived class into base class type.Example:// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 2"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine("Name: Rakesh, Age: 40 "+ "\nName: Somya, Age: 39"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Invoking the hidden method // By type casting ((My_Family)obj).member(); }}Output:Total number of family members: 2
Example:
// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 2"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine("Name: Rakesh, Age: 40 "+ "\nName: Somya, Age: 39"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Invoking the hidden method // By type casting ((My_Family)obj).member(); }}
Output:
Total number of family members: 2
Instead of using derived class reference variable we use the parent class reference variable for calling the hidden method. It is similar to the above way of calling a hidden method. Here we also type case the object of the derived class in a different syntax.Note: If you try to invoke a hidden method using below syntax,My_Member obj = new My_Family();Here, the compiler will give an error because the object of My_Family class cannot fulfill the duties of My_Member class.Example:// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 2"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine("Name: Rakesh, Age: 40 "+ "\nName: Somya, Age: 39"); }} class GFG { // Main method static public void Main() { // Invoking the hidden method My_Family obj = new My_Member(); obj.member(); }}Output:Total number of family members: 2
Note: If you try to invoke a hidden method using below syntax,
My_Member obj = new My_Family();
Here, the compiler will give an error because the object of My_Family class cannot fulfill the duties of My_Member class.
Example:
// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine("Total number of family members: 2"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine("Name: Rakesh, Age: 40 "+ "\nName: Somya, Age: 39"); }} class GFG { // Main method static public void Main() { // Invoking the hidden method My_Family obj = new My_Member(); obj.member(); }}
Output:
Total number of family members: 2
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Mar, 2019"
},
{
"code": null,
"e": 541,
"s": 54,
"text": "As we already know about polymorphism and method overriding in C#. C# also provides a concept to hide the methods of the base class from derived class, this concept is known as Method Hiding. It is also known as Method Shadowing. In method hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword."
},
{
"code": null,
"e": 550,
"s": 541,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// concept of method hidingusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 3\"); }} // Derived Classpublic class My_Member : My_Family { // Reimplement the method of the base class // Using new keyword // It hides the method of the base class public new void member() { Console.WriteLine(\"Name: Rakesh, Age: 40 \\nName: Somya, \"+ \"Age: 39 \\nName: Rohan, Age: 20 \"); }} // Driver Classclass GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}",
"e": 1353,
"s": 550,
"text": null
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Output:"
},
{
"code": null,
"e": 1429,
"s": 1361,
"text": "Name: Rakesh, Age: 40 \nName: Somya, Age: 39 \nName: Rohan, Age: 20 \n"
},
{
"code": null,
"e": 1983,
"s": 1429,
"text": "Explanation: In the above example, My_Family is the base class and My_Member is a derived class. In both the classes we have the same name method, i.e. member() method. But in the derived class, the member() method is declared with the new keyword. When this method is called, it prints the name and the age of the family members not the total number of family members. Which means when we call the member() method with the help of the derived class object, it hides the same name method present in the base class due to the presence of the new keyword."
},
{
"code": null,
"e": 2313,
"s": 1983,
"text": "Now we will see what will happen if we do not use the new keyword to hide the method of a base class from the derived class. As shown in the below example, when we do not use new keyword compiler will give run the code without giving an error, but it will give warning that if you want to hide a method then uses the new keyword."
},
{
"code": null,
"e": 2322,
"s": 2313,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// concept of method hiding// without using the new keywordusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 3\"); }} // Derived Classpublic class My_Member : My_Family { public void member() { Console.WriteLine(\"Name: Rakesh, Age: 40 \\nName: Somya, \"+ \"Age: 39 \\nName: Rohan, Age: 20 \"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}",
"e": 3022,
"s": 2322,
"text": null
},
{
"code": null,
"e": 3031,
"s": 3022,
"text": "Warning:"
},
{
"code": null,
"e": 3239,
"s": 3031,
"text": "prog.cs(18,14): warning CS0108: `My_Member.member()’ hides inherited member `My_Family.member()’. Use the new keyword if hiding was intendedprog.cs(9,14): (Location of the symbol related to previous warning)"
},
{
"code": null,
"e": 3247,
"s": 3239,
"text": "Output:"
},
{
"code": null,
"e": 3315,
"s": 3247,
"text": "Name: Rakesh, Age: 40 \nName: Somya, Age: 39 \nName: Rohan, Age: 20 \n"
},
{
"code": null,
"e": 3453,
"s": 3315,
"text": "In method hiding, you can also call the hidden method of the base class in the derived class using three different ways and the ways are:"
},
{
"code": null,
"e": 4510,
"s": 3453,
"text": "By using the base keyword you can call the hidden method of the base class in your derived class shown in the below example:Example:// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 3\"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { // Calling the hidden method of the // base class in a derived class // Using base keyword base.member(); Console.WriteLine(\"Name: Rakesh, Age: 40 \\nName: Somya,\"+ \" Age: 39 \\nName: Rohan, Age: 20\"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}Output:Total number of family members: 3\nName: Rakesh, Age: 40 \nName: Somya, Age: 39 \nName: Rohan, Age: 20\n"
},
{
"code": null,
"e": 4519,
"s": 4510,
"text": "Example:"
},
{
"code": "// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 3\"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { // Calling the hidden method of the // base class in a derived class // Using base keyword base.member(); Console.WriteLine(\"Name: Rakesh, Age: 40 \\nName: Somya,\"+ \" Age: 39 \\nName: Rohan, Age: 20\"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Access the method of derived class obj.member(); }}",
"e": 5337,
"s": 4519,
"text": null
},
{
"code": null,
"e": 5345,
"s": 5337,
"text": "Output:"
},
{
"code": null,
"e": 5446,
"s": 5345,
"text": "Total number of family members: 3\nName: Rakesh, Age: 40 \nName: Somya, Age: 39 \nName: Rohan, Age: 20\n"
},
{
"code": null,
"e": 6450,
"s": 5446,
"text": "By casting the derived class type to base class type you can invoke the hidden method. As shown in the below example. We know that in inheritance the derived class has all the capabilities of the base class so we can easily cast the object of a derived class into base class type.Example:// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 2\"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine(\"Name: Rakesh, Age: 40 \"+ \"\\nName: Somya, Age: 39\"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Invoking the hidden method // By type casting ((My_Family)obj).member(); }}Output:Total number of family members: 2\n"
},
{
"code": null,
"e": 6459,
"s": 6450,
"text": "Example:"
},
{
"code": "// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 2\"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine(\"Name: Rakesh, Age: 40 \"+ \"\\nName: Somya, Age: 39\"); }} class GFG { // Main method static public void Main() { // Creating the object of the derived class My_Member obj = new My_Member(); // Invoking the hidden method // By type casting ((My_Family)obj).member(); }}",
"e": 7134,
"s": 6459,
"text": null
},
{
"code": null,
"e": 7142,
"s": 7134,
"text": "Output:"
},
{
"code": null,
"e": 7177,
"s": 7142,
"text": "Total number of family members: 2\n"
},
{
"code": null,
"e": 8280,
"s": 7177,
"text": "Instead of using derived class reference variable we use the parent class reference variable for calling the hidden method. It is similar to the above way of calling a hidden method. Here we also type case the object of the derived class in a different syntax.Note: If you try to invoke a hidden method using below syntax,My_Member obj = new My_Family();Here, the compiler will give an error because the object of My_Family class cannot fulfill the duties of My_Member class.Example:// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 2\"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine(\"Name: Rakesh, Age: 40 \"+ \"\\nName: Somya, Age: 39\"); }} class GFG { // Main method static public void Main() { // Invoking the hidden method My_Family obj = new My_Member(); obj.member(); }}Output:Total number of family members: 2\n"
},
{
"code": null,
"e": 8343,
"s": 8280,
"text": "Note: If you try to invoke a hidden method using below syntax,"
},
{
"code": null,
"e": 8376,
"s": 8343,
"text": "My_Member obj = new My_Family();"
},
{
"code": null,
"e": 8498,
"s": 8376,
"text": "Here, the compiler will give an error because the object of My_Family class cannot fulfill the duties of My_Member class."
},
{
"code": null,
"e": 8507,
"s": 8498,
"text": "Example:"
},
{
"code": "// C# program to illustrate how// to access hidden methodusing System; // Base Classpublic class My_Family { public void member() { Console.WriteLine(\"Total number of family members: 2\"); }} // Derived Classpublic class My_Member : My_Family { public new void member() { Console.WriteLine(\"Name: Rakesh, Age: 40 \"+ \"\\nName: Somya, Age: 39\"); }} class GFG { // Main method static public void Main() { // Invoking the hidden method My_Family obj = new My_Member(); obj.member(); }}",
"e": 9086,
"s": 8507,
"text": null
},
{
"code": null,
"e": 9094,
"s": 9086,
"text": "Output:"
},
{
"code": null,
"e": 9129,
"s": 9094,
"text": "Total number of family members: 2\n"
},
{
"code": null,
"e": 9140,
"s": 9129,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 9143,
"s": 9140,
"text": "C#"
}
] |
Pandas – Rolling mean by time interval
|
24 Oct, 2021
In this article, we will be looking at how to calculate the rolling mean of a dataframe by time interval using Pandas in Python.
Pandas dataframe.rolling() is a function that helps us to make calculations on a rolling window. In other words, we take a window of a fixed size and perform some mathematical calculations on it.
Syntax: DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0).mean()
Parameters :
window : Size of the window. That is how many observations we have to take for the calculation of each window.
min_periods : Least number of observations in a window required to have a value (otherwise result is NA).
center : It is used to set the labels at the center of the window.
win_type : It is used to set the window type.
on : Datetime column of our dataframe on which we have to calculate rolling mean.
axis : integer or string, default 0
Dataset Used: Tesla_Stock
Python3
# import pandas as pdimport pandas as pd
Python3
# importing Datatesla_df = pd.read_csv('Tesla_Stock.csv', index_col='Date', parse_dates=True) # printing the dataFrametesla_df.head(10)
Output:
We will be calculating the rolling mean of the column ‘Close’ of the DataFrame.
Python3
# Updating the dataFrame with just the # column 'Close' as others columns are # of no use right now we have used .to_frame# which converts Series to a DataFrame.tesla_df = tesla_df['Close'].to_frame() # calculating Rolling mean and storing it # into a new column of existing dataFrame# we have set the window as 30 and rest all# parameters are set to default.tesla_df['MA30'] = tesla_df['Close'].rolling(30).mean() # Rolling mean is also called as Moving Average ,# hence we have used the notation MA# and MA30 is the moving average (rolling mean) # of 30 days # printing dataframetesla_df
Output:
The First 29 rows of the column MA30 will have a value NULL and the first non NULL value will be at row 30. Now we will be calculating the rolling mean with a window of 200.
Python3
# calculating Rolling mean and storing it into# a new column of existing dataFrame we have set# the window as 200 and rest all parameters are # set to default.tesla_df['MA200'] = tesla_df['Close'].rolling(200).mean() # Rolling mean is also called as Moving Average, hence# we have used the notation MA and MA200 is the moving# average (rolling mean) of 200 days # printing dataframetesla_df
Output:
For ‘MA200’ the first non-NULL will be at row 200. Now lets plot ‘MA30’ , ‘MA200’ and ‘Close’ for better visualization
Python3
# importing matplotlib moduleimport matplotlib.pyplot as pltplt.style.use('default') # %matplotlib inline: only draw static# images in the notebook%matplotlib inline tesla_df[['Close', 'MA30', 'MA200']].plot( label='tesla', figsize=(16, 8))
OUTPUT:
pandas-dataframe-program
Picked
Python pandas-dataFrame
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
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 182,
"s": 52,
"text": " In this article, we will be looking at how to calculate the rolling mean of a dataframe by time interval using Pandas in Python."
},
{
"code": null,
"e": 378,
"s": 182,
"text": "Pandas dataframe.rolling() is a function that helps us to make calculations on a rolling window. In other words, we take a window of a fixed size and perform some mathematical calculations on it."
},
{
"code": null,
"e": 483,
"s": 378,
"text": "Syntax: DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0).mean()"
},
{
"code": null,
"e": 496,
"s": 483,
"text": "Parameters :"
},
{
"code": null,
"e": 607,
"s": 496,
"text": "window : Size of the window. That is how many observations we have to take for the calculation of each window."
},
{
"code": null,
"e": 713,
"s": 607,
"text": "min_periods : Least number of observations in a window required to have a value (otherwise result is NA)."
},
{
"code": null,
"e": 780,
"s": 713,
"text": "center : It is used to set the labels at the center of the window."
},
{
"code": null,
"e": 826,
"s": 780,
"text": "win_type : It is used to set the window type."
},
{
"code": null,
"e": 908,
"s": 826,
"text": "on : Datetime column of our dataframe on which we have to calculate rolling mean."
},
{
"code": null,
"e": 944,
"s": 908,
"text": "axis : integer or string, default 0"
},
{
"code": null,
"e": 970,
"s": 944,
"text": "Dataset Used: Tesla_Stock"
},
{
"code": null,
"e": 978,
"s": 970,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd",
"e": 1019,
"s": 978,
"text": null
},
{
"code": null,
"e": 1027,
"s": 1019,
"text": "Python3"
},
{
"code": "# importing Datatesla_df = pd.read_csv('Tesla_Stock.csv', index_col='Date', parse_dates=True) # printing the dataFrametesla_df.head(10)",
"e": 1187,
"s": 1027,
"text": null
},
{
"code": null,
"e": 1195,
"s": 1187,
"text": "Output:"
},
{
"code": null,
"e": 1275,
"s": 1195,
"text": "We will be calculating the rolling mean of the column ‘Close’ of the DataFrame."
},
{
"code": null,
"e": 1283,
"s": 1275,
"text": "Python3"
},
{
"code": "# Updating the dataFrame with just the # column 'Close' as others columns are # of no use right now we have used .to_frame# which converts Series to a DataFrame.tesla_df = tesla_df['Close'].to_frame() # calculating Rolling mean and storing it # into a new column of existing dataFrame# we have set the window as 30 and rest all# parameters are set to default.tesla_df['MA30'] = tesla_df['Close'].rolling(30).mean() # Rolling mean is also called as Moving Average ,# hence we have used the notation MA# and MA30 is the moving average (rolling mean) # of 30 days # printing dataframetesla_df",
"e": 1878,
"s": 1283,
"text": null
},
{
"code": null,
"e": 1886,
"s": 1878,
"text": "Output:"
},
{
"code": null,
"e": 2061,
"s": 1886,
"text": "The First 29 rows of the column MA30 will have a value NULL and the first non NULL value will be at row 30. Now we will be calculating the rolling mean with a window of 200."
},
{
"code": null,
"e": 2069,
"s": 2061,
"text": "Python3"
},
{
"code": "# calculating Rolling mean and storing it into# a new column of existing dataFrame we have set# the window as 200 and rest all parameters are # set to default.tesla_df['MA200'] = tesla_df['Close'].rolling(200).mean() # Rolling mean is also called as Moving Average, hence# we have used the notation MA and MA200 is the moving# average (rolling mean) of 200 days # printing dataframetesla_df",
"e": 2462,
"s": 2069,
"text": null
},
{
"code": null,
"e": 2470,
"s": 2462,
"text": "Output:"
},
{
"code": null,
"e": 2590,
"s": 2470,
"text": "For ‘MA200’ the first non-NULL will be at row 200. Now lets plot ‘MA30’ , ‘MA200’ and ‘Close’ for better visualization"
},
{
"code": null,
"e": 2598,
"s": 2590,
"text": "Python3"
},
{
"code": "# importing matplotlib moduleimport matplotlib.pyplot as pltplt.style.use('default') # %matplotlib inline: only draw static# images in the notebook%matplotlib inline tesla_df[['Close', 'MA30', 'MA200']].plot( label='tesla', figsize=(16, 8))",
"e": 2842,
"s": 2598,
"text": null
},
{
"code": null,
"e": 2850,
"s": 2842,
"text": "OUTPUT:"
},
{
"code": null,
"e": 2875,
"s": 2850,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 2882,
"s": 2875,
"text": "Picked"
},
{
"code": null,
"e": 2906,
"s": 2882,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2920,
"s": 2906,
"text": "Python-pandas"
},
{
"code": null,
"e": 2927,
"s": 2920,
"text": "Python"
},
{
"code": null,
"e": 3025,
"s": 2927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3043,
"s": 3025,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3085,
"s": 3043,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3107,
"s": 3085,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3139,
"s": 3107,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3168,
"s": 3139,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3195,
"s": 3168,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3216,
"s": 3195,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3252,
"s": 3216,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3275,
"s": 3252,
"text": "Introduction To PYTHON"
}
] |
Instant plus() method in Java with Examples
|
27 Dec, 2018
In Instant class, there are two types of plus() method depending upon the parameters passed to it.
plus() method of a Instant class used to return a copy of this instant with the specified amount of unit added.If it is not possible to add the amount, because the unit is not supported or for some other reason, an exception is thrown. This instance is immutable and unaffected by this method call.
Syntax:
public Instant plus(long amountToAdd,
TemporalUnit unit)
Parameters: This method accepts two parameters amountToAdd which is the amount of the unit to add to the result, may be negative and unit which is the unit of the amount to add, not null.
Return value: This method returns Instant based on this instant with the specified amount added.
Below programs illustrate the plus() method:Program 1:
// Java program to demonstrate// Instant.plus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create an Instant object Instant instant = Instant.parse("2018-12-30T19:34:50.63Z"); // add 30 DAYS to Instant Instant value = instant.plus(30, ChronoUnit.DAYS); // print result System.out.println("Instant after adding 30 DAYS: " + value); }}
Instant after adding 30 DAYS: 2019-01-29T19:34:50.630Z
plus() method of a Instant class used to return a copy of this instant with the specified amount added to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.
Syntax:
public Instant plus(TemporalAmount amountToAdd)
Parameters: This method accepts one single parameter amountToAdd which is the amount to add, It should not be null.
Return value: This method returns Instant based on this instant with the addition made, not null
Below programs illustrate the plus() method:Program 1:
// Java program to demonstrate// Instant.plus() method import java.time.*;public class GFG { public static void main(String[] args) { // create a Instant object Instant inst = Instant.parse("2018-12-30T19:34:50.63Z"); // add 20 Days to Instant Instant value = inst.plus(Period.ofDays(10)); // print result System.out.println("Instant after adding Days: " + value); }}
Instant after adding Days: 2019-01-09T19:34:50.630Z
References:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#plus(java.time.temporal.TemporalAmount)https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#plus(long, java.time.temporal.TemporalUnit)
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "In Instant class, there are two types of plus() method depending upon the parameters passed to it."
},
{
"code": null,
"e": 426,
"s": 127,
"text": "plus() method of a Instant class used to return a copy of this instant with the specified amount of unit added.If it is not possible to add the amount, because the unit is not supported or for some other reason, an exception is thrown. This instance is immutable and unaffected by this method call."
},
{
"code": null,
"e": 434,
"s": 426,
"text": "Syntax:"
},
{
"code": null,
"e": 512,
"s": 434,
"text": "public Instant plus(long amountToAdd,\n TemporalUnit unit)\n"
},
{
"code": null,
"e": 700,
"s": 512,
"text": "Parameters: This method accepts two parameters amountToAdd which is the amount of the unit to add to the result, may be negative and unit which is the unit of the amount to add, not null."
},
{
"code": null,
"e": 797,
"s": 700,
"text": "Return value: This method returns Instant based on this instant with the specified amount added."
},
{
"code": null,
"e": 852,
"s": 797,
"text": "Below programs illustrate the plus() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Instant.plus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create an Instant object Instant instant = Instant.parse(\"2018-12-30T19:34:50.63Z\"); // add 30 DAYS to Instant Instant value = instant.plus(30, ChronoUnit.DAYS); // print result System.out.println(\"Instant after adding 30 DAYS: \" + value); }}",
"e": 1377,
"s": 852,
"text": null
},
{
"code": null,
"e": 1433,
"s": 1377,
"text": "Instant after adding 30 DAYS: 2019-01-29T19:34:50.630Z\n"
},
{
"code": null,
"e": 1661,
"s": 1433,
"text": "plus() method of a Instant class used to return a copy of this instant with the specified amount added to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface."
},
{
"code": null,
"e": 1669,
"s": 1661,
"text": "Syntax:"
},
{
"code": null,
"e": 1718,
"s": 1669,
"text": "public Instant plus(TemporalAmount amountToAdd)\n"
},
{
"code": null,
"e": 1834,
"s": 1718,
"text": "Parameters: This method accepts one single parameter amountToAdd which is the amount to add, It should not be null."
},
{
"code": null,
"e": 1931,
"s": 1834,
"text": "Return value: This method returns Instant based on this instant with the addition made, not null"
},
{
"code": null,
"e": 1986,
"s": 1931,
"text": "Below programs illustrate the plus() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Instant.plus() method import java.time.*;public class GFG { public static void main(String[] args) { // create a Instant object Instant inst = Instant.parse(\"2018-12-30T19:34:50.63Z\"); // add 20 Days to Instant Instant value = inst.plus(Period.ofDays(10)); // print result System.out.println(\"Instant after adding Days: \" + value); }}",
"e": 2460,
"s": 1986,
"text": null
},
{
"code": null,
"e": 2513,
"s": 2460,
"text": "Instant after adding Days: 2019-01-09T19:34:50.630Z\n"
},
{
"code": null,
"e": 2739,
"s": 2513,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#plus(java.time.temporal.TemporalAmount)https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#plus(long, java.time.temporal.TemporalUnit)"
},
{
"code": null,
"e": 2754,
"s": 2739,
"text": "Java-Functions"
},
{
"code": null,
"e": 2767,
"s": 2754,
"text": "Java-Instant"
},
{
"code": null,
"e": 2785,
"s": 2767,
"text": "Java-time package"
},
{
"code": null,
"e": 2790,
"s": 2785,
"text": "Java"
},
{
"code": null,
"e": 2795,
"s": 2790,
"text": "Java"
},
{
"code": null,
"e": 2893,
"s": 2795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2944,
"s": 2893,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2975,
"s": 2944,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2994,
"s": 2975,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3024,
"s": 2994,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3042,
"s": 3024,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3062,
"s": 3042,
"text": "Collections in Java"
},
{
"code": null,
"e": 3094,
"s": 3062,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3109,
"s": 3094,
"text": "Stream In Java"
},
{
"code": null,
"e": 3133,
"s": 3109,
"text": "Singleton Class in Java"
}
] |
Dilated Convolution
|
02 Mar, 2022
Prerequisite: Convolutional Neural Networks
Dilated Convolution: It is a technique that expands the kernel (input) by inserting holes between its consecutive elements. In simpler terms, it is the same as convolution but it involves pixel skipping, so as to cover a larger area of the input.
An additional parameter l (dilation factor) tells how much the input is expanded. In other words, based on the value of this parameter, (l-1) pixels are skipped in the kernel. Fig 1 depicts the difference between normal vs dilated convolution. In essence, normal convolution is just a 1-dilated convolution.
Fig 1: Normal Convolution vs Dilated Convolution
Intuition:
Dilated convolution helps expand the area of the input image covered without pooling. The objective is to cover more information from the output obtained with every convolution operation. This method offers a wider field of view at the same computational cost. We determine the value of the dilation factor (l) by seeing how much information is obtained with each convolution on varying values of l.
By using this method, we are able to obtain more information without increasing the number of kernel parameters. In Fig 1, the image on the left depicts dilated convolution. On keeping the value of l = 2, we skip 1 pixel (l – 1 pixel) while mapping the filter onto the input, thus covering more information in each step.
Formula Involved:
where,
F(s) = Input
k(t) = Applied Filter
*l = l-dilated convolution
(F*lk)(p) = Output
Advantages of Dilated Convolution:
Using this method rather than normal convolution is better as:
Larger receptive field (i.e. no loss of coverage)Computationally efficient (as it provides a larger coverage on the same computation cost)Lesser Memory consumption (as it skips the pooling step) implementationNo loss of resolution of the output image (as we dilate instead of performing pooling)Structure of this convolution helps in maintaining the order of the data.
Larger receptive field (i.e. no loss of coverage)
Computationally efficient (as it provides a larger coverage on the same computation cost)
Lesser Memory consumption (as it skips the pooling step) implementation
No loss of resolution of the output image (as we dilate instead of performing pooling)
Structure of this convolution helps in maintaining the order of the data.
Code Implementation:
Python3
import numpy as npimport tensorflow as tfimport sysfrom scipy.signal import convolve2d np.random.seed(678)tf.random.set_seed(6789)sess = tf.compat.v1.Session() # Initializing a 9x9 matrix of zeros.mat_size = 9matrix = np.zeros((mat_size,mat_size)).astype(np.float32) # Assigning 1's in the middle of matrix# to create a random input matrixfor x in range(4,7): for y in range(3,6): matrix[y,x] = 1 # Creating a random kernel for testkernel = np.array([ [1,2,3], [4,5,6], [7,8,9]]).astype(np.float32) print("Original Matrix Shape : ",matrix.shape)print(matrix)print('\n')print("Original kernel Shape : ",kernel.shape)print(kernel) # self-initializing a dilated kernel.# ======[dilation factor = 3]======dilated_kernel = np.array([ [1,0,0,2,0,0,3], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [4,0,0,5,0,0,6], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [7,0,0,8,0,0,9]]) print('\n')print("Dilated kernel Shape : ",dilated_kernel.shape)print(dilated_kernel) print('\n')print("DILATED CONVOLUTION RESULTS [Dilation Factor = 3]")output = convolve2d(matrix,dilated_kernel,mode='valid')print("Numpy Results Shape: ",output.shape)print(output)
Output
The following output is obtained from the above code.
Output
The output obtained is for a dilation factor of 3. For more experimentation, you can initialize the dilated_kernel with different values of the Dilation factor and observe the changes in the output obtained.
rkbhola5
ddeevviissaavviittaa
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
Support Vector Machine Algorithm
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 72,
"s": 28,
"text": "Prerequisite: Convolutional Neural Networks"
},
{
"code": null,
"e": 320,
"s": 72,
"text": "Dilated Convolution: It is a technique that expands the kernel (input) by inserting holes between its consecutive elements. In simpler terms, it is the same as convolution but it involves pixel skipping, so as to cover a larger area of the input. "
},
{
"code": null,
"e": 628,
"s": 320,
"text": "An additional parameter l (dilation factor) tells how much the input is expanded. In other words, based on the value of this parameter, (l-1) pixels are skipped in the kernel. Fig 1 depicts the difference between normal vs dilated convolution. In essence, normal convolution is just a 1-dilated convolution."
},
{
"code": null,
"e": 677,
"s": 628,
"text": "Fig 1: Normal Convolution vs Dilated Convolution"
},
{
"code": null,
"e": 689,
"s": 677,
"text": "Intuition: "
},
{
"code": null,
"e": 1091,
"s": 689,
"text": "Dilated convolution helps expand the area of the input image covered without pooling. The objective is to cover more information from the output obtained with every convolution operation. This method offers a wider field of view at the same computational cost. We determine the value of the dilation factor (l) by seeing how much information is obtained with each convolution on varying values of l. "
},
{
"code": null,
"e": 1413,
"s": 1091,
"text": "By using this method, we are able to obtain more information without increasing the number of kernel parameters. In Fig 1, the image on the left depicts dilated convolution. On keeping the value of l = 2, we skip 1 pixel (l – 1 pixel) while mapping the filter onto the input, thus covering more information in each step. "
},
{
"code": null,
"e": 1432,
"s": 1413,
"text": "Formula Involved: "
},
{
"code": null,
"e": 1521,
"s": 1432,
"text": "where,\nF(s) = Input \nk(t) = Applied Filter\n*l = l-dilated convolution\n(F*lk)(p) = Output"
},
{
"code": null,
"e": 1559,
"s": 1521,
"text": "Advantages of Dilated Convolution: "
},
{
"code": null,
"e": 1623,
"s": 1559,
"text": "Using this method rather than normal convolution is better as: "
},
{
"code": null,
"e": 1993,
"s": 1623,
"text": "Larger receptive field (i.e. no loss of coverage)Computationally efficient (as it provides a larger coverage on the same computation cost)Lesser Memory consumption (as it skips the pooling step) implementationNo loss of resolution of the output image (as we dilate instead of performing pooling)Structure of this convolution helps in maintaining the order of the data. "
},
{
"code": null,
"e": 2043,
"s": 1993,
"text": "Larger receptive field (i.e. no loss of coverage)"
},
{
"code": null,
"e": 2133,
"s": 2043,
"text": "Computationally efficient (as it provides a larger coverage on the same computation cost)"
},
{
"code": null,
"e": 2205,
"s": 2133,
"text": "Lesser Memory consumption (as it skips the pooling step) implementation"
},
{
"code": null,
"e": 2292,
"s": 2205,
"text": "No loss of resolution of the output image (as we dilate instead of performing pooling)"
},
{
"code": null,
"e": 2367,
"s": 2292,
"text": "Structure of this convolution helps in maintaining the order of the data. "
},
{
"code": null,
"e": 2389,
"s": 2367,
"text": "Code Implementation: "
},
{
"code": null,
"e": 2397,
"s": 2389,
"text": "Python3"
},
{
"code": "import numpy as npimport tensorflow as tfimport sysfrom scipy.signal import convolve2d np.random.seed(678)tf.random.set_seed(6789)sess = tf.compat.v1.Session() # Initializing a 9x9 matrix of zeros.mat_size = 9matrix = np.zeros((mat_size,mat_size)).astype(np.float32) # Assigning 1's in the middle of matrix# to create a random input matrixfor x in range(4,7): for y in range(3,6): matrix[y,x] = 1 # Creating a random kernel for testkernel = np.array([ [1,2,3], [4,5,6], [7,8,9]]).astype(np.float32) print(\"Original Matrix Shape : \",matrix.shape)print(matrix)print('\\n')print(\"Original kernel Shape : \",kernel.shape)print(kernel) # self-initializing a dilated kernel.# ======[dilation factor = 3]======dilated_kernel = np.array([ [1,0,0,2,0,0,3], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [4,0,0,5,0,0,6], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [7,0,0,8,0,0,9]]) print('\\n')print(\"Dilated kernel Shape : \",dilated_kernel.shape)print(dilated_kernel) print('\\n')print(\"DILATED CONVOLUTION RESULTS [Dilation Factor = 3]\")output = convolve2d(matrix,dilated_kernel,mode='valid')print(\"Numpy Results Shape: \",output.shape)print(output)",
"e": 3554,
"s": 2397,
"text": null
},
{
"code": null,
"e": 3563,
"s": 3554,
"text": " Output "
},
{
"code": null,
"e": 3619,
"s": 3563,
"text": "The following output is obtained from the above code. "
},
{
"code": null,
"e": 3626,
"s": 3619,
"text": "Output"
},
{
"code": null,
"e": 3837,
"s": 3628,
"text": "The output obtained is for a dilation factor of 3. For more experimentation, you can initialize the dilated_kernel with different values of the Dilation factor and observe the changes in the output obtained. "
},
{
"code": null,
"e": 3846,
"s": 3837,
"text": "rkbhola5"
},
{
"code": null,
"e": 3867,
"s": 3846,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 3884,
"s": 3867,
"text": "Machine Learning"
},
{
"code": null,
"e": 3891,
"s": 3884,
"text": "Python"
},
{
"code": null,
"e": 3908,
"s": 3891,
"text": "Machine Learning"
},
{
"code": null,
"e": 4006,
"s": 3908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4042,
"s": 4006,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4083,
"s": 4042,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4107,
"s": 4083,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4140,
"s": 4107,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4191,
"s": 4140,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 4219,
"s": 4191,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4269,
"s": 4219,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4291,
"s": 4269,
"text": "Python map() function"
},
{
"code": null,
"e": 4309,
"s": 4291,
"text": "Python Dictionary"
}
] |
Iterative Letter Combinations of a Phone Number
|
10 Dec, 2021
Given an integer array containing digits from [0, 9], the task is to print all possible letter combinations that the numbers could represent.
A mapping of digit to letters (just like on the telephone buttons) is being followed. Note that 0 and 1 do not map to any letters. All the mapping are shown in the image below:
Example:
Input: arr[] = {2, 3} Output: ad ae af bd be bf cd ce cf
Input: arr[] = {9} Output: w x y z
Approach: Now let us think how we would approach this problem without doing it in an iterative way. A recursive solution is intuitive and common. We keep adding each possible letter recursively and this will generate all the possible strings.Let us think about how we can build an iterative solution using the recursive one. Recursion is possible through the use of a stack. So if we use a stack instead of a recursive function will that be an iterative solution? One could say so speaking technically but we then aren’t really doing anything different in terms of logic.
A Stack is a LIFO DS. Can we use another Data structure? What will be the difference if we use a FIFO DS? Let’s say a queue. Since BFS is done by queue and DFS by stack is there any difference between the two?The difference between DFS and BFS is similar to this question. In DFS we will find each path possible in the tree one by one. It will perform all steps for a path first whereas BFS will build all paths together one step at a time.So, a queue would work perfectly for this question. The only difference between the two algorithms using queue and stack will be the way in which they are formed. Stack will form all strings completely one by one whereas the queue will form all the strings together i.e. after x number of passes all the strings will have a length of x.
For example:
If the given number is "23",
then using queue, the letter combinations
obtained will be:
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
and using stack, the letter combinations obtained will
be:
["cf","ce","cd","bf","be","bd","af","ae","ad"].
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return a vector that contains// all the generated letter combinationsvector<string> letterCombinationsUtil(const int number[], int n, const string table[]){ // To store the generated letter combinations vector<string> list; queue<string> q; q.push(""); while (!q.empty()) { string s = q.front(); q.pop(); // If complete word is generated // push it in the list if (s.length() == n) list.push_back(s); else // Try all possible letters for current digit // in number[] for (auto letter : table[number[s.length()]]) q.push(s + letter); } // Return the generated list return list;} // Function that creates the mapping and// calls letterCombinationsUtilvoid letterCombinations(const int number[], int n){ // table[i] stores all characters that // corresponds to ith digit in phone string table[10] = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; vector<string> list = letterCombinationsUtil(number, n, table); // Print the contents of the vector for (auto word : list) cout << word << " "; return;} // Driver codeint main(){ int number[] = { 2, 3 }; int n = sizeof(number) / sizeof(number[0]); // Function call letterCombinations(number, n); return 0;}
// Java implementation of the approachimport java.io.*;import java.util.*; class GFG { // Function to return a vector that contains // all the generated letter combinations static ArrayList<String> letterCombinationsUtil(int[] number, int n, String[] table) { // To store the generated letter combinations ArrayList<String> list = new ArrayList<>(); Queue<String> q = new LinkedList<>(); q.add(""); while (!q.isEmpty()) { String s = q.remove(); // If complete word is generated // push it in the list if (s.length() == n) list.add(s); else { String val = table[number[s.length()]]; for (int i = 0; i < val.length(); i++) { q.add(s + val.charAt(i)); } } } return list; } // Function that creates the mapping and // calls letterCombinationsUtil static void letterCombinations(int[] number, int n) { // table[i] stores all characters that // corresponds to ith digit in phone String[] table = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; ArrayList<String> list = letterCombinationsUtil(number, n, table); // Print the contents of the list for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + " "); } } // Driver code public static void main(String args[]) { int[] number = { 2, 3 }; int n = number.length; // Function call letterCombinations(number, n); }} // This code is contributed by rachana soma
# Python3 implementation of the approachfrom collections import deque # Function to return a list that contains# all the generated letter combinations def letterCombinationsUtil(number, n, table): list = [] q = deque() q.append("") while len(q) != 0: s = q.pop() # If complete word is generated # push it in the list if len(s) == n: list.append(s) else: # Try all possible letters for current digit # in number[] for letter in table[number[len(s)]]: q.append(s + letter) # Return the generated list return list # Function that creates the mapping and# calls letterCombinationsUtildef letterCombinations(number, n): # table[i] stores all characters that # corresponds to ith digit in phone table = ["0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] list = letterCombinationsUtil(number, n, table) s = "" for word in list: s += word + " " print(s) return # Driver codenumber = [2, 3]n = len(number) # Function callletterCombinations(number, n)
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Function to return a vector that contains // all the generated letter combinations static List<String> letterCombinationsUtil(int[] number, int n, String[] table) { // To store the generated letter combinations List<String> list = new List<String>(); Queue<String> q = new Queue<String>(); q.Enqueue(""); while (q.Count != 0) { String s = q.Dequeue(); // If complete word is generated // push it in the list if (s.Length == n) list.Add(s); else { String val = table[number[s.Length]]; for (int i = 0; i < val.Length; i++) { q.Enqueue(s + val[i]); } } } return list; } // Function that creates the mapping and // calls letterCombinationsUtil static void letterCombinations(int[] number, int n) { // table[i] stores all characters that // corresponds to ith digit in phone String[] table = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; List<String> list = letterCombinationsUtil(number, n, table); // Print the contents of the list for (int i = 0; i < list.Count; i++) { Console.Write(list[i] + " "); } } // Driver code public static void Main(String[] args) { int[] number = { 2, 3 }; int n = number.Length; // Function call letterCombinations(number, n); }} // This code is contributed by Princi Singh
ad ae af bd be bf cd ce cf
Time Complexity: O(4^n) as we get set of all possible numbers of length n. In worst case, for each number there can be 4 possibilities.Auxiliary Space: O(4^n)
rachana soma
princi singh
darshan4450
samvarshney
pankajsharmagfg
saurabh1990aror
ashutoshsinghgeeksforgeeks
amartyaghoshgfg
Microsoft
Algorithms
Articles
C++ Programs
Python Programs
Queue
Microsoft
Queue
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 197,
"s": 54,
"text": "Given an integer array containing digits from [0, 9], the task is to print all possible letter combinations that the numbers could represent. "
},
{
"code": null,
"e": 375,
"s": 197,
"text": "A mapping of digit to letters (just like on the telephone buttons) is being followed. Note that 0 and 1 do not map to any letters. All the mapping are shown in the image below: "
},
{
"code": null,
"e": 385,
"s": 375,
"text": "Example: "
},
{
"code": null,
"e": 442,
"s": 385,
"text": "Input: arr[] = {2, 3} Output: ad ae af bd be bf cd ce cf"
},
{
"code": null,
"e": 478,
"s": 442,
"text": "Input: arr[] = {9} Output: w x y z "
},
{
"code": null,
"e": 1050,
"s": 478,
"text": "Approach: Now let us think how we would approach this problem without doing it in an iterative way. A recursive solution is intuitive and common. We keep adding each possible letter recursively and this will generate all the possible strings.Let us think about how we can build an iterative solution using the recursive one. Recursion is possible through the use of a stack. So if we use a stack instead of a recursive function will that be an iterative solution? One could say so speaking technically but we then aren’t really doing anything different in terms of logic."
},
{
"code": null,
"e": 1827,
"s": 1050,
"text": "A Stack is a LIFO DS. Can we use another Data structure? What will be the difference if we use a FIFO DS? Let’s say a queue. Since BFS is done by queue and DFS by stack is there any difference between the two?The difference between DFS and BFS is similar to this question. In DFS we will find each path possible in the tree one by one. It will perform all steps for a path first whereas BFS will build all paths together one step at a time.So, a queue would work perfectly for this question. The only difference between the two algorithms using queue and stack will be the way in which they are formed. Stack will form all strings completely one by one whereas the queue will form all the strings together i.e. after x number of passes all the strings will have a length of x."
},
{
"code": null,
"e": 1840,
"s": 1827,
"text": "For example:"
},
{
"code": null,
"e": 2095,
"s": 1840,
"text": "If the given number is \"23\", \nthen using queue, the letter combinations \nobtained will be:\n[\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"] \nand using stack, the letter combinations obtained will \nbe:\n[\"cf\",\"ce\",\"cd\",\"bf\",\"be\",\"bd\",\"af\",\"ae\",\"ad\"]."
},
{
"code": null,
"e": 2146,
"s": 2095,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2150,
"s": 2146,
"text": "C++"
},
{
"code": null,
"e": 2155,
"s": 2150,
"text": "Java"
},
{
"code": null,
"e": 2163,
"s": 2155,
"text": "Python3"
},
{
"code": null,
"e": 2166,
"s": 2163,
"text": "C#"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return a vector that contains// all the generated letter combinationsvector<string> letterCombinationsUtil(const int number[], int n, const string table[]){ // To store the generated letter combinations vector<string> list; queue<string> q; q.push(\"\"); while (!q.empty()) { string s = q.front(); q.pop(); // If complete word is generated // push it in the list if (s.length() == n) list.push_back(s); else // Try all possible letters for current digit // in number[] for (auto letter : table[number[s.length()]]) q.push(s + letter); } // Return the generated list return list;} // Function that creates the mapping and// calls letterCombinationsUtilvoid letterCombinations(const int number[], int n){ // table[i] stores all characters that // corresponds to ith digit in phone string table[10] = { \"0\", \"1\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\" }; vector<string> list = letterCombinationsUtil(number, n, table); // Print the contents of the vector for (auto word : list) cout << word << \" \"; return;} // Driver codeint main(){ int number[] = { 2, 3 }; int n = sizeof(number) / sizeof(number[0]); // Function call letterCombinations(number, n); return 0;}",
"e": 3721,
"s": 2166,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*;import java.util.*; class GFG { // Function to return a vector that contains // all the generated letter combinations static ArrayList<String> letterCombinationsUtil(int[] number, int n, String[] table) { // To store the generated letter combinations ArrayList<String> list = new ArrayList<>(); Queue<String> q = new LinkedList<>(); q.add(\"\"); while (!q.isEmpty()) { String s = q.remove(); // If complete word is generated // push it in the list if (s.length() == n) list.add(s); else { String val = table[number[s.length()]]; for (int i = 0; i < val.length(); i++) { q.add(s + val.charAt(i)); } } } return list; } // Function that creates the mapping and // calls letterCombinationsUtil static void letterCombinations(int[] number, int n) { // table[i] stores all characters that // corresponds to ith digit in phone String[] table = { \"0\", \"1\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\" }; ArrayList<String> list = letterCombinationsUtil(number, n, table); // Print the contents of the list for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + \" \"); } } // Driver code public static void main(String args[]) { int[] number = { 2, 3 }; int n = number.length; // Function call letterCombinations(number, n); }} // This code is contributed by rachana soma",
"e": 5488,
"s": 3721,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom collections import deque # Function to return a list that contains# all the generated letter combinations def letterCombinationsUtil(number, n, table): list = [] q = deque() q.append(\"\") while len(q) != 0: s = q.pop() # If complete word is generated # push it in the list if len(s) == n: list.append(s) else: # Try all possible letters for current digit # in number[] for letter in table[number[len(s)]]: q.append(s + letter) # Return the generated list return list # Function that creates the mapping and# calls letterCombinationsUtildef letterCombinations(number, n): # table[i] stores all characters that # corresponds to ith digit in phone table = [\"0\", \"1\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"] list = letterCombinationsUtil(number, n, table) s = \"\" for word in list: s += word + \" \" print(s) return # Driver codenumber = [2, 3]n = len(number) # Function callletterCombinations(number, n)",
"e": 6615,
"s": 5488,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Function to return a vector that contains // all the generated letter combinations static List<String> letterCombinationsUtil(int[] number, int n, String[] table) { // To store the generated letter combinations List<String> list = new List<String>(); Queue<String> q = new Queue<String>(); q.Enqueue(\"\"); while (q.Count != 0) { String s = q.Dequeue(); // If complete word is generated // push it in the list if (s.Length == n) list.Add(s); else { String val = table[number[s.Length]]; for (int i = 0; i < val.Length; i++) { q.Enqueue(s + val[i]); } } } return list; } // Function that creates the mapping and // calls letterCombinationsUtil static void letterCombinations(int[] number, int n) { // table[i] stores all characters that // corresponds to ith digit in phone String[] table = { \"0\", \"1\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\" }; List<String> list = letterCombinationsUtil(number, n, table); // Print the contents of the list for (int i = 0; i < list.Count; i++) { Console.Write(list[i] + \" \"); } } // Driver code public static void Main(String[] args) { int[] number = { 2, 3 }; int n = number.Length; // Function call letterCombinations(number, n); }} // This code is contributed by Princi Singh",
"e": 8350,
"s": 6615,
"text": null
},
{
"code": null,
"e": 8378,
"s": 8350,
"text": "ad ae af bd be bf cd ce cf "
},
{
"code": null,
"e": 8537,
"s": 8378,
"text": "Time Complexity: O(4^n) as we get set of all possible numbers of length n. In worst case, for each number there can be 4 possibilities.Auxiliary Space: O(4^n)"
},
{
"code": null,
"e": 8550,
"s": 8537,
"text": "rachana soma"
},
{
"code": null,
"e": 8563,
"s": 8550,
"text": "princi singh"
},
{
"code": null,
"e": 8575,
"s": 8563,
"text": "darshan4450"
},
{
"code": null,
"e": 8587,
"s": 8575,
"text": "samvarshney"
},
{
"code": null,
"e": 8603,
"s": 8587,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 8619,
"s": 8603,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 8646,
"s": 8619,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 8662,
"s": 8646,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 8672,
"s": 8662,
"text": "Microsoft"
},
{
"code": null,
"e": 8683,
"s": 8672,
"text": "Algorithms"
},
{
"code": null,
"e": 8692,
"s": 8683,
"text": "Articles"
},
{
"code": null,
"e": 8705,
"s": 8692,
"text": "C++ Programs"
},
{
"code": null,
"e": 8721,
"s": 8705,
"text": "Python Programs"
},
{
"code": null,
"e": 8727,
"s": 8721,
"text": "Queue"
},
{
"code": null,
"e": 8737,
"s": 8727,
"text": "Microsoft"
},
{
"code": null,
"e": 8743,
"s": 8737,
"text": "Queue"
},
{
"code": null,
"e": 8754,
"s": 8743,
"text": "Algorithms"
}
] |
IntroSort or Introspective sort
|
25 Nov, 2021
Introsort(Introspective sort) is a comparison based sort that consists of three sorting phases. They are Quicksort, Heapsort, and Insertion sort. Basic concepts of Introsort and the C++ code are available hereThe following section shows how the Introsort algorithm is formulated, after reviewing the pros and cons of the respective algorithms.
Quicksort The Quicksort is an efficient sorting algorithm but has the worst-case performance of O(N ^ 2) comparisons with O(N) auxiliary space. This worst-case complexity depends on two phases of the Quicksort algorithm. 1. Choosing the pivot element 2. Recursion depth during the course of the algorithmHeapsort Heapsort has O(N log N) worst-case time complexity, which is much better than the worst case of Quicksort. So, is it evident that Heapsort is the best? No, the secret of Quicksort is that it does not swap already elements that are already in order, which is unnecessary, whereas with the Heapsort, even if all of the data is already sorted, the algorithm swaps all of the elements to order the array. Also, by choosing the optimal pivot, the worst-case of O(N ^ 2) can be avoided in quicksort. But, the swapping will pay more time in the case of Heapsort that is unavoidable. Hence, Quicksort outperforms Heapsort.The best things about Heapsort is that, if the recursion depth becomes too large like (log N), the worst case complexity would be still O(N log N). Mergesort The Mergesort has the worst case complexity only as O(N log N). Mergesort can work well on any type of data sets irrespective of its size whereas the Quicksort cannot work well with large data sets. But, Mergesort is not in-place whereas Quicksort is in-place, and that plays a vital role in here. Mergesort goes well with LinkedLists whereas Quicksort goes well with arrays. The locality of reference is better with Quicksort, whereas with Mergesort it is bad. So, for conventional purposes, having memory constraints in hand, Quicksort outperforms Mergesort. Insertion sort The main advantage of the insertion sort is its simplicity. It also exhibits a good performance when dealing with a small list. The insertion sort is an in-place sorting algorithm so the space requirement is minimal. The disadvantage of the insertion sort is that it does not perform as well as the other sorting algorithms when the size of the data gets larger.
Quicksort The Quicksort is an efficient sorting algorithm but has the worst-case performance of O(N ^ 2) comparisons with O(N) auxiliary space. This worst-case complexity depends on two phases of the Quicksort algorithm. 1. Choosing the pivot element 2. Recursion depth during the course of the algorithm
Heapsort Heapsort has O(N log N) worst-case time complexity, which is much better than the worst case of Quicksort. So, is it evident that Heapsort is the best? No, the secret of Quicksort is that it does not swap already elements that are already in order, which is unnecessary, whereas with the Heapsort, even if all of the data is already sorted, the algorithm swaps all of the elements to order the array. Also, by choosing the optimal pivot, the worst-case of O(N ^ 2) can be avoided in quicksort. But, the swapping will pay more time in the case of Heapsort that is unavoidable. Hence, Quicksort outperforms Heapsort.The best things about Heapsort is that, if the recursion depth becomes too large like (log N), the worst case complexity would be still O(N log N).
Mergesort The Mergesort has the worst case complexity only as O(N log N). Mergesort can work well on any type of data sets irrespective of its size whereas the Quicksort cannot work well with large data sets. But, Mergesort is not in-place whereas Quicksort is in-place, and that plays a vital role in here. Mergesort goes well with LinkedLists whereas Quicksort goes well with arrays. The locality of reference is better with Quicksort, whereas with Mergesort it is bad. So, for conventional purposes, having memory constraints in hand, Quicksort outperforms Mergesort.
Insertion sort The main advantage of the insertion sort is its simplicity. It also exhibits a good performance when dealing with a small list. The insertion sort is an in-place sorting algorithm so the space requirement is minimal. The disadvantage of the insertion sort is that it does not perform as well as the other sorting algorithms when the size of the data gets larger.
Here is how Introsort is formulated: Choosing the right sorting algorithm depends on the occasion where the sorting algorithm is being used. There are a good number of sorting algorithms in hand already that has pros and cons of its own. So, to get a better sorting algorithm, the solution is to tweak the existing algorithms and produce a new sorting algorithm that works better. There are a lot of hybrid algorithms, that outperforms the general sorting algorithms. One such is the Introsort. The best versions of Quicksort are competitive with both heap sort and merge sort on the vast majority of inputs. Rarely Quicksort has the worst case of O(N ^ 2) running time and O(N) stack usage. Both Heapsort and Mergesort have O(N log N) worst-case running time, together with a stack usage of O(1) for Heapsort and O(log N) for Mergesort respectively. Also, Insertion sort performs better than any of the above algorithms if the data set is small.Combining all the pros of the sorting algorithms, Introsort behaves based on the data set.
If the number of elements in the input gets fewer, the Introsort performs Insertion sort for the input.Having the least number of comparisons(Quicksort) in mind, for splitting the array by finding the pivot element, Quicksort is used. Quoted earlier, the worst case of Quicksort is based on the two phases and here is how we can fix them.Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot elementRecursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N).
If the number of elements in the input gets fewer, the Introsort performs Insertion sort for the input.
Having the least number of comparisons(Quicksort) in mind, for splitting the array by finding the pivot element, Quicksort is used. Quoted earlier, the worst case of Quicksort is based on the two phases and here is how we can fix them.Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot elementRecursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N).
Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot elementRecursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N).
Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot element
Recursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N).
How does depthLimit work? depthLimit represents maximum depth for recursion. It is typically chosen as log of length of input array (please refer below implementation). The idea is to ensure that the worst case time complexity remains O(N log N). Note that the worst-case time complexity of HeapSort is O(N log N).
Why is Mergesort not used? As the arrays are being dealt with the in-place concept where Quicksort outperforms Mergesort, we are not using Mergesort.
Can Introsort be applied everywhere?
If the data won’t fit in an array, Introsort cannot be used.Furthermore, like Quicksort and Heapsort, Introsort is not stable. When a stable sort is needed, Introsort cannot be applied.
If the data won’t fit in an array, Introsort cannot be used.
Furthermore, like Quicksort and Heapsort, Introsort is not stable. When a stable sort is needed, Introsort cannot be applied.
Is Introsort the only hybrid sorting algorithm? No. There are other hybrid sorting algorithms like Hybrid Mergesort, Tim sort, Insertion-Merge hybrid.Comparison of Heapsort, Insertion sort, Quicksort, Introsort while sorting 6000 elements(in milliseconds).
Pseudocode:
sort(A : array):
depthLimit = 2xfloor(log(length(A)))
introsort(A, depthLimit)
introsort(A, depthLimit):
n = length(A)
if n<=16:
insertionSort(A)
if depthLimit == 0:
heapsort(A)
else:
// using quick sort, the
// partition point is found
p = partition(A)
introsort(A[0:p-1], depthLimit - 1)
introsort(A[p+1:n], depthLimit - 1)
Time Complexity: Worst-case performance: O(nlogn) (better than Quicksort) Average-case performance: O(nlogn)In the Quicksort phase, the pivot can either be chosen using the median-of-3 concept or last element of the array. For data that has a huge number of elements, median-of-3 concept slows down the running time of the Quicksort.In the example described below, the quicksort algorithm calculates the pivot element based on the median-of-3 concept.
Example:
C++
Java
Python3
C#
// C++ implementation of Introsort algorithm #include <bits/stdc++.h>using namespace std; // A utility function to swap the values pointed by// the two pointersvoid swapValue(int* a, int* b){ int* temp = a; a = b; b = temp; return;} /* Function to sort an array using insertion sort*/void InsertionSort(int arr[], int* begin, int* end){ // Get the left and the right index of the subarray // to be sorted int left = begin - arr; int right = end - arr; for (int i = left + 1; i <= right; i++) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= left && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } return;} // A function to partition the array and return// the partition pointint* Partition(int arr[], int low, int high){ int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { // increment index of smaller element i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (arr + i + 1);} // A function that find the middle of the// values pointed by the pointers a, b, c// and return that pointerint* MedianOfThree(int* a, int* b, int* c){ if (*a < *b && *b < *c) return (b); if (*a < *c && *c <= *b) return (c); if (*b <= *a && *a < *c) return (a); if (*b < *c && *c <= *a) return (c); if (*c <= *a && *a < *b) return (a); if (*c <= *b && *b <= *a) return (b);} // A Utility function to perform intro sortvoid IntrosortUtil(int arr[], int* begin, int* end, int depthLimit){ // Count the number of elements int size = end - begin; // If partition size is low then do insertion sort if (size < 16) { InsertionSort(arr, begin, end); return; } // If the depth is zero use heapsort if (depthLimit == 0) { make_heap(begin, end + 1); sort_heap(begin, end + 1); return; } // Else use a median-of-three concept to // find a good pivot int* pivot = MedianOfThree(begin, begin + size / 2, end); // Swap the values pointed by the two pointers swapValue(pivot, end); // Perform Quick Sort int* partitionPoint = Partition(arr, begin - arr, end - arr); IntrosortUtil(arr, begin, partitionPoint - 1, depthLimit - 1); IntrosortUtil(arr, partitionPoint + 1, end, depthLimit - 1); return;} /* Implementation of introsort*/void Introsort(int arr[], int* begin, int* end){ int depthLimit = 2 * log(end - begin); // Perform a recursive Introsort IntrosortUtil(arr, begin, end, depthLimit); return;} // A utility function ot print an array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " \n"[i + 1 == n];} // Driver program to test Introsortint main(){ int arr[] = { 2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); // Pass the array, the pointer to the first element and // the pointer to the last element Introsort(arr, arr, arr + n - 1); printArray(arr, n); return (0);}
// Java implementation of Introsort algorithm import java.io.IOException; public class Introsort { // the actual data that has to be sorted private int a[]; // the number of elements in the data private int n; // Constructor to initialize the size // of the data Introsort(int n) { a = new int[n]; this.n = 0; } // The utility function to insert the data private void dataAppend(int temp) { a[n] = temp; n++; } // The utility function to swap two elements private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // To maxHeap a subtree rooted with node i which is // an index in a[]. heapN is size of heap private void maxHeap(int i, int heapN, int begin) { int temp = a[begin + i - 1]; int child; while (i <= heapN / 2) { child = 2 * i; if (child < heapN && a[begin + child - 1] < a[begin + child]) child++; if (temp >= a[begin + child - 1]) break; a[begin + i - 1] = a[begin + child - 1]; i = child; } a[begin + i - 1] = temp; } // Function to build the heap (rearranging the array) private void heapify(int begin, int end, int heapN) { for (int i = (heapN) / 2; i >= 1; i--) maxHeap(i, heapN, begin); } // main function to do heapsort private void heapSort(int begin, int end) { int heapN = end - begin; // Build heap (rearrange array) this.heapify(begin, end, heapN); // One by one extract an element from heap for (int i = heapN; i >= 1; i--) { // Move current root to end swap(begin, begin + i); // call maxHeap() on the reduced heap maxHeap(1, i, begin); } } // function that implements insertion sort private void insertionSort(int left, int right) { for (int i = left; i <= right; i++) { int key = a[i]; int j = i; // Move elements of arr[0..i-1], that are // greater than the key, to one position ahead // of their current position while (j > left && a[j - 1] > key) { a[j] = a[j - 1]; j--; } a[j] = key; } } // Function for finding the median of the three elements private int findPivot(int a1, int b1, int c1) { int max = Math.max(Math.max(a[a1], a[b1]), a[c1]); int min = Math.min(Math.min(a[a1], a[b1]), a[c1]); int median = max ^ min ^ a[a1] ^ a[b1] ^ a[c1]; if (median == a[a1]) return a1; if (median == a[b1]) return b1; return c1; } // This function takes the last element as pivot, places // the pivot element at its correct position in sorted // array, and places all smaller (smaller than pivot) // to the left of the pivot // and greater elements to the right of the pivot private int partition(int low, int high) { // pivot int pivot = a[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If the current element is smaller // than or equal to the pivot if (a[j] <= pivot) { // increment index of smaller element i++; swap(i, j); } } swap(i + 1, high); return (i + 1); } // The main function that implements Introsort // low --> Starting index, // high --> Ending index, // depthLimit --> recursion level private void sortDataUtil(int begin, int end, int depthLimit) { if (end - begin > 16) { if (depthLimit == 0) { // if the recursion limit is // occurred call heap sort this.heapSort(begin, end); return; } depthLimit = depthLimit - 1; int pivot = findPivot(begin, begin + ((end - begin) / 2) + 1, end); swap(pivot, end); // p is partitioning index, // arr[p] is now at right place int p = partition(begin, end); // Separately sort elements before // partition and after partition sortDataUtil(begin, p - 1, depthLimit); sortDataUtil(p + 1, end, depthLimit); } else { // if the data set is small, // call insertion sort insertionSort(begin, end); } } // A utility function to begin the // Introsort module private void sortData() { // Initialise the depthLimit // as 2*log(length(data)) int depthLimit = (int)(2 * Math.floor(Math.log(n) / Math.log(2))); this.sortDataUtil(0, n - 1, depthLimit); } // A utility function to print the array data private void printData() { for (int i = 0; i < n; i++) System.out.print(a[i] + " "); } // Driver code public static void main(String args[]) throws IOException { int[] inp = { 2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8 }; int n = inp.length; Introsort introsort = new Introsort(n); for (int i = 0; i < n; i++) { introsort.dataAppend(inp[i]); } introsort.sortData(); introsort.printData(); }}
# Python implementation of Introsort algorithm import mathimport sysfrom heapq import heappush, heappop arr = [] # The main function to sort# an array of the given size# using heapsort algorithm def heapsort(): global arr h = [] # building the heap for value in arr: heappush(h, value) arr = [] # extracting the sorted elements one by one arr = arr + [heappop(h) for i in range(len(h))] # The main function to sort the data using# insertion sort algorithm def InsertionSort(begin, end): left = begin right = end # Traverse through 1 to len(arr) for i in range(left + 1, right + 1): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i - 1 while j >= left and arr[j] > key: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key # This function takes last element as pivot, places# the pivot element at its correct position in sorted# array, and places all smaller (smaller than pivot)# to left of pivot and all greater elements to right# of pivot def Partition(low, high): global arr # pivot pivot = arr[high] # index of smaller element i = low - 1 for j in range(low, high): # If the current element is smaller than or # equal to the pivot if arr[j] <= pivot: # increment index of smaller element i = i + 1 (arr[i], arr[j]) = (arr[j], arr[i]) (arr[i + 1], arr[high]) = (arr[high], arr[i + 1]) return i + 1 # The function to find the median# of the three elements in# in the index a, b, d def MedianOfThree(a, b, d): global arr A = arr[a] B = arr[b] C = arr[d] if A <= B and B <= C: return b if C <= B and B <= A: return b if B <= A and A <= C: return a if C <= A and A <= B: return a if B <= C and C <= A: return d if A <= C and C <= B: return d # The main function that implements Introsort# low --> Starting index,# high --> Ending index# depthLimit --> recursion level def IntrosortUtil(begin, end, depthLimit): global arr size = end - begin if size < 16: # if the data set is small, call insertion sort InsertionSort(begin, end) return if depthLimit == 0: # if the recursion limit is occurred call heap sort heapsort() return pivot = MedianOfThree(begin, begin + size // 2, end) (arr[pivot], arr[end]) = (arr[end], arr[pivot]) # partitionPoint is partitioning index, # arr[partitionPoint] is now at right place partitionPoint = Partition(begin, end) # Separately sort elements before partition and after partition IntrosortUtil(begin, partitionPoint - 1, depthLimit - 1) IntrosortUtil(partitionPoint + 1, end, depthLimit - 1) # A utility function to begin the Introsort module def Introsort(begin, end): # initialise the depthLimit as 2 * log(length(data)) depthLimit = 2 * math.floor(math.log2(end - begin)) IntrosortUtil(begin, end, depthLimit) # A utility function to print the array data def printArr(): print ('Arr: ', arr) def main(): global arr arr = arr + [ 2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8 ] n = len(arr) Introsort(0, n - 1) printArr() if __name__ == '__main__': main()
// C# implementation of// Introsort algorithmusing System;class Introsort{ // the actual data that// has to be sortedpublic int []a; // the number of elements// in the datapublic int n; // Constructor to initialize// the size of the dataIntrosort(int n){ a = new int[n]; this.n = 0;} // The utility function to// insert the dataprivate void dataAppend(int temp){ a[n] = temp; n++;} // The utility function to// swap two elementsprivate void swap(int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp;} // To maxHeap a subtree rooted// with node i which is an index// in []a. heapN is size of heapprivate void maxHeap(int i, int heapN, int begin){ int temp = a[begin + i - 1]; int child; while (i <= heapN / 2) { child = 2 * i; if (child < heapN && a[begin + child - 1] < a[begin + child]) child++; if (temp >= a[begin + child - 1]) break; a[begin + i - 1] = a[begin + child - 1]; i = child; } a[begin + i - 1] = temp;} // Function to build the// heap (rearranging the array)private void heapify(int begin, int end, int heapN){ for (int i = (heapN) / 2; i >= 1; i--) maxHeap(i, heapN, begin);} // main function to do heapsortprivate void heapSort(int begin, int end){ int heapN = end - begin; // Build heap (rearrange array) this.heapify(begin, end, heapN); // One by one extract an element // from heap for (int i = heapN; i >= 1; i--) { // Move current root to end swap(begin, begin + i); // call maxHeap() on the // reduced heap maxHeap(1, i, begin); }} // function that implements// insertion sortprivate void insertionSort(int left, int right){ for (int i = left; i <= right; i++) { int key = a[i]; int j = i; // Move elements of arr[0..i-1], // that are greater than the key, // to one position ahead // of their current position while (j > left && a[j - 1] > key) { a[j] = a[j - 1]; j--; } a[j] = key; }} // Function for finding the median// of the three elementsprivate int findPivot(int a1, int b1, int c1){ int max = Math.Max( Math.Max(a[a1], a[b1]), a[c1]); int min = Math.Min( Math.Min(a[a1], a[b1]), a[c1]); int median = max ^ min ^ a[a1] ^ a[b1] ^ a[c1]; if (median == a[a1]) return a1; if (median == a[b1]) return b1; return c1;} // This function takes the last element// as pivot, places the pivot element at// its correct position in sorted// array, and places all smaller// (smaller than pivot) to the left of// the pivot and greater elements to// the right of the pivotprivate int partition(int low, int high){ // pivot int pivot = a[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If the current element // is smaller than or equal // to the pivot if (a[j] <= pivot) { // increment index of // smaller element i++; swap(i, j); } } swap(i + 1, high); return (i + 1);} // The main function that implements// Introsort low --> Starting index,// high --> Ending index, depthLimit// --> recursion levelprivate void sortDataUtil(int begin, int end, int depthLimit){ if (end - begin > 16) { if (depthLimit == 0) { // if the recursion limit is // occurred call heap sort this.heapSort(begin, end); return; } depthLimit = depthLimit - 1; int pivot = findPivot(begin, begin + ((end - begin) / 2) + 1, end); swap(pivot, end); // p is partitioning index, // arr[p] is now at right place int p = partition(begin, end); // Separately sort elements // before partition and after // partition sortDataUtil(begin, p - 1, depthLimit); sortDataUtil(p + 1, end, depthLimit); } else { // if the data set is small, // call insertion sort insertionSort(begin, end); }} // A utility function to begin// the Introsort moduleprivate void sortData(){ // Initialise the depthLimit // as 2*log(length(data)) int depthLimit = (int)(2 * Math.Floor( Math.Log(n) / Math.Log(2))); this.sortDataUtil(0, n - 1, depthLimit);} // A utility function to print// the array dataprivate void printData(){ for (int i = 0; i < n; i++) Console.Write(a[i] + " ");} // Driver codepublic static void Main(String []args){ int[] inp = {2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8}; int n = inp.Length; Introsort introsort = new Introsort(n); for (int i = 0; i < n; i++) { introsort.dataAppend(inp[i]); } introsort.sortData(); introsort.printData();}} // This code is contributed by Rajput-Ji
0 2 2 2 3 4 4 8 8 8 9 10 10 10 11 13 13 13 16 18 22 22 23 24 24 27 27 28 28 28
Lokesh Karthikeyan
Rajput-Ji
mikewolfe
ashutoshsinghgeeksforgeeks
Heap Sort
Merge Sort
Picked
Quick Sort
Algorithms
Divide and Conquer
Sorting
Divide and Conquer
Sorting
Merge Sort
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 399,
"s": 54,
"text": "Introsort(Introspective sort) is a comparison based sort that consists of three sorting phases. They are Quicksort, Heapsort, and Insertion sort. Basic concepts of Introsort and the C++ code are available hereThe following section shows how the Introsort algorithm is formulated, after reviewing the pros and cons of the respective algorithms. "
},
{
"code": null,
"e": 2424,
"s": 399,
"text": "Quicksort The Quicksort is an efficient sorting algorithm but has the worst-case performance of O(N ^ 2) comparisons with O(N) auxiliary space. This worst-case complexity depends on two phases of the Quicksort algorithm. 1. Choosing the pivot element 2. Recursion depth during the course of the algorithmHeapsort Heapsort has O(N log N) worst-case time complexity, which is much better than the worst case of Quicksort. So, is it evident that Heapsort is the best? No, the secret of Quicksort is that it does not swap already elements that are already in order, which is unnecessary, whereas with the Heapsort, even if all of the data is already sorted, the algorithm swaps all of the elements to order the array. Also, by choosing the optimal pivot, the worst-case of O(N ^ 2) can be avoided in quicksort. But, the swapping will pay more time in the case of Heapsort that is unavoidable. Hence, Quicksort outperforms Heapsort.The best things about Heapsort is that, if the recursion depth becomes too large like (log N), the worst case complexity would be still O(N log N). Mergesort The Mergesort has the worst case complexity only as O(N log N). Mergesort can work well on any type of data sets irrespective of its size whereas the Quicksort cannot work well with large data sets. But, Mergesort is not in-place whereas Quicksort is in-place, and that plays a vital role in here. Mergesort goes well with LinkedLists whereas Quicksort goes well with arrays. The locality of reference is better with Quicksort, whereas with Mergesort it is bad. So, for conventional purposes, having memory constraints in hand, Quicksort outperforms Mergesort. Insertion sort The main advantage of the insertion sort is its simplicity. It also exhibits a good performance when dealing with a small list. The insertion sort is an in-place sorting algorithm so the space requirement is minimal. The disadvantage of the insertion sort is that it does not perform as well as the other sorting algorithms when the size of the data gets larger. "
},
{
"code": null,
"e": 2729,
"s": 2424,
"text": "Quicksort The Quicksort is an efficient sorting algorithm but has the worst-case performance of O(N ^ 2) comparisons with O(N) auxiliary space. This worst-case complexity depends on two phases of the Quicksort algorithm. 1. Choosing the pivot element 2. Recursion depth during the course of the algorithm"
},
{
"code": null,
"e": 3500,
"s": 2729,
"text": "Heapsort Heapsort has O(N log N) worst-case time complexity, which is much better than the worst case of Quicksort. So, is it evident that Heapsort is the best? No, the secret of Quicksort is that it does not swap already elements that are already in order, which is unnecessary, whereas with the Heapsort, even if all of the data is already sorted, the algorithm swaps all of the elements to order the array. Also, by choosing the optimal pivot, the worst-case of O(N ^ 2) can be avoided in quicksort. But, the swapping will pay more time in the case of Heapsort that is unavoidable. Hence, Quicksort outperforms Heapsort.The best things about Heapsort is that, if the recursion depth becomes too large like (log N), the worst case complexity would be still O(N log N)."
},
{
"code": null,
"e": 4072,
"s": 3500,
"text": " Mergesort The Mergesort has the worst case complexity only as O(N log N). Mergesort can work well on any type of data sets irrespective of its size whereas the Quicksort cannot work well with large data sets. But, Mergesort is not in-place whereas Quicksort is in-place, and that plays a vital role in here. Mergesort goes well with LinkedLists whereas Quicksort goes well with arrays. The locality of reference is better with Quicksort, whereas with Mergesort it is bad. So, for conventional purposes, having memory constraints in hand, Quicksort outperforms Mergesort."
},
{
"code": null,
"e": 4452,
"s": 4072,
"text": " Insertion sort The main advantage of the insertion sort is its simplicity. It also exhibits a good performance when dealing with a small list. The insertion sort is an in-place sorting algorithm so the space requirement is minimal. The disadvantage of the insertion sort is that it does not perform as well as the other sorting algorithms when the size of the data gets larger. "
},
{
"code": null,
"e": 5490,
"s": 4452,
"text": "Here is how Introsort is formulated: Choosing the right sorting algorithm depends on the occasion where the sorting algorithm is being used. There are a good number of sorting algorithms in hand already that has pros and cons of its own. So, to get a better sorting algorithm, the solution is to tweak the existing algorithms and produce a new sorting algorithm that works better. There are a lot of hybrid algorithms, that outperforms the general sorting algorithms. One such is the Introsort. The best versions of Quicksort are competitive with both heap sort and merge sort on the vast majority of inputs. Rarely Quicksort has the worst case of O(N ^ 2) running time and O(N) stack usage. Both Heapsort and Mergesort have O(N log N) worst-case running time, together with a stack usage of O(1) for Heapsort and O(log N) for Mergesort respectively. Also, Insertion sort performs better than any of the above algorithms if the data set is small.Combining all the pros of the sorting algorithms, Introsort behaves based on the data set. "
},
{
"code": null,
"e": 6149,
"s": 5490,
"text": "If the number of elements in the input gets fewer, the Introsort performs Insertion sort for the input.Having the least number of comparisons(Quicksort) in mind, for splitting the array by finding the pivot element, Quicksort is used. Quoted earlier, the worst case of Quicksort is based on the two phases and here is how we can fix them.Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot elementRecursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N)."
},
{
"code": null,
"e": 6253,
"s": 6149,
"text": "If the number of elements in the input gets fewer, the Introsort performs Insertion sort for the input."
},
{
"code": null,
"e": 6809,
"s": 6253,
"text": "Having the least number of comparisons(Quicksort) in mind, for splitting the array by finding the pivot element, Quicksort is used. Quoted earlier, the worst case of Quicksort is based on the two phases and here is how we can fix them.Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot elementRecursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N)."
},
{
"code": null,
"e": 7130,
"s": 6809,
"text": "Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot elementRecursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N)."
},
{
"code": null,
"e": 7288,
"s": 7130,
"text": "Choosing the pivot element: We can use either of median-of-3 concept or randomized pivot concept or middle as the pivot concept for finding the pivot element"
},
{
"code": null,
"e": 7452,
"s": 7288,
"text": "Recursion depth during the course of the algorithm: When the recursion depth gets higher, Introsort uses Heapsort as it has the definite upper bound of O(N log N)."
},
{
"code": null,
"e": 7767,
"s": 7452,
"text": "How does depthLimit work? depthLimit represents maximum depth for recursion. It is typically chosen as log of length of input array (please refer below implementation). The idea is to ensure that the worst case time complexity remains O(N log N). Note that the worst-case time complexity of HeapSort is O(N log N)."
},
{
"code": null,
"e": 7917,
"s": 7767,
"text": "Why is Mergesort not used? As the arrays are being dealt with the in-place concept where Quicksort outperforms Mergesort, we are not using Mergesort."
},
{
"code": null,
"e": 7956,
"s": 7917,
"text": "Can Introsort be applied everywhere? "
},
{
"code": null,
"e": 8142,
"s": 7956,
"text": "If the data won’t fit in an array, Introsort cannot be used.Furthermore, like Quicksort and Heapsort, Introsort is not stable. When a stable sort is needed, Introsort cannot be applied."
},
{
"code": null,
"e": 8203,
"s": 8142,
"text": "If the data won’t fit in an array, Introsort cannot be used."
},
{
"code": null,
"e": 8329,
"s": 8203,
"text": "Furthermore, like Quicksort and Heapsort, Introsort is not stable. When a stable sort is needed, Introsort cannot be applied."
},
{
"code": null,
"e": 8588,
"s": 8329,
"text": "Is Introsort the only hybrid sorting algorithm? No. There are other hybrid sorting algorithms like Hybrid Mergesort, Tim sort, Insertion-Merge hybrid.Comparison of Heapsort, Insertion sort, Quicksort, Introsort while sorting 6000 elements(in milliseconds). "
},
{
"code": null,
"e": 8601,
"s": 8588,
"text": "Pseudocode: "
},
{
"code": null,
"e": 9012,
"s": 8601,
"text": "sort(A : array):\n depthLimit = 2xfloor(log(length(A)))\n introsort(A, depthLimit)\n\nintrosort(A, depthLimit):\n n = length(A)\n if n<=16:\n insertionSort(A)\n if depthLimit == 0:\n heapsort(A)\n else:\n\n // using quick sort, the\n // partition point is found \n p = partition(A) \n introsort(A[0:p-1], depthLimit - 1)\n introsort(A[p+1:n], depthLimit - 1)"
},
{
"code": null,
"e": 9465,
"s": 9012,
"text": "Time Complexity: Worst-case performance: O(nlogn) (better than Quicksort) Average-case performance: O(nlogn)In the Quicksort phase, the pivot can either be chosen using the median-of-3 concept or last element of the array. For data that has a huge number of elements, median-of-3 concept slows down the running time of the Quicksort.In the example described below, the quicksort algorithm calculates the pivot element based on the median-of-3 concept. "
},
{
"code": null,
"e": 9474,
"s": 9465,
"text": "Example:"
},
{
"code": null,
"e": 9478,
"s": 9474,
"text": "C++"
},
{
"code": null,
"e": 9483,
"s": 9478,
"text": "Java"
},
{
"code": null,
"e": 9491,
"s": 9483,
"text": "Python3"
},
{
"code": null,
"e": 9494,
"s": 9491,
"text": "C#"
},
{
"code": "// C++ implementation of Introsort algorithm #include <bits/stdc++.h>using namespace std; // A utility function to swap the values pointed by// the two pointersvoid swapValue(int* a, int* b){ int* temp = a; a = b; b = temp; return;} /* Function to sort an array using insertion sort*/void InsertionSort(int arr[], int* begin, int* end){ // Get the left and the right index of the subarray // to be sorted int left = begin - arr; int right = end - arr; for (int i = left + 1; i <= right; i++) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= left && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } return;} // A function to partition the array and return// the partition pointint* Partition(int arr[], int low, int high){ int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { // increment index of smaller element i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (arr + i + 1);} // A function that find the middle of the// values pointed by the pointers a, b, c// and return that pointerint* MedianOfThree(int* a, int* b, int* c){ if (*a < *b && *b < *c) return (b); if (*a < *c && *c <= *b) return (c); if (*b <= *a && *a < *c) return (a); if (*b < *c && *c <= *a) return (c); if (*c <= *a && *a < *b) return (a); if (*c <= *b && *b <= *a) return (b);} // A Utility function to perform intro sortvoid IntrosortUtil(int arr[], int* begin, int* end, int depthLimit){ // Count the number of elements int size = end - begin; // If partition size is low then do insertion sort if (size < 16) { InsertionSort(arr, begin, end); return; } // If the depth is zero use heapsort if (depthLimit == 0) { make_heap(begin, end + 1); sort_heap(begin, end + 1); return; } // Else use a median-of-three concept to // find a good pivot int* pivot = MedianOfThree(begin, begin + size / 2, end); // Swap the values pointed by the two pointers swapValue(pivot, end); // Perform Quick Sort int* partitionPoint = Partition(arr, begin - arr, end - arr); IntrosortUtil(arr, begin, partitionPoint - 1, depthLimit - 1); IntrosortUtil(arr, partitionPoint + 1, end, depthLimit - 1); return;} /* Implementation of introsort*/void Introsort(int arr[], int* begin, int* end){ int depthLimit = 2 * log(end - begin); // Perform a recursive Introsort IntrosortUtil(arr, begin, end, depthLimit); return;} // A utility function ot print an array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \\n\"[i + 1 == n];} // Driver program to test Introsortint main(){ int arr[] = { 2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); // Pass the array, the pointer to the first element and // the pointer to the last element Introsort(arr, arr, arr + n - 1); printArray(arr, n); return (0);}",
"e": 13103,
"s": 9494,
"text": null
},
{
"code": "// Java implementation of Introsort algorithm import java.io.IOException; public class Introsort { // the actual data that has to be sorted private int a[]; // the number of elements in the data private int n; // Constructor to initialize the size // of the data Introsort(int n) { a = new int[n]; this.n = 0; } // The utility function to insert the data private void dataAppend(int temp) { a[n] = temp; n++; } // The utility function to swap two elements private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // To maxHeap a subtree rooted with node i which is // an index in a[]. heapN is size of heap private void maxHeap(int i, int heapN, int begin) { int temp = a[begin + i - 1]; int child; while (i <= heapN / 2) { child = 2 * i; if (child < heapN && a[begin + child - 1] < a[begin + child]) child++; if (temp >= a[begin + child - 1]) break; a[begin + i - 1] = a[begin + child - 1]; i = child; } a[begin + i - 1] = temp; } // Function to build the heap (rearranging the array) private void heapify(int begin, int end, int heapN) { for (int i = (heapN) / 2; i >= 1; i--) maxHeap(i, heapN, begin); } // main function to do heapsort private void heapSort(int begin, int end) { int heapN = end - begin; // Build heap (rearrange array) this.heapify(begin, end, heapN); // One by one extract an element from heap for (int i = heapN; i >= 1; i--) { // Move current root to end swap(begin, begin + i); // call maxHeap() on the reduced heap maxHeap(1, i, begin); } } // function that implements insertion sort private void insertionSort(int left, int right) { for (int i = left; i <= right; i++) { int key = a[i]; int j = i; // Move elements of arr[0..i-1], that are // greater than the key, to one position ahead // of their current position while (j > left && a[j - 1] > key) { a[j] = a[j - 1]; j--; } a[j] = key; } } // Function for finding the median of the three elements private int findPivot(int a1, int b1, int c1) { int max = Math.max(Math.max(a[a1], a[b1]), a[c1]); int min = Math.min(Math.min(a[a1], a[b1]), a[c1]); int median = max ^ min ^ a[a1] ^ a[b1] ^ a[c1]; if (median == a[a1]) return a1; if (median == a[b1]) return b1; return c1; } // This function takes the last element as pivot, places // the pivot element at its correct position in sorted // array, and places all smaller (smaller than pivot) // to the left of the pivot // and greater elements to the right of the pivot private int partition(int low, int high) { // pivot int pivot = a[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If the current element is smaller // than or equal to the pivot if (a[j] <= pivot) { // increment index of smaller element i++; swap(i, j); } } swap(i + 1, high); return (i + 1); } // The main function that implements Introsort // low --> Starting index, // high --> Ending index, // depthLimit --> recursion level private void sortDataUtil(int begin, int end, int depthLimit) { if (end - begin > 16) { if (depthLimit == 0) { // if the recursion limit is // occurred call heap sort this.heapSort(begin, end); return; } depthLimit = depthLimit - 1; int pivot = findPivot(begin, begin + ((end - begin) / 2) + 1, end); swap(pivot, end); // p is partitioning index, // arr[p] is now at right place int p = partition(begin, end); // Separately sort elements before // partition and after partition sortDataUtil(begin, p - 1, depthLimit); sortDataUtil(p + 1, end, depthLimit); } else { // if the data set is small, // call insertion sort insertionSort(begin, end); } } // A utility function to begin the // Introsort module private void sortData() { // Initialise the depthLimit // as 2*log(length(data)) int depthLimit = (int)(2 * Math.floor(Math.log(n) / Math.log(2))); this.sortDataUtil(0, n - 1, depthLimit); } // A utility function to print the array data private void printData() { for (int i = 0; i < n; i++) System.out.print(a[i] + \" \"); } // Driver code public static void main(String args[]) throws IOException { int[] inp = { 2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8 }; int n = inp.length; Introsort introsort = new Introsort(n); for (int i = 0; i < n; i++) { introsort.dataAppend(inp[i]); } introsort.sortData(); introsort.printData(); }}",
"e": 18809,
"s": 13103,
"text": null
},
{
"code": "# Python implementation of Introsort algorithm import mathimport sysfrom heapq import heappush, heappop arr = [] # The main function to sort# an array of the given size# using heapsort algorithm def heapsort(): global arr h = [] # building the heap for value in arr: heappush(h, value) arr = [] # extracting the sorted elements one by one arr = arr + [heappop(h) for i in range(len(h))] # The main function to sort the data using# insertion sort algorithm def InsertionSort(begin, end): left = begin right = end # Traverse through 1 to len(arr) for i in range(left + 1, right + 1): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i - 1 while j >= left and arr[j] > key: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key # This function takes last element as pivot, places# the pivot element at its correct position in sorted# array, and places all smaller (smaller than pivot)# to left of pivot and all greater elements to right# of pivot def Partition(low, high): global arr # pivot pivot = arr[high] # index of smaller element i = low - 1 for j in range(low, high): # If the current element is smaller than or # equal to the pivot if arr[j] <= pivot: # increment index of smaller element i = i + 1 (arr[i], arr[j]) = (arr[j], arr[i]) (arr[i + 1], arr[high]) = (arr[high], arr[i + 1]) return i + 1 # The function to find the median# of the three elements in# in the index a, b, d def MedianOfThree(a, b, d): global arr A = arr[a] B = arr[b] C = arr[d] if A <= B and B <= C: return b if C <= B and B <= A: return b if B <= A and A <= C: return a if C <= A and A <= B: return a if B <= C and C <= A: return d if A <= C and C <= B: return d # The main function that implements Introsort# low --> Starting index,# high --> Ending index# depthLimit --> recursion level def IntrosortUtil(begin, end, depthLimit): global arr size = end - begin if size < 16: # if the data set is small, call insertion sort InsertionSort(begin, end) return if depthLimit == 0: # if the recursion limit is occurred call heap sort heapsort() return pivot = MedianOfThree(begin, begin + size // 2, end) (arr[pivot], arr[end]) = (arr[end], arr[pivot]) # partitionPoint is partitioning index, # arr[partitionPoint] is now at right place partitionPoint = Partition(begin, end) # Separately sort elements before partition and after partition IntrosortUtil(begin, partitionPoint - 1, depthLimit - 1) IntrosortUtil(partitionPoint + 1, end, depthLimit - 1) # A utility function to begin the Introsort module def Introsort(begin, end): # initialise the depthLimit as 2 * log(length(data)) depthLimit = 2 * math.floor(math.log2(end - begin)) IntrosortUtil(begin, end, depthLimit) # A utility function to print the array data def printArr(): print ('Arr: ', arr) def main(): global arr arr = arr + [ 2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8 ] n = len(arr) Introsort(0, n - 1) printArr() if __name__ == '__main__': main()",
"e": 22288,
"s": 18809,
"text": null
},
{
"code": "// C# implementation of// Introsort algorithmusing System;class Introsort{ // the actual data that// has to be sortedpublic int []a; // the number of elements// in the datapublic int n; // Constructor to initialize// the size of the dataIntrosort(int n){ a = new int[n]; this.n = 0;} // The utility function to// insert the dataprivate void dataAppend(int temp){ a[n] = temp; n++;} // The utility function to// swap two elementsprivate void swap(int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp;} // To maxHeap a subtree rooted// with node i which is an index// in []a. heapN is size of heapprivate void maxHeap(int i, int heapN, int begin){ int temp = a[begin + i - 1]; int child; while (i <= heapN / 2) { child = 2 * i; if (child < heapN && a[begin + child - 1] < a[begin + child]) child++; if (temp >= a[begin + child - 1]) break; a[begin + i - 1] = a[begin + child - 1]; i = child; } a[begin + i - 1] = temp;} // Function to build the// heap (rearranging the array)private void heapify(int begin, int end, int heapN){ for (int i = (heapN) / 2; i >= 1; i--) maxHeap(i, heapN, begin);} // main function to do heapsortprivate void heapSort(int begin, int end){ int heapN = end - begin; // Build heap (rearrange array) this.heapify(begin, end, heapN); // One by one extract an element // from heap for (int i = heapN; i >= 1; i--) { // Move current root to end swap(begin, begin + i); // call maxHeap() on the // reduced heap maxHeap(1, i, begin); }} // function that implements// insertion sortprivate void insertionSort(int left, int right){ for (int i = left; i <= right; i++) { int key = a[i]; int j = i; // Move elements of arr[0..i-1], // that are greater than the key, // to one position ahead // of their current position while (j > left && a[j - 1] > key) { a[j] = a[j - 1]; j--; } a[j] = key; }} // Function for finding the median// of the three elementsprivate int findPivot(int a1, int b1, int c1){ int max = Math.Max( Math.Max(a[a1], a[b1]), a[c1]); int min = Math.Min( Math.Min(a[a1], a[b1]), a[c1]); int median = max ^ min ^ a[a1] ^ a[b1] ^ a[c1]; if (median == a[a1]) return a1; if (median == a[b1]) return b1; return c1;} // This function takes the last element// as pivot, places the pivot element at// its correct position in sorted// array, and places all smaller// (smaller than pivot) to the left of// the pivot and greater elements to// the right of the pivotprivate int partition(int low, int high){ // pivot int pivot = a[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If the current element // is smaller than or equal // to the pivot if (a[j] <= pivot) { // increment index of // smaller element i++; swap(i, j); } } swap(i + 1, high); return (i + 1);} // The main function that implements// Introsort low --> Starting index,// high --> Ending index, depthLimit// --> recursion levelprivate void sortDataUtil(int begin, int end, int depthLimit){ if (end - begin > 16) { if (depthLimit == 0) { // if the recursion limit is // occurred call heap sort this.heapSort(begin, end); return; } depthLimit = depthLimit - 1; int pivot = findPivot(begin, begin + ((end - begin) / 2) + 1, end); swap(pivot, end); // p is partitioning index, // arr[p] is now at right place int p = partition(begin, end); // Separately sort elements // before partition and after // partition sortDataUtil(begin, p - 1, depthLimit); sortDataUtil(p + 1, end, depthLimit); } else { // if the data set is small, // call insertion sort insertionSort(begin, end); }} // A utility function to begin// the Introsort moduleprivate void sortData(){ // Initialise the depthLimit // as 2*log(length(data)) int depthLimit = (int)(2 * Math.Floor( Math.Log(n) / Math.Log(2))); this.sortDataUtil(0, n - 1, depthLimit);} // A utility function to print// the array dataprivate void printData(){ for (int i = 0; i < n; i++) Console.Write(a[i] + \" \");} // Driver codepublic static void Main(String []args){ int[] inp = {2, 10, 24, 2, 10, 11, 27, 4, 2, 4, 28, 16, 9, 8, 28, 10, 13, 24, 22, 28, 0, 13, 27, 13, 3, 23, 18, 22, 8, 8}; int n = inp.Length; Introsort introsort = new Introsort(n); for (int i = 0; i < n; i++) { introsort.dataAppend(inp[i]); } introsort.sortData(); introsort.printData();}} // This code is contributed by Rajput-Ji",
"e": 27396,
"s": 22288,
"text": null
},
{
"code": null,
"e": 27476,
"s": 27396,
"text": "0 2 2 2 3 4 4 8 8 8 9 10 10 10 11 13 13 13 16 18 22 22 23 24 24 27 27 28 28 28 "
},
{
"code": null,
"e": 27495,
"s": 27476,
"text": "Lokesh Karthikeyan"
},
{
"code": null,
"e": 27505,
"s": 27495,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 27515,
"s": 27505,
"text": "mikewolfe"
},
{
"code": null,
"e": 27542,
"s": 27515,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 27552,
"s": 27542,
"text": "Heap Sort"
},
{
"code": null,
"e": 27563,
"s": 27552,
"text": "Merge Sort"
},
{
"code": null,
"e": 27570,
"s": 27563,
"text": "Picked"
},
{
"code": null,
"e": 27581,
"s": 27570,
"text": "Quick Sort"
},
{
"code": null,
"e": 27592,
"s": 27581,
"text": "Algorithms"
},
{
"code": null,
"e": 27611,
"s": 27592,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 27619,
"s": 27611,
"text": "Sorting"
},
{
"code": null,
"e": 27638,
"s": 27619,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 27646,
"s": 27638,
"text": "Sorting"
},
{
"code": null,
"e": 27657,
"s": 27646,
"text": "Merge Sort"
},
{
"code": null,
"e": 27668,
"s": 27657,
"text": "Algorithms"
}
] |
NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (EncoderDecoder Model) | by Mohammed AL-Ma'amari | Towards Data Science
|
In [NLP | Sequence to Sequence Networks| Part 1| Processing text data] we learnt how to process text data, In this part we will create the model which will take the data we processed and use it to train to translate English sentences to French.
We will use an architecture called (seq2seq) or ( Encoder Decoder), It is appropriate in our case where the length of the input sequence ( English sentences in our case) does not has the same length as the output data ( French sentences in our case)
Encoder decoder architecture consists of two main parts :
Encoder:
Encoder:
The encoder simply takes the input data, and train on it then it passes the last state of its recurrent layer as an initial state to the first recurrent layer of the decoder part.
Encoder input : English sentencesEncoder initial state : It depends on the initializer we use
2. Decoder :
The decoder takes the last state of encoder’s last recurrent layer and uses it as an initial state to its first recurrent layer , the input of the decoder is the sequences that we want to get ( in our case French sentences).
Decoder input : French sentencesDecoder initial state : The last state of encoder’s last recurrent layer
Some other images explaining the encoder decoder:
To learn more about encoder decoder architecture [0],[1],[2],[3],[4]
First, Import needed dependencies :
Building the encoder :
We use the (Keras Functional API) to build such complex models, if you want to learn more about Keras functional API : [1],[2]
The encoder is made up of :
Input Layer : Takes the English sentence and pass it to the embedding layer.Embedding Layer : Takes the English sentence and convert each word to fixed size vectorFirst LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, We used CuDNNLSTM layer instead of LSTM because it’s much much faster.Second LSTM Layer : It does the same thing as the previous layer, but instead of passing its output, it passes its states to the first LSTM layer of the decoder .
Input Layer : Takes the English sentence and pass it to the embedding layer.
Embedding Layer : Takes the English sentence and convert each word to fixed size vector
First LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, We used CuDNNLSTM layer instead of LSTM because it’s much much faster.
Second LSTM Layer : It does the same thing as the previous layer, but instead of passing its output, it passes its states to the first LSTM layer of the decoder .
Building the decoder :
The decoder is made up of :
Input Layer : Takes the French sentence and pass it to the embedding layer.Embedding Layer : Takes the French sentence and convert each word to fixed size vectorFirst LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, but here in the decoder, we initialize the state of this layer to be the last state of the last LSTM layer from the decoder .Second LSTM Layer : Processing the output from the previous layer and passes its output to a dense layer .Dense Layer (Output Layer) : Takes the output from the previous layer and outputs a one hot vector representing the target French word
Input Layer : Takes the French sentence and pass it to the embedding layer.
Embedding Layer : Takes the French sentence and convert each word to fixed size vector
First LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, but here in the decoder, we initialize the state of this layer to be the last state of the last LSTM layer from the decoder .
Second LSTM Layer : Processing the output from the previous layer and passes its output to a dense layer .
Dense Layer (Output Layer) : Takes the output from the previous layer and outputs a one hot vector representing the target French word
Note :
We have to know that we don’t convert each English sentence into French in one time step, we do that in a number of time steps that equals the number of words that the longest English sentence has.
so if the longest English sentence has 10 words, we have to take 10 time steps to get its French translation.
I simplified the encoder decoder model using the previous blocks, Where in reality, we have many time steps, not just one as in the simplified representation, and the final output is not a sentence that we can read directly, what is really happening is that every time step we get a one hot vector that represent the target word.
Bringing the encoder and decoder together into one model :
I only used 9000 samples because I did not have enough memory to use the whole dataset, and because of that, the result wasn’t good enough.
The optimizer we used is rmsprop , it is used in models that have recurrent layers.
This optimizer is usually a good choice for recurrent neural networks.
We used categorical_crossentropy as the loss function, because we treat each word as a category (our output is a one hot vector that represents a word)
We got to know what an encoder decoder model is.
How to create the encoder
How to use the embedding layer
How to make the decoder
We understood how the encoder decoder model works
We trained the model
In the next part of this series, we will use the trained model to translate English sentences to French.
1- NLP | Sequence to Sequence Networks| Part 1| Processing text data
2- NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (Encoder Decoder Model)
All the references o this series will be at the end of the last part.
You can follow me on Twitter @ModMaamari
AI Generates Taylor Swift’s Song Lyrics
Deep Neural Networks for Regression Problems
Machine Learning Crash Course with TensorFlow APIs Summary
How To Make A CNN Using Tensorflow and Keras
How to Choose the Best Machine Learning Model ?
|
[
{
"code": null,
"e": 417,
"s": 172,
"text": "In [NLP | Sequence to Sequence Networks| Part 1| Processing text data] we learnt how to process text data, In this part we will create the model which will take the data we processed and use it to train to translate English sentences to French."
},
{
"code": null,
"e": 667,
"s": 417,
"text": "We will use an architecture called (seq2seq) or ( Encoder Decoder), It is appropriate in our case where the length of the input sequence ( English sentences in our case) does not has the same length as the output data ( French sentences in our case)"
},
{
"code": null,
"e": 725,
"s": 667,
"text": "Encoder decoder architecture consists of two main parts :"
},
{
"code": null,
"e": 734,
"s": 725,
"text": "Encoder:"
},
{
"code": null,
"e": 743,
"s": 734,
"text": "Encoder:"
},
{
"code": null,
"e": 923,
"s": 743,
"text": "The encoder simply takes the input data, and train on it then it passes the last state of its recurrent layer as an initial state to the first recurrent layer of the decoder part."
},
{
"code": null,
"e": 1017,
"s": 923,
"text": "Encoder input : English sentencesEncoder initial state : It depends on the initializer we use"
},
{
"code": null,
"e": 1030,
"s": 1017,
"text": "2. Decoder :"
},
{
"code": null,
"e": 1255,
"s": 1030,
"text": "The decoder takes the last state of encoder’s last recurrent layer and uses it as an initial state to its first recurrent layer , the input of the decoder is the sequences that we want to get ( in our case French sentences)."
},
{
"code": null,
"e": 1360,
"s": 1255,
"text": "Decoder input : French sentencesDecoder initial state : The last state of encoder’s last recurrent layer"
},
{
"code": null,
"e": 1410,
"s": 1360,
"text": "Some other images explaining the encoder decoder:"
},
{
"code": null,
"e": 1479,
"s": 1410,
"text": "To learn more about encoder decoder architecture [0],[1],[2],[3],[4]"
},
{
"code": null,
"e": 1515,
"s": 1479,
"text": "First, Import needed dependencies :"
},
{
"code": null,
"e": 1538,
"s": 1515,
"text": "Building the encoder :"
},
{
"code": null,
"e": 1665,
"s": 1538,
"text": "We use the (Keras Functional API) to build such complex models, if you want to learn more about Keras functional API : [1],[2]"
},
{
"code": null,
"e": 1693,
"s": 1665,
"text": "The encoder is made up of :"
},
{
"code": null,
"e": 2205,
"s": 1693,
"text": "Input Layer : Takes the English sentence and pass it to the embedding layer.Embedding Layer : Takes the English sentence and convert each word to fixed size vectorFirst LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, We used CuDNNLSTM layer instead of LSTM because it’s much much faster.Second LSTM Layer : It does the same thing as the previous layer, but instead of passing its output, it passes its states to the first LSTM layer of the decoder ."
},
{
"code": null,
"e": 2282,
"s": 2205,
"text": "Input Layer : Takes the English sentence and pass it to the embedding layer."
},
{
"code": null,
"e": 2370,
"s": 2282,
"text": "Embedding Layer : Takes the English sentence and convert each word to fixed size vector"
},
{
"code": null,
"e": 2557,
"s": 2370,
"text": "First LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, We used CuDNNLSTM layer instead of LSTM because it’s much much faster."
},
{
"code": null,
"e": 2720,
"s": 2557,
"text": "Second LSTM Layer : It does the same thing as the previous layer, but instead of passing its output, it passes its states to the first LSTM layer of the decoder ."
},
{
"code": null,
"e": 2743,
"s": 2720,
"text": "Building the decoder :"
},
{
"code": null,
"e": 2771,
"s": 2743,
"text": "The decoder is made up of :"
},
{
"code": null,
"e": 3414,
"s": 2771,
"text": "Input Layer : Takes the French sentence and pass it to the embedding layer.Embedding Layer : Takes the French sentence and convert each word to fixed size vectorFirst LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, but here in the decoder, we initialize the state of this layer to be the last state of the last LSTM layer from the decoder .Second LSTM Layer : Processing the output from the previous layer and passes its output to a dense layer .Dense Layer (Output Layer) : Takes the output from the previous layer and outputs a one hot vector representing the target French word"
},
{
"code": null,
"e": 3490,
"s": 3414,
"text": "Input Layer : Takes the French sentence and pass it to the embedding layer."
},
{
"code": null,
"e": 3577,
"s": 3490,
"text": "Embedding Layer : Takes the French sentence and convert each word to fixed size vector"
},
{
"code": null,
"e": 3819,
"s": 3577,
"text": "First LSTM Layer : Every time step, it takes a vector that represents a word and pass its output to the next layer, but here in the decoder, we initialize the state of this layer to be the last state of the last LSTM layer from the decoder ."
},
{
"code": null,
"e": 3926,
"s": 3819,
"text": "Second LSTM Layer : Processing the output from the previous layer and passes its output to a dense layer ."
},
{
"code": null,
"e": 4061,
"s": 3926,
"text": "Dense Layer (Output Layer) : Takes the output from the previous layer and outputs a one hot vector representing the target French word"
},
{
"code": null,
"e": 4068,
"s": 4061,
"text": "Note :"
},
{
"code": null,
"e": 4266,
"s": 4068,
"text": "We have to know that we don’t convert each English sentence into French in one time step, we do that in a number of time steps that equals the number of words that the longest English sentence has."
},
{
"code": null,
"e": 4376,
"s": 4266,
"text": "so if the longest English sentence has 10 words, we have to take 10 time steps to get its French translation."
},
{
"code": null,
"e": 4706,
"s": 4376,
"text": "I simplified the encoder decoder model using the previous blocks, Where in reality, we have many time steps, not just one as in the simplified representation, and the final output is not a sentence that we can read directly, what is really happening is that every time step we get a one hot vector that represent the target word."
},
{
"code": null,
"e": 4765,
"s": 4706,
"text": "Bringing the encoder and decoder together into one model :"
},
{
"code": null,
"e": 4905,
"s": 4765,
"text": "I only used 9000 samples because I did not have enough memory to use the whole dataset, and because of that, the result wasn’t good enough."
},
{
"code": null,
"e": 4989,
"s": 4905,
"text": "The optimizer we used is rmsprop , it is used in models that have recurrent layers."
},
{
"code": null,
"e": 5060,
"s": 4989,
"text": "This optimizer is usually a good choice for recurrent neural networks."
},
{
"code": null,
"e": 5212,
"s": 5060,
"text": "We used categorical_crossentropy as the loss function, because we treat each word as a category (our output is a one hot vector that represents a word)"
},
{
"code": null,
"e": 5261,
"s": 5212,
"text": "We got to know what an encoder decoder model is."
},
{
"code": null,
"e": 5287,
"s": 5261,
"text": "How to create the encoder"
},
{
"code": null,
"e": 5318,
"s": 5287,
"text": "How to use the embedding layer"
},
{
"code": null,
"e": 5342,
"s": 5318,
"text": "How to make the decoder"
},
{
"code": null,
"e": 5392,
"s": 5342,
"text": "We understood how the encoder decoder model works"
},
{
"code": null,
"e": 5413,
"s": 5392,
"text": "We trained the model"
},
{
"code": null,
"e": 5518,
"s": 5413,
"text": "In the next part of this series, we will use the trained model to translate English sentences to French."
},
{
"code": null,
"e": 5587,
"s": 5518,
"text": "1- NLP | Sequence to Sequence Networks| Part 1| Processing text data"
},
{
"code": null,
"e": 5672,
"s": 5587,
"text": "2- NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (Encoder Decoder Model)"
},
{
"code": null,
"e": 5742,
"s": 5672,
"text": "All the references o this series will be at the end of the last part."
},
{
"code": null,
"e": 5783,
"s": 5742,
"text": "You can follow me on Twitter @ModMaamari"
},
{
"code": null,
"e": 5823,
"s": 5783,
"text": "AI Generates Taylor Swift’s Song Lyrics"
},
{
"code": null,
"e": 5868,
"s": 5823,
"text": "Deep Neural Networks for Regression Problems"
},
{
"code": null,
"e": 5927,
"s": 5868,
"text": "Machine Learning Crash Course with TensorFlow APIs Summary"
},
{
"code": null,
"e": 5972,
"s": 5927,
"text": "How To Make A CNN Using Tensorflow and Keras"
}
] |
Find N from the value of N! - GeeksforGeeks
|
16 Aug, 2021
Given a number K which represents the factorial of a number N, the task is to find the value of N. Note: K < 1018Examples:
Input: K = 120 Output: 5 Explanation: 5! = 1 * 2 * 3 * 4 * 5 = 120Input: K = 6 Output: 3 Explanation: 3! = 1 * 2 * 3 = 6
Approach: It is given that the value of N! is less than 1018. On observation we can see that this is true only for N <= 18. Therefore we can precompute values of factorials from 1 to 18 and store it in a Hash Table or Map. After precomputation, for every value of N!, the corresponding N is returned in constant time. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find a number such that// the factorial of that number is given #include "bits/stdc++.h"#define ll long long intusing namespace std; // Map to precompute and store the// factorials of the numbersmap<ll, ll> m; // Function to precompute factorialint precompute(){ ll fact = 1; for (ll i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m[fact] = i; }} // Driver codeint main(){ // Precomputing the factorials precompute(); int K = 120; cout << m[K] << endl; K = 6; cout << m[K] << endl; return 0;}
// Java program to find a number such that// the factorial of that number is givenimport java.util.*; class GFG{ // Map to precompute and store the// factorials of the numbersstatic Map<Integer, Integer> m = new HashMap<Integer, Integer>(); // Function to precompute factorialstatic void precompute(){ int fact = 1; for (int i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m.put(fact, i); }} // Driver codepublic static void main(String[] args){ // Precomputing the factorials precompute(); int K = 120; System.out.print(m.get(K) +"\n"); K = 6; System.out.print(m.get(K) +"\n"); }} // This code is contributed by 29AjayKumar
# Python3 program to find a number such that# the factorial of that number is given # Map to precompute and store the# factorials of the numbersm = {}; # Function to precompute factorialdef precompute() : fact = 1; for i in range(1, 19) : # Calculating the factorial for # each i and storing in a map fact = fact * i; m[fact] = i; # Driver codeif __name__ == "__main__" : # Precomputing the factorials precompute(); K = 120; print(m[K]); K = 6; print(m[K]) ; # This code is contributed by AnkitRai01
// C# program to find a number such that// the factorial of that number is givenusing System;using System.Collections.Generic; class GFG{ // Map to precompute and store the// factorials of the numbersstatic Dictionary<int, int> m = new Dictionary<int, int>(); // Function to precompute factorialstatic void precompute(){ int fact = 1; for (int i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m.Add(fact, i); }} // Driver codepublic static void Main(String[] args){ // Precomputing the factorials precompute(); int K = 120; Console.Write(m[K] +"\n"); K = 6; Console.Write(m[K] +"\n"); }} // This code is contributed by 29AjayKumar
<script>// Javascript implementation of the// above approach // Map to precompute and store the// factorials of the numbersvar m = {}; // Function to precompute factorialfunction precompute(){ var fact = 1; for (var i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m[fact] = i; }} // Driver codeprecompute();var K = 120;document.write(m[K] + "<br>"); K = 6;document.write(m[K]); // This code is contributed by Shivanisingh</script>
5
3
ankthon
29AjayKumar
shivanisinghss2110
anikakapoor
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Program to multiply two matrices
Fizz Buzz Implementation
Modular multiplicative inverse
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
Interfaces in Java
|
[
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 24817,
"s": 24692,
"text": "Given a number K which represents the factorial of a number N, the task is to find the value of N. Note: K < 1018Examples: "
},
{
"code": null,
"e": 24940,
"s": 24817,
"text": "Input: K = 120 Output: 5 Explanation: 5! = 1 * 2 * 3 * 4 * 5 = 120Input: K = 6 Output: 3 Explanation: 3! = 1 * 2 * 3 = 6 "
},
{
"code": null,
"e": 25313,
"s": 24942,
"text": "Approach: It is given that the value of N! is less than 1018. On observation we can see that this is true only for N <= 18. Therefore we can precompute values of factorials from 1 to 18 and store it in a Hash Table or Map. After precomputation, for every value of N!, the corresponding N is returned in constant time. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25317,
"s": 25313,
"text": "C++"
},
{
"code": null,
"e": 25322,
"s": 25317,
"text": "Java"
},
{
"code": null,
"e": 25330,
"s": 25322,
"text": "Python3"
},
{
"code": null,
"e": 25333,
"s": 25330,
"text": "C#"
},
{
"code": null,
"e": 25344,
"s": 25333,
"text": "Javascript"
},
{
"code": "// C++ program to find a number such that// the factorial of that number is given #include \"bits/stdc++.h\"#define ll long long intusing namespace std; // Map to precompute and store the// factorials of the numbersmap<ll, ll> m; // Function to precompute factorialint precompute(){ ll fact = 1; for (ll i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m[fact] = i; }} // Driver codeint main(){ // Precomputing the factorials precompute(); int K = 120; cout << m[K] << endl; K = 6; cout << m[K] << endl; return 0;}",
"e": 25975,
"s": 25344,
"text": null
},
{
"code": "// Java program to find a number such that// the factorial of that number is givenimport java.util.*; class GFG{ // Map to precompute and store the// factorials of the numbersstatic Map<Integer, Integer> m = new HashMap<Integer, Integer>(); // Function to precompute factorialstatic void precompute(){ int fact = 1; for (int i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m.put(fact, i); }} // Driver codepublic static void main(String[] args){ // Precomputing the factorials precompute(); int K = 120; System.out.print(m.get(K) +\"\\n\"); K = 6; System.out.print(m.get(K) +\"\\n\"); }} // This code is contributed by 29AjayKumar",
"e": 26723,
"s": 25975,
"text": null
},
{
"code": "# Python3 program to find a number such that# the factorial of that number is given # Map to precompute and store the# factorials of the numbersm = {}; # Function to precompute factorialdef precompute() : fact = 1; for i in range(1, 19) : # Calculating the factorial for # each i and storing in a map fact = fact * i; m[fact] = i; # Driver codeif __name__ == \"__main__\" : # Precomputing the factorials precompute(); K = 120; print(m[K]); K = 6; print(m[K]) ; # This code is contributed by AnkitRai01",
"e": 27288,
"s": 26723,
"text": null
},
{
"code": "// C# program to find a number such that// the factorial of that number is givenusing System;using System.Collections.Generic; class GFG{ // Map to precompute and store the// factorials of the numbersstatic Dictionary<int, int> m = new Dictionary<int, int>(); // Function to precompute factorialstatic void precompute(){ int fact = 1; for (int i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m.Add(fact, i); }} // Driver codepublic static void Main(String[] args){ // Precomputing the factorials precompute(); int K = 120; Console.Write(m[K] +\"\\n\"); K = 6; Console.Write(m[K] +\"\\n\"); }} // This code is contributed by 29AjayKumar",
"e": 28047,
"s": 27288,
"text": null
},
{
"code": "<script>// Javascript implementation of the// above approach // Map to precompute and store the// factorials of the numbersvar m = {}; // Function to precompute factorialfunction precompute(){ var fact = 1; for (var i = 1; i <= 18; i++) { // Calculating the factorial for // each i and storing in a map fact = fact * i; m[fact] = i; }} // Driver codeprecompute();var K = 120;document.write(m[K] + \"<br>\"); K = 6;document.write(m[K]); // This code is contributed by Shivanisingh</script>",
"e": 28580,
"s": 28047,
"text": null
},
{
"code": null,
"e": 28584,
"s": 28580,
"text": "5\n3"
},
{
"code": null,
"e": 28594,
"s": 28586,
"text": "ankthon"
},
{
"code": null,
"e": 28606,
"s": 28594,
"text": "29AjayKumar"
},
{
"code": null,
"e": 28625,
"s": 28606,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 28637,
"s": 28625,
"text": "anikakapoor"
},
{
"code": null,
"e": 28650,
"s": 28637,
"text": "Mathematical"
},
{
"code": null,
"e": 28669,
"s": 28650,
"text": "School Programming"
},
{
"code": null,
"e": 28682,
"s": 28669,
"text": "Mathematical"
},
{
"code": null,
"e": 28780,
"s": 28682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28812,
"s": 28780,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 28856,
"s": 28812,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 28889,
"s": 28856,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 28914,
"s": 28889,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 28945,
"s": 28914,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 28963,
"s": 28945,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28979,
"s": 28963,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29004,
"s": 28979,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29023,
"s": 29004,
"text": "Inheritance in C++"
}
] |
Loading Custom Image Dataset for Deep Learning Models: Part 1 | by Renu Khandelwal | Towards Data Science
|
In this article, you will learn how to load and create image train and test dataset from custom data as an input for Deep learning models. You will learn to load the dataset using.
Open CV2
PIL
The dataset used here is Intel Image Classification from Kaggle.
Intel Image classification dataset is already split into train, test, and Val, and we will only use the training dataset to learn how to load the dataset using different libraries.
Open the image file. The format of the file can be JPEG, PNG, BMP, etc.Resize the image to match the input size for the Input layer of the Deep Learning model.Convert the image pixels to float datatype.Normalize the image to have pixel values scaled down between 0 and 1 from 0 to 255.Image data for Deep Learning models should be either a numpy array or a tensor object.
Open the image file. The format of the file can be JPEG, PNG, BMP, etc.
Resize the image to match the input size for the Input layer of the Deep Learning model.
Convert the image pixels to float datatype.
Normalize the image to have pixel values scaled down between 0 and 1 from 0 to 255.
Image data for Deep Learning models should be either a numpy array or a tensor object.
Importing required libraries
import pandas as pdimport numpy as npimport osimport tensorflow as tfimport cv2from tensorflow import kerasfrom tensorflow.keras import layers, Dense, Input, InputLayer, Flattenfrom tensorflow.keras.models import Sequential, Modelfrom matplotlib import pyplot as pltimport matplotlib.image as mpimg%matplotlib inline
Printing random five images from one of the folders
plt.figure(figsize=(20,20))test_folder=r'CV\Intel_Images\seg_train\seg_train\forest'for i in range(5): file = random.choice(os.listdir(img_folder)) image_path= os.path.join(img_folder, file) img=mpimg.imread(image_path) ax=plt.subplot(1,5,i+1) ax.title.set_text(file) plt.imshow(img)
Setting the Image dimension and source folder for loading the dataset
IMG_WIDTH=200IMG_HEIGHT=200img_folder=r'CV\Intel_Images\seg_train\seg_train\'
Creating the image data and the labels from the images in the folder
In the function below
The source folder is the input parameter containing the images for different classes.
Read the image file from the folder and convert it to the right color format.
Resize the image based on the input dimension required for the model
Convert the image to a Numpy array with float32 as the datatype
Normalize the image array to have values scaled down between 0 and 1 from 0 to 255 for a similar data distribution, which helps with faster convergence.
def create_dataset(img_folder): img_data_array=[] class_name=[] for dir1 in os.listdir(img_folder): for file in os.listdir(os.path.join(img_folder, dir1)): image_path= os.path.join(img_folder, dir1, file) image= cv2.imread( image_path, cv2.COLOR_BGR2RGB) image=cv2.resize(image, (IMG_HEIGHT, IMG_WIDTH),interpolation = cv2.INTER_AREA) image=np.array(image) image = image.astype('float32') image /= 255 img_data_array.append(image) class_name.append(dir1) return img_data_array, class_name# extract the image array and class nameimg_data, class_name =create_dataset(r'CV\Intel_Images\seg_train\seg_train')
Converting text labels to numeric codes
Create a dictionary for all unique values for the classes
target_dict={k: v for v, k in enumerate(np.unique(class_name))}target_dict
Convert the class_names to their respective numeric value based on the dictionary
target_val= [target_dict[class_name[i]] for i in range(len(class_name))]
Creating a simple deep learning model and compiling it
model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(IMG_HEIGHT,IMG_WIDTH, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])encoder.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
We finally fit our dataset to train the model. We can use Numpy array as the input
history = model.fit(x=np.array(img_data, np.float32), y=np.array(list(map(int,target_val)), np.float32), epochs=5)
We can also convert the input data to tensors to train the model by using tf.cast()
history = model.fit(x=tf.cast(np.array(img_data), tf.float64), y=tf.cast(list(map(int,target_val)),tf.int32), epochs=5)
We will use the same model for further training by loading image dataset using different libraries
Adding additional library for loading image dataset using PIL
from PIL import Image
Creating the image data and the labels from the images in the folder using PIL
In the function below
The source folder is the input parameter containing the images for different classes.
Open the image file from the folder using PIL.
Resize the image based on the input dimension required for the model
Convert the image to a Numpy array with float32 as the datatype
Normalize the image array for faster convergence.
def create_dataset_PIL(img_folder): img_data_array=[] class_name=[] for dir1 in os.listdir(img_folder): for file in os.listdir(os.path.join(img_folder, dir1)): image_path= os.path.join(img_folder, dir1, file) image= np.array(Image.open(image_path)) image= np.resize(image,(IMG_HEIGHT,IMG_WIDTH,3)) image = image.astype('float32') image /= 255 img_data_array.append(image) class_name.append(dir1) return img_data_array , class_namePIL_img_data, class_name=create_dataset_PIL(img_folder)
Converting text labels to numeric codes
Following is the same code that we used for CV2
target_dict={k: v for v, k in enumerate(np.unique(class_name))}target_val= [target_dict[class_name[i]] for i in range(len(class_name))]
Creating and compiling a simple Deep Learning Model
model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(IMG_HEIGHT,IMG_WIDTH, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])encoder.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
We finally fit our dataset to train the model. We can use Numpy array as the input
history = model.fit(x=np.array(PIL_img_data, np.float32), y=np.array(list(map(int,target_val)), np.float32), epochs=5)
We can also convert the input data to tensors to train the model by using tf.cast()
history = model.fit(x=tf.cast(np.array(PIL_img_data), tf.float64), y=tf.cast(list(map(int,target_val)),tf.int32), epochs=5)
The process is the same for loading the dataset using CV2 and PIL except for a couple of steps.
Now this will help you load the dataset using CV2 and PIL library.
Code for loading dataset using CV2 and PIL available here.
In the next article, we will load the dataset using.
Keras
Tensorflow core including tf.data
|
[
{
"code": null,
"e": 228,
"s": 47,
"text": "In this article, you will learn how to load and create image train and test dataset from custom data as an input for Deep learning models. You will learn to load the dataset using."
},
{
"code": null,
"e": 237,
"s": 228,
"text": "Open CV2"
},
{
"code": null,
"e": 241,
"s": 237,
"text": "PIL"
},
{
"code": null,
"e": 306,
"s": 241,
"text": "The dataset used here is Intel Image Classification from Kaggle."
},
{
"code": null,
"e": 487,
"s": 306,
"text": "Intel Image classification dataset is already split into train, test, and Val, and we will only use the training dataset to learn how to load the dataset using different libraries."
},
{
"code": null,
"e": 859,
"s": 487,
"text": "Open the image file. The format of the file can be JPEG, PNG, BMP, etc.Resize the image to match the input size for the Input layer of the Deep Learning model.Convert the image pixels to float datatype.Normalize the image to have pixel values scaled down between 0 and 1 from 0 to 255.Image data for Deep Learning models should be either a numpy array or a tensor object."
},
{
"code": null,
"e": 931,
"s": 859,
"text": "Open the image file. The format of the file can be JPEG, PNG, BMP, etc."
},
{
"code": null,
"e": 1020,
"s": 931,
"text": "Resize the image to match the input size for the Input layer of the Deep Learning model."
},
{
"code": null,
"e": 1064,
"s": 1020,
"text": "Convert the image pixels to float datatype."
},
{
"code": null,
"e": 1148,
"s": 1064,
"text": "Normalize the image to have pixel values scaled down between 0 and 1 from 0 to 255."
},
{
"code": null,
"e": 1235,
"s": 1148,
"text": "Image data for Deep Learning models should be either a numpy array or a tensor object."
},
{
"code": null,
"e": 1264,
"s": 1235,
"text": "Importing required libraries"
},
{
"code": null,
"e": 1582,
"s": 1264,
"text": "import pandas as pdimport numpy as npimport osimport tensorflow as tfimport cv2from tensorflow import kerasfrom tensorflow.keras import layers, Dense, Input, InputLayer, Flattenfrom tensorflow.keras.models import Sequential, Modelfrom matplotlib import pyplot as pltimport matplotlib.image as mpimg%matplotlib inline"
},
{
"code": null,
"e": 1634,
"s": 1582,
"text": "Printing random five images from one of the folders"
},
{
"code": null,
"e": 1936,
"s": 1634,
"text": "plt.figure(figsize=(20,20))test_folder=r'CV\\Intel_Images\\seg_train\\seg_train\\forest'for i in range(5): file = random.choice(os.listdir(img_folder)) image_path= os.path.join(img_folder, file) img=mpimg.imread(image_path) ax=plt.subplot(1,5,i+1) ax.title.set_text(file) plt.imshow(img)"
},
{
"code": null,
"e": 2006,
"s": 1936,
"text": "Setting the Image dimension and source folder for loading the dataset"
},
{
"code": null,
"e": 2084,
"s": 2006,
"text": "IMG_WIDTH=200IMG_HEIGHT=200img_folder=r'CV\\Intel_Images\\seg_train\\seg_train\\'"
},
{
"code": null,
"e": 2153,
"s": 2084,
"text": "Creating the image data and the labels from the images in the folder"
},
{
"code": null,
"e": 2175,
"s": 2153,
"text": "In the function below"
},
{
"code": null,
"e": 2261,
"s": 2175,
"text": "The source folder is the input parameter containing the images for different classes."
},
{
"code": null,
"e": 2339,
"s": 2261,
"text": "Read the image file from the folder and convert it to the right color format."
},
{
"code": null,
"e": 2408,
"s": 2339,
"text": "Resize the image based on the input dimension required for the model"
},
{
"code": null,
"e": 2472,
"s": 2408,
"text": "Convert the image to a Numpy array with float32 as the datatype"
},
{
"code": null,
"e": 2625,
"s": 2472,
"text": "Normalize the image array to have values scaled down between 0 and 1 from 0 to 255 for a similar data distribution, which helps with faster convergence."
},
{
"code": null,
"e": 3352,
"s": 2625,
"text": "def create_dataset(img_folder): img_data_array=[] class_name=[] for dir1 in os.listdir(img_folder): for file in os.listdir(os.path.join(img_folder, dir1)): image_path= os.path.join(img_folder, dir1, file) image= cv2.imread( image_path, cv2.COLOR_BGR2RGB) image=cv2.resize(image, (IMG_HEIGHT, IMG_WIDTH),interpolation = cv2.INTER_AREA) image=np.array(image) image = image.astype('float32') image /= 255 img_data_array.append(image) class_name.append(dir1) return img_data_array, class_name# extract the image array and class nameimg_data, class_name =create_dataset(r'CV\\Intel_Images\\seg_train\\seg_train')"
},
{
"code": null,
"e": 3392,
"s": 3352,
"text": "Converting text labels to numeric codes"
},
{
"code": null,
"e": 3450,
"s": 3392,
"text": "Create a dictionary for all unique values for the classes"
},
{
"code": null,
"e": 3525,
"s": 3450,
"text": "target_dict={k: v for v, k in enumerate(np.unique(class_name))}target_dict"
},
{
"code": null,
"e": 3607,
"s": 3525,
"text": "Convert the class_names to their respective numeric value based on the dictionary"
},
{
"code": null,
"e": 3681,
"s": 3607,
"text": "target_val= [target_dict[class_name[i]] for i in range(len(class_name))]"
},
{
"code": null,
"e": 3736,
"s": 3681,
"text": "Creating a simple deep learning model and compiling it"
},
{
"code": null,
"e": 4226,
"s": 3736,
"text": "model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(IMG_HEIGHT,IMG_WIDTH, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])encoder.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 4309,
"s": 4226,
"text": "We finally fit our dataset to train the model. We can use Numpy array as the input"
},
{
"code": null,
"e": 4424,
"s": 4309,
"text": "history = model.fit(x=np.array(img_data, np.float32), y=np.array(list(map(int,target_val)), np.float32), epochs=5)"
},
{
"code": null,
"e": 4508,
"s": 4424,
"text": "We can also convert the input data to tensors to train the model by using tf.cast()"
},
{
"code": null,
"e": 4628,
"s": 4508,
"text": "history = model.fit(x=tf.cast(np.array(img_data), tf.float64), y=tf.cast(list(map(int,target_val)),tf.int32), epochs=5)"
},
{
"code": null,
"e": 4727,
"s": 4628,
"text": "We will use the same model for further training by loading image dataset using different libraries"
},
{
"code": null,
"e": 4789,
"s": 4727,
"text": "Adding additional library for loading image dataset using PIL"
},
{
"code": null,
"e": 4811,
"s": 4789,
"text": "from PIL import Image"
},
{
"code": null,
"e": 4890,
"s": 4811,
"text": "Creating the image data and the labels from the images in the folder using PIL"
},
{
"code": null,
"e": 4912,
"s": 4890,
"text": "In the function below"
},
{
"code": null,
"e": 4998,
"s": 4912,
"text": "The source folder is the input parameter containing the images for different classes."
},
{
"code": null,
"e": 5045,
"s": 4998,
"text": "Open the image file from the folder using PIL."
},
{
"code": null,
"e": 5114,
"s": 5045,
"text": "Resize the image based on the input dimension required for the model"
},
{
"code": null,
"e": 5178,
"s": 5114,
"text": "Convert the image to a Numpy array with float32 as the datatype"
},
{
"code": null,
"e": 5228,
"s": 5178,
"text": "Normalize the image array for faster convergence."
},
{
"code": null,
"e": 5824,
"s": 5228,
"text": "def create_dataset_PIL(img_folder): img_data_array=[] class_name=[] for dir1 in os.listdir(img_folder): for file in os.listdir(os.path.join(img_folder, dir1)): image_path= os.path.join(img_folder, dir1, file) image= np.array(Image.open(image_path)) image= np.resize(image,(IMG_HEIGHT,IMG_WIDTH,3)) image = image.astype('float32') image /= 255 img_data_array.append(image) class_name.append(dir1) return img_data_array , class_namePIL_img_data, class_name=create_dataset_PIL(img_folder)"
},
{
"code": null,
"e": 5864,
"s": 5824,
"text": "Converting text labels to numeric codes"
},
{
"code": null,
"e": 5912,
"s": 5864,
"text": "Following is the same code that we used for CV2"
},
{
"code": null,
"e": 6049,
"s": 5912,
"text": "target_dict={k: v for v, k in enumerate(np.unique(class_name))}target_val= [target_dict[class_name[i]] for i in range(len(class_name))]"
},
{
"code": null,
"e": 6101,
"s": 6049,
"text": "Creating and compiling a simple Deep Learning Model"
},
{
"code": null,
"e": 6591,
"s": 6101,
"text": "model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(IMG_HEIGHT,IMG_WIDTH, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])encoder.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 6674,
"s": 6591,
"text": "We finally fit our dataset to train the model. We can use Numpy array as the input"
},
{
"code": null,
"e": 6793,
"s": 6674,
"text": "history = model.fit(x=np.array(PIL_img_data, np.float32), y=np.array(list(map(int,target_val)), np.float32), epochs=5)"
},
{
"code": null,
"e": 6877,
"s": 6793,
"text": "We can also convert the input data to tensors to train the model by using tf.cast()"
},
{
"code": null,
"e": 7001,
"s": 6877,
"text": "history = model.fit(x=tf.cast(np.array(PIL_img_data), tf.float64), y=tf.cast(list(map(int,target_val)),tf.int32), epochs=5)"
},
{
"code": null,
"e": 7097,
"s": 7001,
"text": "The process is the same for loading the dataset using CV2 and PIL except for a couple of steps."
},
{
"code": null,
"e": 7164,
"s": 7097,
"text": "Now this will help you load the dataset using CV2 and PIL library."
},
{
"code": null,
"e": 7223,
"s": 7164,
"text": "Code for loading dataset using CV2 and PIL available here."
},
{
"code": null,
"e": 7276,
"s": 7223,
"text": "In the next article, we will load the dataset using."
},
{
"code": null,
"e": 7282,
"s": 7276,
"text": "Keras"
}
] |
Python - 3D Charts
|
Python is also capable of creating 3d charts. It involves adding a subplot to an existing two-dimensional plot and assigning the projection parameter as 3d.
3dPlot is drawn by mpl_toolkits.mplot3d to add a subplot to an existing 2d plot.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
chart = plt.figure()
chart3d = chart.add_subplot(111, projection='3d')
# Create some test data.
X, Y, Z = axes3d.get_test_data(0.08)
# Plot a wireframe.
chart3d.plot_wireframe(X, Y, Z, color='r',rstride=15, cstride=10)
plt.show()
Its output is as follows −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2688,
"s": 2529,
"text": "Python is also capable of creating 3d charts. It involves adding a subplot to an existing two-dimensional plot and assigning the projection parameter as 3d. "
},
{
"code": null,
"e": 2770,
"s": 2688,
"text": "3dPlot is drawn by mpl_toolkits.mplot3d to add a subplot to an existing 2d plot."
},
{
"code": null,
"e": 3079,
"s": 2770,
"text": "from mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\n\n\nchart = plt.figure()\nchart3d = chart.add_subplot(111, projection='3d')\n\n# Create some test data.\nX, Y, Z = axes3d.get_test_data(0.08)\n\n# Plot a wireframe.\nchart3d.plot_wireframe(X, Y, Z, color='r',rstride=15, cstride=10)\n\nplt.show()\n "
},
{
"code": null,
"e": 3106,
"s": 3079,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3143,
"s": 3106,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3159,
"s": 3143,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3192,
"s": 3159,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3211,
"s": 3192,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3246,
"s": 3211,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3268,
"s": 3246,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3302,
"s": 3268,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3330,
"s": 3302,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3365,
"s": 3330,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3379,
"s": 3365,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3412,
"s": 3379,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3429,
"s": 3412,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3436,
"s": 3429,
"text": " Print"
},
{
"code": null,
"e": 3447,
"s": 3436,
"text": " Add Notes"
}
] |
JOGL - Drawing Basics
|
OpenGL API has provided primitive methods for drawing basic graphical elements such as point, vertex, line etc. Using these methods, you can develop shapes such as triangle, polygon and circle. In both, 2D and 3D dimensions. This chapter teaches you how to draw a basic line using JOGL in a Java program.
To access programs which are specific to a hardware and operating system platforms and where the libraries are written in other languages such as C and C++ (native applications), Java uses a programming framework called Java Native Interface (JNI). JOGL uses this interface internally to access OpenGL functions as shown in the following diagram.
All the four methods of GLEventListener interface have the code (java JOGL methods) to call OpenGL functions internally. Naming of those JOGL methods is also similar to the naming conventions of OpenGL. If the function name in OpenGL is glBegin(), it is used as gl.glBegin().
Whenever the gl.glBegin() method of java JOGL is called, it internally invokes the glBegin() method of OpenGL. This is the reason for installing native library files on the user system at the time of installing JOGL.
This is an important method which holds the code for developing graphics. It
requires the GLAutoDrawable interface object as its parameter.
The display() method initially gets OpenGL context using the object of GL interface (GL inherits GLBase interface which contains methods to generate all OpenGL context objects). Since this tutorial is about JOGL2, let us generate a GL2 object.
The following code snippet shows how to generate a GL2 Object −
//Generating GL object
GL gl = drawable.getGL();
GL gl = drawable.getGL();
//Using this Getting the Gl2 Object
//this can be written in a single line like
final GL2 gl = drawable.getGL().getGL2();
Using the object of GL2 interface, one can access the members of this interface,
which in turn provide access to OpenGL [1.0... 3.0] functions.
GL2 interface contains a huge list of methods but here three main important
methods are discussed namely glBegin(), glVertex(), and glEnd().
glBegin()
This method starts the process of drawing a line. It takes predefined string integer “GL_LINES” as a parameter, which is inherited from GL interface.
glVertex3f()/glVertex2f()
This method creates the vertex and we have to pass coordinates as parameters 3f and 2f, which denote 3-dimensional floating point coordinates and 2-dimensional floating point coordinates respectively.
glEnd()
ends the line
Below given is the program to draws a basic line using JOGL −
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.swing.JFrame;
public class Line implements GLEventListener {
@Override
public void display(GLAutoDrawable drawable) {
final GL2 gl = drawable.getGL().getGL2();
gl.glBegin (GL2.GL_LINES);//static field
gl.glVertex3f(0.50f,-0.50f,0);
gl.glVertex3f(-0.50f,0.50f,0);
gl.glEnd();
}
@Override
public void dispose(GLAutoDrawable arg0) {
//method body
}
@Override
public void init(GLAutoDrawable arg0) {
// method body
}
public static void main(String[] args) {
//getting the capabilities object of GL2 profile
final GLProfile profile = GLProfile.get(GLProfile.GL2);
GLCapabilities capabilities = new GLCapabilities(profile);
// The canvas
final GLCanvas glcanvas = new GLCanvas(capabilities);
Line l = new Line();
glcanvas.addGLEventListener(l);
glcanvas.setSize(400, 400);
//creating frame
final JFrame frame = new JFrame ("straight Line");
//adding canvas to frame
frame.getContentPane().add(glcanvas);
frame.setSize(frame.getContentPane().getPreferredSize());
frame.setVisible(true);
}//end of main
}//end of classimport javax.media.opengl.GL2;
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2324,
"s": 2019,
"text": "OpenGL API has provided primitive methods for drawing basic graphical elements such as point, vertex, line etc. Using these methods, you can develop shapes such as triangle, polygon and circle. In both, 2D and 3D dimensions. This chapter teaches you how to draw a basic line using JOGL in a Java program."
},
{
"code": null,
"e": 2671,
"s": 2324,
"text": "To access programs which are specific to a hardware and operating system platforms and where the libraries are written in other languages such as C and C++ (native applications), Java uses a programming framework called Java Native Interface (JNI). JOGL uses this interface internally to access OpenGL functions as shown in the following diagram."
},
{
"code": null,
"e": 2947,
"s": 2671,
"text": "All the four methods of GLEventListener interface have the code (java JOGL methods) to call OpenGL functions internally. Naming of those JOGL methods is also similar to the naming conventions of OpenGL. If the function name in OpenGL is glBegin(), it is used as gl.glBegin()."
},
{
"code": null,
"e": 3164,
"s": 2947,
"text": "Whenever the gl.glBegin() method of java JOGL is called, it internally invokes the glBegin() method of OpenGL. This is the reason for installing native library files on the user system at the time of installing JOGL."
},
{
"code": null,
"e": 3304,
"s": 3164,
"text": "This is an important method which holds the code for developing graphics. It\nrequires the GLAutoDrawable interface object as its parameter."
},
{
"code": null,
"e": 3548,
"s": 3304,
"text": "The display() method initially gets OpenGL context using the object of GL interface (GL inherits GLBase interface which contains methods to generate all OpenGL context objects). Since this tutorial is about JOGL2, let us generate a GL2 object."
},
{
"code": null,
"e": 3612,
"s": 3548,
"text": "The following code snippet shows how to generate a GL2 Object −"
},
{
"code": null,
"e": 3811,
"s": 3612,
"text": "//Generating GL object\nGL gl = drawable.getGL();\nGL gl = drawable.getGL();\n\n//Using this Getting the Gl2 Object\n//this can be written in a single line like\nfinal GL2 gl = drawable.getGL().getGL2();\n"
},
{
"code": null,
"e": 3955,
"s": 3811,
"text": "Using the object of GL2 interface, one can access the members of this interface,\nwhich in turn provide access to OpenGL [1.0... 3.0] functions."
},
{
"code": null,
"e": 4096,
"s": 3955,
"text": "GL2 interface contains a huge list of methods but here three main important\nmethods are discussed namely glBegin(), glVertex(), and glEnd()."
},
{
"code": null,
"e": 4106,
"s": 4096,
"text": "glBegin()"
},
{
"code": null,
"e": 4256,
"s": 4106,
"text": "This method starts the process of drawing a line. It takes predefined string integer “GL_LINES” as a parameter, which is inherited from GL interface."
},
{
"code": null,
"e": 4282,
"s": 4256,
"text": "glVertex3f()/glVertex2f()"
},
{
"code": null,
"e": 4483,
"s": 4282,
"text": "This method creates the vertex and we have to pass coordinates as parameters 3f and 2f, which denote 3-dimensional floating point coordinates and 2-dimensional floating point coordinates respectively."
},
{
"code": null,
"e": 4491,
"s": 4483,
"text": "glEnd()"
},
{
"code": null,
"e": 4505,
"s": 4491,
"text": "ends the line"
},
{
"code": null,
"e": 4567,
"s": 4505,
"text": "Below given is the program to draws a basic line using JOGL −"
},
{
"code": null,
"e": 6108,
"s": 4567,
"text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\n\nimport javax.swing.JFrame;\n\npublic class Line implements GLEventListener {\n\n @Override\n public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n \n gl.glBegin (GL2.GL_LINES);//static field\n gl.glVertex3f(0.50f,-0.50f,0);\n gl.glVertex3f(-0.50f,0.50f,0);\n gl.glEnd();\n\n }\n \n @Override\n public void dispose(GLAutoDrawable arg0) {\n //method body\n }\n \n @Override\n public void init(GLAutoDrawable arg0) {\n // method body\n }\n\t\n public static void main(String[] args) {\n\n //getting the capabilities object of GL2 profile \n final GLProfile profile = GLProfile.get(GLProfile.GL2);\n GLCapabilities capabilities = new GLCapabilities(profile);\n \n // The canvas\n final GLCanvas glcanvas = new GLCanvas(capabilities);\n Line l = new Line();\n glcanvas.addGLEventListener(l);\n glcanvas.setSize(400, 400);\n \n //creating frame\n final JFrame frame = new JFrame (\"straight Line\");\n \n //adding canvas to frame\n frame.getContentPane().add(glcanvas);\n \n frame.setSize(frame.getContentPane().getPreferredSize());\n frame.setVisible(true);\n \n }//end of main\n\t\n}//end of classimport javax.media.opengl.GL2;"
},
{
"code": null,
"e": 6115,
"s": 6108,
"text": " Print"
},
{
"code": null,
"e": 6126,
"s": 6115,
"text": " Add Notes"
}
] |
Combinational Circuits - GeeksforGeeks
|
19 Nov, 2018
In the 1st column there are 4 NOR Gates,
number them as 1 to 4 ( top to down).
In the 2nd column there are 2 NOR Gates,
number them as 5 and 6 ( top to down).
In the 3rd column there is only 1 NOR Gate,
number it as 7.
1st numbered Gate gives output as : ( P + Q )'
2nd numbered Gate gives output as : ( Q + R )'
3rd numbered Gate gives output as : ( P + R )'
4th numbered Gate gives output as : ( R + Q )'
5th numbered Gate gives output as :
(( P + Q )' + ( Q + R )')'
= ((P + Q)'' . ( Q + R )'') ( De Morgan's law)
= (P + Q ) . ( Q + R ) ( Idempotent Law, A'' = A)
= (PQ + PR + Q + QR )
= (Q(1 + P + R) + PR) = Q + PR ( as, 1 + " any
boolean expression" = 1 )
Similarly 6th numbered Gate gives output as : R + PQ
(as this time R is common here)
Now 7th numbered Gate gives output as :
((Q + PR) + (R + PQ))'
= (Q( 1+P) + R(1+P))'
= (Q+R)'
Pi = Ai ⨁ Bi and Gi = AiBi
Si = Pi ⨁ Ci and Ci+1 = Gi + PiCi , where C0 is the input carry.
c1 = g0 + p0c0 = 1 AND, 1 OR
c2 = g1 + p1g0 + p1p0c0
= 2 AND, 1 OR
c3 = g2 + p2g1 + p2p1go + p2p1p0c0
= 3 AND, 1 OR
c4 = g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0
= 4 AND, 1 OR
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Tailwind CSS vs Bootstrap
How to Show Images on Click using HTML ?
Microsoft Interview Experience for Internship (Via Engage)
How to Calculate Number of Host in a Subnet?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
|
[
{
"code": null,
"e": 27219,
"s": 27191,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 28132,
"s": 27219,
"text": "In the 1st column there are 4 NOR Gates, \nnumber them as 1 to 4 ( top to down).\n\nIn the 2nd column there are 2 NOR Gates, \nnumber them as 5 and 6 ( top to down).\n\nIn the 3rd column there is only 1 NOR Gate, \nnumber it as 7.\n\n1st numbered Gate gives output as : ( P + Q )'\n2nd numbered Gate gives output as : ( Q + R )'\n3rd numbered Gate gives output as : ( P + R )'\n4th numbered Gate gives output as : ( R + Q )'\n5th numbered Gate gives output as :\n(( P + Q )' + ( Q + R )')'\n= ((P + Q)'' . ( Q + R )'') ( De Morgan's law)\n= (P + Q ) . ( Q + R ) ( Idempotent Law, A'' = A)\n= (PQ + PR + Q + QR )\n= (Q(1 + P + R) + PR) = Q + PR ( as, 1 + \" any \n boolean expression\" = 1 )\n\nSimilarly 6th numbered Gate gives output as : R + PQ \n (as this time R is common here)\n\nNow 7th numbered Gate gives output as :\n((Q + PR) + (R + PQ))'\n= (Q( 1+P) + R(1+P))'\n= (Q+R)' "
},
{
"code": null,
"e": 28160,
"s": 28132,
"text": "Pi = Ai ⨁ Bi and Gi = AiBi "
},
{
"code": null,
"e": 28226,
"s": 28160,
"text": "Si = Pi ⨁ Ci and Ci+1 = Gi + PiCi , where C0 is the input carry. "
},
{
"code": null,
"e": 28417,
"s": 28226,
"text": "c1 = g0 + p0c0 = 1 AND, 1 OR\nc2 = g1 + p1g0 + p1p0c0 \n = 2 AND, 1 OR\n\nc3 = g2 + p2g1 + p2p1go + p2p1p0c0 \n = 3 AND, 1 OR\nc4 = g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0 \n = 4 AND, 1 OR"
},
{
"code": null,
"e": 28515,
"s": 28417,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 28524,
"s": 28515,
"text": "Comments"
},
{
"code": null,
"e": 28537,
"s": 28524,
"text": "Old Comments"
},
{
"code": null,
"e": 28563,
"s": 28537,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 28604,
"s": 28563,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 28663,
"s": 28604,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 28708,
"s": 28663,
"text": "How to Calculate Number of Host in a Subnet?"
},
{
"code": null,
"e": 28766,
"s": 28708,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 28828,
"s": 28766,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 28869,
"s": 28828,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28904,
"s": 28869,
"text": "Insert Image in a Jupyter Notebook"
},
{
"code": null,
"e": 28947,
"s": 28904,
"text": "How to Replace Values in a List in Python?"
}
] |
Git - Online Repositories
|
GitHub is a web-based hosting service for software development projects that uses the Git revision control system. It also has their standard GUI application available for download (Windows, Mac, GNU/ Linux) directly from the service's website. But in this session, we will see only CLI part.
Go to github.com. If you already have the GitHub account, then login using that account or create a new one. Follow the steps from github.com website to create a new repository.
Tom decides to use the GitHub server. To start a new project, he creates a new directory and one file inside that.
[tom@CentOS]$ mkdir github_repo
[tom@CentOS]$ cd github_repo/
[tom@CentOS]$ vi hello.c
[tom@CentOS]$ make hello
cc hello.c -o hello
[tom@CentOS]$ ./hello
The above command will produce the following result:
Hello, World !!!
After verifying his code, he initializes the directory with the git init command and commits his changes locally.
[tom@CentOS]$ git init
Initialized empty Git repository in /home/tom/github_repo/.git/
[tom@CentOS]$ git status -s
?? hello
?? hello.c
[tom@CentOS]$ git add hello.c
[tom@CentOS]$ git status -s
A hello.c
?? hello
[tom@CentOS]$ git commit -m 'Initial commit'
After that, he adds the GitHub repository URL as a remote origin and pushes his changes to the remote repository.
[tom@CentOS]$ git remote add origin https://github.com/kangralkar/testing_repo.git
[tom@CentOS]$ git push -u origin master
Push operation will ask for GitHub user name and password. After successful authentication, the operation will succeed.
The above command will produce the following result:
Username for 'https://github.com': kangralkar
Password for 'https://kangralkar@github.com':
Counting objects: 3, done.
Writing objects: 100% (3/3), 214 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/kangralkar/test_repo.git
* [new branch] master −> master
Branch master set up to track remote branch master from origin.
From now, Tom can push any changes to the GitHub repository. He can use all the commands discussed in this chapter with the GitHub repository.
Tom successfully pushed all his changes to the GitHub repository. Now, other developers can view these changes by performing clone operation or updating their local repository.
Jerry creates a new directory in his home directory and clones the GitHub repository by using the git clone command.
[jerry@CentOS]$ pwd
/home/jerry
[jerry@CentOS]$ mkdir jerry_repo
[jerry@CentOS]$ git clone https://github.com/kangralkar/test_repo.git
The above command produces the following result:
Cloning into 'test_repo'...
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 3 (delta 0)
Unpacking objects: 100% (3/3), done.
He verifies the directory contents by executing the ls command.
[jerry@CentOS]$ ls
test_repo
[jerry@CentOS]$ ls test_repo/
hello.c
251 Lectures
35.5 hours
Gowthami Swarna
23 Lectures
2 hours
Asif Hussain
15 Lectures
1.5 hours
Abhilash Nelson
125 Lectures
9 hours
John Shea
13 Lectures
2.5 hours
Raghu Pandey
13 Lectures
3 hours
Sebastian Sulinski
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2338,
"s": 2045,
"text": "GitHub is a web-based hosting service for software development projects that uses the Git revision control system. It also has their standard GUI application available for download (Windows, Mac, GNU/ Linux) directly from the service's website. But in this session, we will see only CLI part."
},
{
"code": null,
"e": 2516,
"s": 2338,
"text": "Go to github.com. If you already have the GitHub account, then login using that account or create a new one. Follow the steps from github.com website to create a new repository."
},
{
"code": null,
"e": 2631,
"s": 2516,
"text": "Tom decides to use the GitHub server. To start a new project, he creates a new directory and one file inside that."
},
{
"code": null,
"e": 2790,
"s": 2631,
"text": "[tom@CentOS]$ mkdir github_repo\n\n[tom@CentOS]$ cd github_repo/\n\n[tom@CentOS]$ vi hello.c\n\n[tom@CentOS]$ make hello\ncc hello.c -o hello\n\n[tom@CentOS]$ ./hello\n"
},
{
"code": null,
"e": 2843,
"s": 2790,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 2861,
"s": 2843,
"text": "Hello, World !!!\n"
},
{
"code": null,
"e": 2975,
"s": 2861,
"text": "After verifying his code, he initializes the directory with the git init command and commits his changes locally."
},
{
"code": null,
"e": 3237,
"s": 2975,
"text": "[tom@CentOS]$ git init\nInitialized empty Git repository in /home/tom/github_repo/.git/\n\n[tom@CentOS]$ git status -s\n?? hello\n?? hello.c\n\n[tom@CentOS]$ git add hello.c\n\n[tom@CentOS]$ git status -s\nA hello.c\n?? hello\n\n[tom@CentOS]$ git commit -m 'Initial commit'\n"
},
{
"code": null,
"e": 3351,
"s": 3237,
"text": "After that, he adds the GitHub repository URL as a remote origin and pushes his changes to the remote repository."
},
{
"code": null,
"e": 3476,
"s": 3351,
"text": "[tom@CentOS]$ git remote add origin https://github.com/kangralkar/testing_repo.git\n\n[tom@CentOS]$ git push -u origin master\n"
},
{
"code": null,
"e": 3596,
"s": 3476,
"text": "Push operation will ask for GitHub user name and password. After successful authentication, the operation will succeed."
},
{
"code": null,
"e": 3649,
"s": 3596,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 4004,
"s": 3649,
"text": "Username for 'https://github.com': kangralkar\nPassword for 'https://kangralkar@github.com': \nCounting objects: 3, done.\nWriting objects: 100% (3/3), 214 bytes, done.\nTotal 3 (delta 0), reused 0 (delta 0)\nTo https://github.com/kangralkar/test_repo.git\n * [new branch] master −> master\n Branch master set up to track remote branch master from origin.\n"
},
{
"code": null,
"e": 4147,
"s": 4004,
"text": "From now, Tom can push any changes to the GitHub repository. He can use all the commands discussed in this chapter with the GitHub repository."
},
{
"code": null,
"e": 4324,
"s": 4147,
"text": "Tom successfully pushed all his changes to the GitHub repository. Now, other developers can view these changes by performing clone operation or updating their local repository."
},
{
"code": null,
"e": 4441,
"s": 4324,
"text": "Jerry creates a new directory in his home directory and clones the GitHub repository by using the git clone command."
},
{
"code": null,
"e": 4579,
"s": 4441,
"text": "[jerry@CentOS]$ pwd\n/home/jerry\n\n[jerry@CentOS]$ mkdir jerry_repo\n\n[jerry@CentOS]$ git clone https://github.com/kangralkar/test_repo.git\n"
},
{
"code": null,
"e": 4628,
"s": 4579,
"text": "The above command produces the following result:"
},
{
"code": null,
"e": 4775,
"s": 4628,
"text": "Cloning into 'test_repo'...\nremote: Counting objects: 3, done.\nremote: Total 3 (delta 0), reused 3 (delta 0)\nUnpacking objects: 100% (3/3), done.\n"
},
{
"code": null,
"e": 4839,
"s": 4775,
"text": "He verifies the directory contents by executing the ls command."
},
{
"code": null,
"e": 4908,
"s": 4839,
"text": "[jerry@CentOS]$ ls\ntest_repo\n\n[jerry@CentOS]$ ls test_repo/\nhello.c\n"
},
{
"code": null,
"e": 4945,
"s": 4908,
"text": "\n 251 Lectures \n 35.5 hours \n"
},
{
"code": null,
"e": 4962,
"s": 4945,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 4995,
"s": 4962,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5009,
"s": 4995,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5044,
"s": 5009,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5061,
"s": 5044,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5095,
"s": 5061,
"text": "\n 125 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5106,
"s": 5095,
"text": " John Shea"
},
{
"code": null,
"e": 5141,
"s": 5106,
"text": "\n 13 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5155,
"s": 5141,
"text": " Raghu Pandey"
},
{
"code": null,
"e": 5188,
"s": 5155,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5208,
"s": 5188,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 5215,
"s": 5208,
"text": " Print"
},
{
"code": null,
"e": 5226,
"s": 5215,
"text": " Add Notes"
}
] |
R - Matrices
|
Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations.
A Matrix is created using the matrix() function.
The basic syntax for creating a matrix in R is −
matrix(data, nrow, ncol, byrow, dimnames)
Following is the description of the parameters used −
data is the input vector which becomes the data elements of the matrix.
data is the input vector which becomes the data elements of the matrix.
nrow is the number of rows to be created.
nrow is the number of rows to be created.
ncol is the number of columns to be created.
ncol is the number of columns to be created.
byrow is a logical clue. If TRUE then the input vector elements are arranged by row.
byrow is a logical clue. If TRUE then the input vector elements are arranged by row.
dimname is the names assigned to the rows and columns.
dimname is the names assigned to the rows and columns.
Create a matrix taking a vector of numbers as input.
# Elements are arranged sequentially by row.
M <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(M)
# Elements are arranged sequentially by column.
N <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(N)
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
print(P)
When we execute the above code, it produces the following result −
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 6 7 8
[3,] 9 10 11
[4,] 12 13 14
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
col1 col2 col3
row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14
Elements of a matrix can be accessed by using the column and row index of the element. We consider the matrix P above to find the specific elements below.
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
# Create the matrix.
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
# Access the element at 3rd column and 1st row.
print(P[1,3])
# Access the element at 2nd column and 4th row.
print(P[4,2])
# Access only the 2nd row.
print(P[2,])
# Access only the 3rd column.
print(P[,3])
When we execute the above code, it produces the following result −
[1] 5
[1] 13
col1 col2 col3
6 7 8
row1 row2 row3 row4
5 8 11 14
Various mathematical operations are performed on the matrices using the R operators. The result of the operation is also a matrix.
The dimensions (number of rows and columns) should be same for the matrices involved in the operation.
# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)
# Add the matrices.
result <- matrix1 + matrix2
cat("Result of addition","\n")
print(result)
# Subtract the matrices
result <- matrix1 - matrix2
cat("Result of subtraction","\n")
print(result)
When we execute the above code, it produces the following result −
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of addition
[,1] [,2] [,3]
[1,] 8 -1 5
[2,] 11 13 10
Result of subtraction
[,1] [,2] [,3]
[1,] -2 -1 -1
[2,] 7 -5 2
# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)
# Multiply the matrices.
result <- matrix1 * matrix2
cat("Result of multiplication","\n")
print(result)
# Divide the matrices
result <- matrix1 / matrix2
cat("Result of division","\n")
print(result)
When we execute the above code, it produces the following result −
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of multiplication
[,1] [,2] [,3]
[1,] 15 0 6
[2,] 18 36 24
Result of division
[,1] [,2] [,3]
[1,] 0.6 -Inf 0.6666667
[2,] 4.5 0.4444444 1.5000000
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2745,
"s": 2402,
"text": "Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations."
},
{
"code": null,
"e": 2794,
"s": 2745,
"text": "A Matrix is created using the matrix() function."
},
{
"code": null,
"e": 2843,
"s": 2794,
"text": "The basic syntax for creating a matrix in R is −"
},
{
"code": null,
"e": 2886,
"s": 2843,
"text": "matrix(data, nrow, ncol, byrow, dimnames)\n"
},
{
"code": null,
"e": 2940,
"s": 2886,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 3012,
"s": 2940,
"text": "data is the input vector which becomes the data elements of the matrix."
},
{
"code": null,
"e": 3084,
"s": 3012,
"text": "data is the input vector which becomes the data elements of the matrix."
},
{
"code": null,
"e": 3126,
"s": 3084,
"text": "nrow is the number of rows to be created."
},
{
"code": null,
"e": 3168,
"s": 3126,
"text": "nrow is the number of rows to be created."
},
{
"code": null,
"e": 3213,
"s": 3168,
"text": "ncol is the number of columns to be created."
},
{
"code": null,
"e": 3258,
"s": 3213,
"text": "ncol is the number of columns to be created."
},
{
"code": null,
"e": 3343,
"s": 3258,
"text": "byrow is a logical clue. If TRUE then the input vector elements are arranged by row."
},
{
"code": null,
"e": 3428,
"s": 3343,
"text": "byrow is a logical clue. If TRUE then the input vector elements are arranged by row."
},
{
"code": null,
"e": 3483,
"s": 3428,
"text": "dimname is the names assigned to the rows and columns."
},
{
"code": null,
"e": 3538,
"s": 3483,
"text": "dimname is the names assigned to the rows and columns."
},
{
"code": null,
"e": 3591,
"s": 3538,
"text": "Create a matrix taking a vector of numbers as input."
},
{
"code": null,
"e": 4004,
"s": 3591,
"text": "# Elements are arranged sequentially by row.\nM <- matrix(c(3:14), nrow = 4, byrow = TRUE)\nprint(M)\n\n# Elements are arranged sequentially by column.\nN <- matrix(c(3:14), nrow = 4, byrow = FALSE)\nprint(N)\n\n# Define the column and row names.\nrownames = c(\"row1\", \"row2\", \"row3\", \"row4\")\ncolnames = c(\"col1\", \"col2\", \"col3\")\n\nP <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))\nprint(P)"
},
{
"code": null,
"e": 4071,
"s": 4004,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 4372,
"s": 4071,
"text": " [,1] [,2] [,3]\n[1,] 3 4 5\n[2,] 6 7 8\n[3,] 9 10 11\n[4,] 12 13 14\n [,1] [,2] [,3]\n[1,] 3 7 11\n[2,] 4 8 12\n[3,] 5 9 13\n[4,] 6 10 14\n col1 col2 col3\nrow1 3 4 5\nrow2 6 7 8\nrow3 9 10 11\nrow4 12 13 14\n"
},
{
"code": null,
"e": 4527,
"s": 4372,
"text": "Elements of a matrix can be accessed by using the column and row index of the element. We consider the matrix P above to find the specific elements below."
},
{
"code": null,
"e": 4960,
"s": 4527,
"text": "# Define the column and row names.\nrownames = c(\"row1\", \"row2\", \"row3\", \"row4\")\ncolnames = c(\"col1\", \"col2\", \"col3\")\n\n# Create the matrix.\nP <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))\n\n# Access the element at 3rd column and 1st row.\nprint(P[1,3])\n\n# Access the element at 2nd column and 4th row.\nprint(P[4,2])\n\n# Access only the 2nd row.\nprint(P[2,])\n\n# Access only the 3rd column.\nprint(P[,3])"
},
{
"code": null,
"e": 5027,
"s": 4960,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5115,
"s": 5027,
"text": "[1] 5\n[1] 13\ncol1 col2 col3 \n 6 7 8 \nrow1 row2 row3 row4 \n 5 8 11 14 \n"
},
{
"code": null,
"e": 5246,
"s": 5115,
"text": "Various mathematical operations are performed on the matrices using the R operators. The result of the operation is also a matrix."
},
{
"code": null,
"e": 5349,
"s": 5246,
"text": "The dimensions (number of rows and columns) should be same for the matrices involved in the operation."
},
{
"code": null,
"e": 5701,
"s": 5349,
"text": "# Create two 2x3 matrices.\nmatrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)\nprint(matrix1)\n\nmatrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)\nprint(matrix2)\n\n# Add the matrices.\nresult <- matrix1 + matrix2\ncat(\"Result of addition\",\"\\n\")\nprint(result)\n\n# Subtract the matrices\nresult <- matrix1 - matrix2\ncat(\"Result of subtraction\",\"\\n\")\nprint(result)"
},
{
"code": null,
"e": 5768,
"s": 5701,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 6052,
"s": 5768,
"text": " [,1] [,2] [,3]\n[1,] 3 -1 2\n[2,] 9 4 6\n [,1] [,2] [,3]\n[1,] 5 0 3\n[2,] 2 9 4\nResult of addition \n [,1] [,2] [,3]\n[1,] 8 -1 5\n[2,] 11 13 10\nResult of subtraction \n [,1] [,2] [,3]\n[1,] -2 -1 -1\n[2,] 7 -5 2\n"
},
{
"code": null,
"e": 6410,
"s": 6052,
"text": "# Create two 2x3 matrices.\nmatrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)\nprint(matrix1)\n\nmatrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)\nprint(matrix2)\n\n# Multiply the matrices.\nresult <- matrix1 * matrix2\ncat(\"Result of multiplication\",\"\\n\")\nprint(result)\n\n# Divide the matrices\nresult <- matrix1 / matrix2\ncat(\"Result of division\",\"\\n\")\nprint(result)"
},
{
"code": null,
"e": 6477,
"s": 6410,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 6794,
"s": 6477,
"text": " [,1] [,2] [,3]\n[1,] 3 -1 2\n[2,] 9 4 6\n [,1] [,2] [,3]\n[1,] 5 0 3\n[2,] 2 9 4\nResult of multiplication \n [,1] [,2] [,3]\n[1,] 15 0 6\n[2,] 18 36 24\nResult of division \n [,1] [,2] [,3]\n[1,] 0.6 -Inf 0.6666667\n[2,] 4.5 0.4444444 1.5000000\n"
},
{
"code": null,
"e": 6827,
"s": 6794,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6842,
"s": 6827,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6877,
"s": 6842,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6892,
"s": 6877,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6927,
"s": 6892,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6942,
"s": 6927,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6975,
"s": 6942,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6989,
"s": 6975,
"text": " Asif Hussain"
},
{
"code": null,
"e": 7024,
"s": 6989,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7039,
"s": 7024,
"text": " Nishant Malik"
},
{
"code": null,
"e": 7074,
"s": 7039,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7088,
"s": 7074,
"text": " Asif Hussain"
},
{
"code": null,
"e": 7095,
"s": 7088,
"text": " Print"
},
{
"code": null,
"e": 7106,
"s": 7095,
"text": " Add Notes"
}
] |
swap() function in C++
|
The swap() function is used to swap two numbers. By using this function, you do not need any third variable to swap two numbers.
Here is the syntax of swap() in C++ language,
void swap(int variable_name1, int variable_name2);
If we assign the values to variables or pass user-defined values, it will swap the values of variables but the value of variables will remain same at the actual place.
Here is an example of swap() in C++ language,
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
int x = 35, y = 75;
printf("Value of x :%d",x);
printf("\nValue of y :%d",y);
swap(x, y);
printf("\nAfter swapping, the values are: x = %d, y = %d", x, y);
return 0;
}
Value of x :35
Value of y :75
After swapping, the values are: x = 75, y = 35
It is better that we pass the values to the variables by reference, it will swap the values of variables at actual place.
Here is another example of swap() in C++ language,
Live Demo
#include <stdio.h>
void SwapValue(int &a, int &b) {
int t = a;
a = b;
b = t;
}
int main() {
int a, b;
printf("Enter value of a : ");
scanf("%d", &a);
printf("\nEnter value of b : ");
scanf("%d", &b);
SwapValue(a, b);
printf("\nAfter swapping, the values are: a = %d, b = %d", a, b);
return 0;
}
Enter value of a : 8
Enter value of b : 28
After swapping, the values are: a = 28, b = 8
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "The swap() function is used to swap two numbers. By using this function, you do not need any third variable to swap two numbers."
},
{
"code": null,
"e": 1237,
"s": 1191,
"text": "Here is the syntax of swap() in C++ language,"
},
{
"code": null,
"e": 1288,
"s": 1237,
"text": "void swap(int variable_name1, int variable_name2);"
},
{
"code": null,
"e": 1456,
"s": 1288,
"text": "If we assign the values to variables or pass user-defined values, it will swap the values of variables but the value of variables will remain same at the actual place."
},
{
"code": null,
"e": 1502,
"s": 1456,
"text": "Here is an example of swap() in C++ language,"
},
{
"code": null,
"e": 1513,
"s": 1502,
"text": " Live Demo"
},
{
"code": null,
"e": 1758,
"s": 1513,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n int x = 35, y = 75;\n printf(\"Value of x :%d\",x);\n printf(\"\\nValue of y :%d\",y);\n swap(x, y);\n printf(\"\\nAfter swapping, the values are: x = %d, y = %d\", x, y);\n return 0;\n}"
},
{
"code": null,
"e": 1835,
"s": 1758,
"text": "Value of x :35\nValue of y :75\nAfter swapping, the values are: x = 75, y = 35"
},
{
"code": null,
"e": 1957,
"s": 1835,
"text": "It is better that we pass the values to the variables by reference, it will swap the values of variables at actual place."
},
{
"code": null,
"e": 2008,
"s": 1957,
"text": "Here is another example of swap() in C++ language,"
},
{
"code": null,
"e": 2019,
"s": 2008,
"text": " Live Demo"
},
{
"code": null,
"e": 2347,
"s": 2019,
"text": "#include <stdio.h>\nvoid SwapValue(int &a, int &b) {\n int t = a;\n a = b;\n b = t;\n}\nint main() {\n int a, b;\n printf(\"Enter value of a : \");\n scanf(\"%d\", &a);\n printf(\"\\nEnter value of b : \");\n scanf(\"%d\", &b);\n SwapValue(a, b);\n printf(\"\\nAfter swapping, the values are: a = %d, b = %d\", a, b);\n return 0;\n}"
},
{
"code": null,
"e": 2436,
"s": 2347,
"text": "Enter value of a : 8\nEnter value of b : 28\nAfter swapping, the values are: a = 28, b = 8"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.