title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
cauchy_distribution a() in C++ with Examples - GeeksforGeeks
16 Oct, 2018 The cauchy_distribution::a() function is an inbuilt function in C++ STL which is used to returns the distribution parameter associated with Cauchy distribution. The class cauchy_distribution is present in header file random. Before going to the syntax of the function, brief introduction to Cauchy Distribution. Cauchy Distribution A random variable X is said to follow Cauchy Distribution with parameter a and b if it has the probability density function of the form, Where a is the location parameter specifying the location of peak of the distribution and b is the scale parameter specifying the half-width at half-maximum. Mean and Variance of the distribution is not defined, but its median and mode both exists and equals to a. Syntax: cauchy_distribution_name.a() Parameters: This function does not accepts any parameter. Return Value: The function returns the distribution parameter associated with the distribution. This parameter is known as the peak location parameter of the Cauchy distribution, which determines the shift to either side of the distribution shape. The parameter is set on construction. Below programs illustrates the cauchy_distribution::a() function in C++ STL: Program 1: // CPP program to illustrate// cauchy_distribution::a()#include <iostream>#include <random>using namespace std; // Driver programint main(){ default_random_engine generator; cauchy_distribution<double> d(0.78, 1.45); // prints the first value cout << "Cauchy distribution: " << d.a(); return 0;} Cauchy distribution: 0.78 Program 2: // CPP program to illustrate// cauchy_distribution::a()#include <iostream>#include <random>using namespace std; // Driver programint main(){ default_random_engine generator; // Define a cauchy distribution with default // parameters a=0.0 and b=1.0 cauchy_distribution<double> d; // prints the first value cout << "Cauchy distribution: " << d.a(); return 0;} Cauchy distribution: 0 cpp-math STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24208, "s": 24180, "text": "\n16 Oct, 2018" }, { "code": null, "e": 24520, "s": 24208, "text": "The cauchy_distribution::a() function is an inbuilt function in C++ STL which is used to returns the distribution parameter associated with Cauchy distribution. The class cauchy_distribution is present in header file random. Before going to the syntax of the function, brief introduction to Cauchy Distribution." }, { "code": null, "e": 24677, "s": 24520, "text": "Cauchy Distribution A random variable X is said to follow Cauchy Distribution with parameter a and b if it has the probability density function of the form," }, { "code": null, "e": 24942, "s": 24677, "text": "Where a is the location parameter specifying the location of peak of the distribution and b is the scale parameter specifying the half-width at half-maximum. Mean and Variance of the distribution is not defined, but its median and mode both exists and equals to a." }, { "code": null, "e": 24950, "s": 24942, "text": "Syntax:" }, { "code": null, "e": 24979, "s": 24950, "text": "cauchy_distribution_name.a()" }, { "code": null, "e": 25037, "s": 24979, "text": "Parameters: This function does not accepts any parameter." }, { "code": null, "e": 25323, "s": 25037, "text": "Return Value: The function returns the distribution parameter associated with the distribution. This parameter is known as the peak location parameter of the Cauchy distribution, which determines the shift to either side of the distribution shape. The parameter is set on construction." }, { "code": null, "e": 25400, "s": 25323, "text": "Below programs illustrates the cauchy_distribution::a() function in C++ STL:" }, { "code": null, "e": 25411, "s": 25400, "text": "Program 1:" }, { "code": "// CPP program to illustrate// cauchy_distribution::a()#include <iostream>#include <random>using namespace std; // Driver programint main(){ default_random_engine generator; cauchy_distribution<double> d(0.78, 1.45); // prints the first value cout << \"Cauchy distribution: \" << d.a(); return 0;}", "e": 25727, "s": 25411, "text": null }, { "code": null, "e": 25754, "s": 25727, "text": "Cauchy distribution: 0.78\n" }, { "code": null, "e": 25765, "s": 25754, "text": "Program 2:" }, { "code": "// CPP program to illustrate// cauchy_distribution::a()#include <iostream>#include <random>using namespace std; // Driver programint main(){ default_random_engine generator; // Define a cauchy distribution with default // parameters a=0.0 and b=1.0 cauchy_distribution<double> d; // prints the first value cout << \"Cauchy distribution: \" << d.a(); return 0;}", "e": 26153, "s": 25765, "text": null }, { "code": null, "e": 26177, "s": 26153, "text": "Cauchy distribution: 0\n" }, { "code": null, "e": 26186, "s": 26177, "text": "cpp-math" }, { "code": null, "e": 26190, "s": 26186, "text": "STL" }, { "code": null, "e": 26201, "s": 26190, "text": "C Language" }, { "code": null, "e": 26205, "s": 26201, "text": "C++" }, { "code": null, "e": 26209, "s": 26205, "text": "STL" }, { "code": null, "e": 26213, "s": 26209, "text": "CPP" }, { "code": null, "e": 26311, "s": 26213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26320, "s": 26311, "text": "Comments" }, { "code": null, "e": 26333, "s": 26320, "text": "Old Comments" }, { "code": null, "e": 26371, "s": 26333, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26397, "s": 26371, "text": "Exception Handling in C++" }, { "code": null, "e": 26417, "s": 26397, "text": "Multithreading in C" }, { "code": null, "e": 26439, "s": 26417, "text": "'this' pointer in C++" }, { "code": null, "e": 26477, "s": 26439, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26495, "s": 26477, "text": "Vector in C++ STL" }, { "code": null, "e": 26514, "s": 26495, "text": "Inheritance in C++" }, { "code": null, "e": 26560, "s": 26514, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 26603, "s": 26560, "text": "Map in C++ Standard Template Library (STL)" } ]
BabylonJS - Environment Setup
In this chapter, we will learn how to set up the environment for BabylonJS. To start with the setup, visit the official website of Babylon.js − www.babylonjs.com. Go to the download section and choose the latest version of Babylon.js and store in your folder. The screenshot for the same is as follows − You can also go to GITHUB and clone the babylonjs project − Babylon.js In your command line type − git clone https://github.com/BabylonJS/Babylon.js.git go to cd BabylonJS/ npm install The required files will be available in the BabylonJS folder. You can use the VSCode (Microsoft Visual Studio Code) for editing.The code comes with builtin functionalities like highlighting if any error, hightlighting the syntax, etc. You can use the editor of your choice and it is not mandatory to use only VSCode. Print Add Notes Bookmark this page
[ { "code": null, "e": 2259, "s": 2183, "text": "In this chapter, we will learn how to set up the environment for BabylonJS." }, { "code": null, "e": 2443, "s": 2259, "text": "To start with the setup, visit the official website of Babylon.js − www.babylonjs.com. Go to the download section and choose the latest version of Babylon.js and store in your folder." }, { "code": null, "e": 2487, "s": 2443, "text": "The screenshot for the same is as follows −" }, { "code": null, "e": 2547, "s": 2487, "text": "You can also go to GITHUB and clone the babylonjs project −" }, { "code": null, "e": 2558, "s": 2547, "text": "Babylon.js" }, { "code": null, "e": 2587, "s": 2558, "text": "In your command line type −" }, { "code": null, "e": 2674, "s": 2587, "text": "git clone https://github.com/BabylonJS/Babylon.js.git\ngo to cd BabylonJS/\nnpm install\n" }, { "code": null, "e": 2736, "s": 2674, "text": "The required files will be available in the BabylonJS folder." }, { "code": null, "e": 2991, "s": 2736, "text": "You can use the VSCode (Microsoft Visual Studio Code) for editing.The code comes with builtin functionalities like highlighting if any error, hightlighting the syntax, etc. You can use the editor of your choice and it is not mandatory to use only VSCode." }, { "code": null, "e": 2998, "s": 2991, "text": " Print" }, { "code": null, "e": 3009, "s": 2998, "text": " Add Notes" } ]
Using EXPLAIN keyword in MySQL
MySQL EXPLAIN gives a query execution plan. EXPLAIN can be used in the beginning with SELECT, INSERT, DELETE, REPLACE, and UPDATE. To avoid the complete table scan in database, you need to use index. Let us first create a table − mysql> create table DemoTable1488 -> ( -> StudentId int, -> StudentName varchar(20), -> StudentAge int -> ); Query OK, 0 rows affected (2.18 sec) Here is the query to create index − mysql> create index student_id_index on DemoTable1488(StudentId); Query OK, 0 rows affected (0.90 sec) Records: 0 Duplicates: 0 Warnings: 0 insert into DemoTable1488 valueInsert some records in the table using insert command − mysql> insert into DemoTable1488 values(101,'Sam',21); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable1488 values(102,'Bob',23); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable1488 values(103,'David',20); Query OK, 1 row affected (0.21 sec) Display all records from the table using select statement − mysql> select * from DemoTable1488; This will produce the following output − +-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 101 | Sam | 21 | | 102 | Bob | 23 | | 103 | David | 20 | +-----------+-------------+------------+ 3 rows in set (0.00 sec) Now, use EXPLAIN − mysql> explain select * from DemoTable1488 where StudentId=1; This will produce the following output − +----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+ | 1 | SIMPLE | DemoTable1488 | NULL | ref | student_id_index | student_id_index | 5 | const | 1 | 100.00 | NULL | +----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+ 1 row in set, 1 warning (0.00 sec)
[ { "code": null, "e": 1193, "s": 1062, "text": "MySQL EXPLAIN gives a query execution plan. EXPLAIN can be used in the beginning with SELECT, INSERT, DELETE, REPLACE, and UPDATE." }, { "code": null, "e": 1292, "s": 1193, "text": "To avoid the complete table scan in database, you need to use index. Let us first create a table −" }, { "code": null, "e": 1453, "s": 1292, "text": "mysql> create table DemoTable1488\n -> (\n -> StudentId int,\n -> StudentName varchar(20),\n -> StudentAge int\n -> );\nQuery OK, 0 rows affected (2.18 sec)" }, { "code": null, "e": 1489, "s": 1453, "text": "Here is the query to create index −" }, { "code": null, "e": 1631, "s": 1489, "text": "mysql> create index student_id_index on DemoTable1488(StudentId);\nQuery OK, 0 rows affected (0.90 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1718, "s": 1631, "text": "insert into DemoTable1488 valueInsert some records in the table using insert command −" }, { "code": null, "e": 1993, "s": 1718, "text": "mysql> insert into DemoTable1488 values(101,'Sam',21);\nQuery OK, 1 row affected (0.32 sec)\nmysql> insert into DemoTable1488 values(102,'Bob',23);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable1488 values(103,'David',20);\nQuery OK, 1 row affected (0.21 sec)" }, { "code": null, "e": 2053, "s": 1993, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2089, "s": 2053, "text": "mysql> select * from DemoTable1488;" }, { "code": null, "e": 2130, "s": 2089, "text": "This will produce the following output −" }, { "code": null, "e": 2442, "s": 2130, "text": "+-----------+-------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+-------------+------------+\n| 101 | Sam | 21 |\n| 102 | Bob | 23 |\n| 103 | David | 20 |\n+-----------+-------------+------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2461, "s": 2442, "text": "Now, use EXPLAIN −" }, { "code": null, "e": 2523, "s": 2461, "text": "mysql> explain select * from DemoTable1488 where StudentId=1;" }, { "code": null, "e": 2564, "s": 2523, "text": "This will produce the following output −" }, { "code": null, "e": 3293, "s": 2564, "text": "+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+\n| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |\n+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+\n| 1 | SIMPLE | DemoTable1488 | NULL | ref | student_id_index | student_id_index | 5 | const | 1 | 100.00 | NULL |\n+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+\n1 row in set, 1 warning (0.00 sec)" } ]
How to deal with error “var(x) : Calling var(x) on a factor x is defunct.” in R?
The error “Calling var(x) on a factor x is defunct” occurs when we try to apply a numerical function on factor data. For example, if we have a factor column in a data frame then applying numerical functions on that column would result in the above error. To deal with this problem, we can use as.numeric function along with the numerical function as shown in the below examples. Following snippet creates a sample data frame − x<-factor(rpois(20,5)) df<-data.frame(x) df The following dataframe is created − x 1 7 2 3 3 7 4 4 5 7 6 6 7 4 8 6 9 8 10 2 11 6 12 6 13 9 14 5 15 3 16 4 17 10 18 2 19 4 20 2 Now, in order to apply t test on data in x, add the following code to the above snippet − t.test(df$x,mu=2) If you execute all the above given snippets as a single program, it generates the following Output − Error in var(x) : Calling var(x) on a factor x is defunct. Hence, use something like the following ' to test for a constant vector. 'all(duplicated(x)[-1L]) If you execute all the above given snippets as a single program, it generates the following Output − In addition: Warning message: In mean.default(x) : argument is not numeric or logical: returning NA Now, use as.numeric function on x while applying t.test function and add the following code to the above snippet − t.test(as.numeric(df$x),mu=2) If you execute all the above given snippets as a single program, it generates the following Outpu for the one sample t-test − data: as.numeric(df$x) t = 4.3061, df = 19, p-value = 0.0003811 alternative hypothesis: true mean is not equal to 2 95 percent confidence interval: 3.156355 5.343645 sample estimates: mean of x 4.25 Following snippet creates a sample data frame − y<-factor(rpois(20,2)) dat<-data.frame(y) dat The following dataframe is created − y 1 1 2 2 3 4 4 4 5 2 6 0 7 0 8 1 9 3 10 0 11 2 12 0 13 0 14 2 15 2 16 2 17 2 18 0 19 4 20 2 Now, in order to apply t test on data, add the following code to the above snippet − t.test(dat$y,mu=0) If you execute all the above given snippets as a single program, it generates the following output − Error in var(x) : Calling var(x) on a factor x is defunct. Use something like the following to test for a constant vector − 'all(duplicated(x)[-1L])' If you execute all the above given snippets as a single program, it generates the following Output − In addition: Warning message: In mean.default(x) : argument is not numeric or logical: returning NA Now, use as.numeric function on y while applying t.test function, add the following code to the above snippet − t.test(as.numeric(dat$y),mu=0) If you execute all the above given snippets as a single program, it generates the following Output for the one sample t-test − data: as.numeric(dat$y) t = 8.5446, df = 19, p-value = 6.216e-08 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 2.000878 3.299122 sample estimates: mean of x 2.65
[ { "code": null, "e": 1179, "s": 1062, "text": "The error “Calling var(x) on a factor x is defunct” occurs when we try to apply a numerical function on factor data." }, { "code": null, "e": 1441, "s": 1179, "text": "For example, if we have a factor column in a data frame then applying numerical functions on that column would result in the above error. To deal with this problem, we can use as.numeric function along with the numerical function as shown in the below examples." }, { "code": null, "e": 1489, "s": 1441, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1533, "s": 1489, "text": "x<-factor(rpois(20,5))\ndf<-data.frame(x)\ndf" }, { "code": null, "e": 1570, "s": 1533, "text": "The following dataframe is created −" }, { "code": null, "e": 1696, "s": 1570, "text": " x\n1 7\n2 3\n3 7\n4 4\n5 7\n6 6\n7 4\n8 6\n9 8\n10 2\n11 6\n12 6\n13 9\n14 5\n15 3\n16 4\n17 10\n18 2\n19 4\n20 2" }, { "code": null, "e": 1786, "s": 1696, "text": "Now, in order to apply t test on data in x, add the following code to the above snippet −" }, { "code": null, "e": 1804, "s": 1786, "text": "t.test(df$x,mu=2)" }, { "code": null, "e": 1905, "s": 1804, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 1964, "s": 1905, "text": "Error in var(x) : Calling var(x) on a factor x is defunct." }, { "code": null, "e": 2037, "s": 1964, "text": "Hence, use something like the following ' to test for a constant vector." }, { "code": null, "e": 2062, "s": 2037, "text": "'all(duplicated(x)[-1L])" }, { "code": null, "e": 2163, "s": 2062, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 2263, "s": 2163, "text": "In addition: Warning message:\nIn mean.default(x) : argument is not numeric or logical: returning NA" }, { "code": null, "e": 2378, "s": 2263, "text": "Now, use as.numeric function on x while applying t.test function and add the following code to the above snippet −" }, { "code": null, "e": 2408, "s": 2378, "text": "t.test(as.numeric(df$x),mu=2)" }, { "code": null, "e": 2534, "s": 2408, "text": "If you execute all the above given snippets as a single program, it generates the following Outpu for the one sample t-test −" }, { "code": null, "e": 2739, "s": 2534, "text": "data: as.numeric(df$x)\nt = 4.3061, df = 19, p-value = 0.0003811\nalternative hypothesis: true mean is not equal to 2\n95 percent confidence interval:\n 3.156355 5.343645\nsample estimates:\nmean of x\n 4.25" }, { "code": null, "e": 2787, "s": 2739, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 2833, "s": 2787, "text": "y<-factor(rpois(20,2))\ndat<-data.frame(y)\ndat" }, { "code": null, "e": 2870, "s": 2833, "text": "The following dataframe is created −" }, { "code": null, "e": 2996, "s": 2870, "text": " y\n1 1\n2 2\n3 4\n4 4\n5 2\n6 0\n7 0\n8 1\n9 3\n10 0\n11 2\n12 0\n13 0\n14 2\n15 2\n16 2\n17 2\n18 0\n19 4\n20 2" }, { "code": null, "e": 3081, "s": 2996, "text": "Now, in order to apply t test on data, add the following code to the above snippet −" }, { "code": null, "e": 3100, "s": 3081, "text": "t.test(dat$y,mu=0)" }, { "code": null, "e": 3201, "s": 3100, "text": "If you execute all the above given snippets as a single program, it generates the following output −" }, { "code": null, "e": 3260, "s": 3201, "text": "Error in var(x) : Calling var(x) on a factor x is defunct." }, { "code": null, "e": 3325, "s": 3260, "text": "Use something like the following to test for a constant vector −" }, { "code": null, "e": 3351, "s": 3325, "text": "'all(duplicated(x)[-1L])'" }, { "code": null, "e": 3452, "s": 3351, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 3552, "s": 3452, "text": "In addition: Warning message:\nIn mean.default(x) : argument is not numeric or logical: returning NA" }, { "code": null, "e": 3664, "s": 3552, "text": "Now, use as.numeric function on y while applying t.test function, add the following code to the above snippet −" }, { "code": null, "e": 3695, "s": 3664, "text": "t.test(as.numeric(dat$y),mu=0)" }, { "code": null, "e": 3822, "s": 3695, "text": "If you execute all the above given snippets as a single program, it generates the following Output for the one sample t-test −" }, { "code": null, "e": 4028, "s": 3822, "text": "data: as.numeric(dat$y)\nt = 8.5446, df = 19, p-value = 6.216e-08\nalternative hypothesis: true mean is not equal to 0\n95 percent confidence interval:\n 2.000878 3.299122\nsample estimates:\nmean of x\n 2.65" } ]
Program to find number of combinations of coins to reach target in Python
Suppose we have a list of coins and another value amount, we have to find the number of combinations there are that sum to amount. If the answer is very large, then mod the result by 10^9 + 7. So, if the input is like coins = [2, 5] amount = 10, then the output will be 2, as we can make these combinations − [2, 2, 2, 2, 2], [5, 5] To solve this, we will follow these steps − m := 10^9 + 7 dp := a list of size same as amount + 1, and fill it with 0 dp[0] := 1 for each d in coins, dofor i in range 1 to size of dp, doif i - d >= 0, thendp[i] := dp[i] + dp[i - d] for i in range 1 to size of dp, doif i - d >= 0, thendp[i] := dp[i] + dp[i - d] if i - d >= 0, thendp[i] := dp[i] + dp[i - d] dp[i] := dp[i] + dp[i - d] return (last element of dp) mod m Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, coins, amount): dp = [0] * (amount + 1) dp[0] = 1 for d in coins: for i in range(1, len(dp)): if i - d >= 0: dp[i] += dp[i - d] return dp[-1] % (10 ** 9 + 7) ob = Solution() coins = [2, 5] amount = 10 print(ob.solve(coins, amount)) [2, 5], 10 2
[ { "code": null, "e": 1255, "s": 1062, "text": "Suppose we have a list of coins and another value amount, we have to find the number of combinations there are that sum to amount. If the answer is very large, then mod the result by 10^9 + 7." }, { "code": null, "e": 1395, "s": 1255, "text": "So, if the input is like coins = [2, 5] amount = 10, then the output will be 2, as we can make these combinations − [2, 2, 2, 2, 2], [5, 5]" }, { "code": null, "e": 1439, "s": 1395, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1453, "s": 1439, "text": "m := 10^9 + 7" }, { "code": null, "e": 1513, "s": 1453, "text": "dp := a list of size same as amount + 1, and fill it with 0" }, { "code": null, "e": 1524, "s": 1513, "text": "dp[0] := 1" }, { "code": null, "e": 1627, "s": 1524, "text": "for each d in coins, dofor i in range 1 to size of dp, doif i - d >= 0, thendp[i] := dp[i] + dp[i - d]" }, { "code": null, "e": 1707, "s": 1627, "text": "for i in range 1 to size of dp, doif i - d >= 0, thendp[i] := dp[i] + dp[i - d]" }, { "code": null, "e": 1753, "s": 1707, "text": "if i - d >= 0, thendp[i] := dp[i] + dp[i - d]" }, { "code": null, "e": 1780, "s": 1753, "text": "dp[i] := dp[i] + dp[i - d]" }, { "code": null, "e": 1814, "s": 1780, "text": "return (last element of dp) mod m" }, { "code": null, "e": 1884, "s": 1814, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1895, "s": 1884, "text": " Live Demo" }, { "code": null, "e": 2222, "s": 1895, "text": "class Solution:\n def solve(self, coins, amount):\n dp = [0] * (amount + 1)\n dp[0] = 1\n for d in coins:\n for i in range(1, len(dp)):\n if i - d >= 0:\n dp[i] += dp[i - d]\n return dp[-1] % (10 ** 9 + 7)\nob = Solution()\ncoins = [2, 5]\namount = 10\nprint(ob.solve(coins, amount))" }, { "code": null, "e": 2233, "s": 2222, "text": "[2, 5], 10" }, { "code": null, "e": 2235, "s": 2233, "text": "2" } ]
Contextual Emotion Detection in Textual Conversations Using Neural Networks | by Sergey Smetanin | Towards Data Science
Nowadays, talking to conversational agents is becoming a daily routine, and it is crucial for dialogue systems to generate responses as human-like as possible. As one of the main aspects, primary attention should be given to providing emotionally aware responses to users. In this article, we are going to describe the recurrent neural network architecture for emotion detection in textual conversations, that participated in SemEval-2019 Task 3 “EmoContext”, that is, an annual workshop on semantic evaluation. The task objective is to classify emotion (i.e. happy, sad, angry, and others) in a 3-turn conversational data set. The rest of the article is organized as follows. Section 1 gives a brief overview of the EmoContext task and the provided data. Sections 2 and 3 focus on the texts pre-processing and word embeddings, consequently. In section 4, we described the architecture of the LSTM model used in our submission. In conclusion, the final performance of our system and the source code are presented. The model is implemented in Python using Keras library. The SemEval-2019 Task 3 “EmoContext” is focused on the contextual emotion detection in textual conversation. In EmoContext, given a textual user utterance along with 2 turns of context in a conversation, we must classify whether the emotion of the next user utterance is “happy”, “sad”, “angry” or “others” (Table 1). There are only two conversation participants: an anonymous person (Tuen-1 and Turn-3) and the AI-based chatbot Ruuh (Turn-2). For a detailed description, see (Chatterjee et al., 2019). During the competition, we had access to 30160 human-labeled texts provided by task organizers, where about 5000 samples each from “angry”, “sad”, “happy” class and 15000 for “others” class (Table 2). Dev and test sets, which were also provided by organizers, in contrast with a train set, have a real-life distribution, which is about 4% for each emotional class and the rest for the “others” class. Data provided by Microsoft and can be found in the official LinkedIn group. In addition to this data, we collected 900k English tweets in order to create a distant dataset of 300k tweets for each emotion. To form the distant dataset, we based on the strategy of Go et al. (2009), under which we simply associate tweets with the presence of emotion-related words such as ‘#angry’, ‘#annoyed’, ‘#happy’, ‘#sad, ‘#surprised’, etc. The list of query terms was based on the query terms of SemEval-2018 AIT DISC (Duppada et al., 2018). The key performance metric of EmoContext is a micro-average F1 score for three emotion classes, i.e. ‘sad’, ‘happy’, and ‘angry’. Before any training stage, texts were pre-processed by text tool Ekphrasis (Baziotis et al., 2017). This tool helps to perform spell correction, word normalization, segmentation, and allows to specify which tokens should be omitted, normalized or annotated with special tags. We used the following techniques for the pre-processing stage. URLs, emails, the date and time, usernames, percentage, currencies, and numbers were replaced with the corresponding tags. Repeated, censored, elongated, and capitalized terms were annotated with the corresponding tags. Elongated words were automatically corrected based on built-in word statistics corpus. Hashtags and contractions unpacking (i.e. word segmentation) was performed based on built-in word statistics corpus. A manually created dictionary for replacing terms extracted from the text was used in order to reduce a variety of emotions. In addition, Emphasis provides with the tokenizer which is able to identify most emojis, emoticons, and complicated expressions such as censored, emphasized and elongated words as well as dates, times, currencies, and acronyms. Word embeddings have become an essential part of any deep-learning approaches for NLP systems. To determine the most suitable vectors for emotions detection task, we try Word2Vec (Mikolov et al., 2013), GloVe (Pennington et al., 2014) and FastText (Joulin et al., 2017) models as well as DataStories pre-trained word vectors (Baziotis et al., 2017). The key concept of Word2Vec is to locate words, which share common contexts in the training corpus, in close proximity in vector space. Both Word2Vec and Glove models learn geometrical encodings of words from their co-occurrence information, but essentially the former is a predictive model, and the latter is a count-based model. In other words, while Word2Vec tries to predict a target word (CBOW architecture) or a context (Skip-gram architecture), i.e. to minimize the loss function, GloVe calculates word vectors doing dimensionality reduction on the co-occurrence counts matrix. FastText is very similar to Word2Vec except for the fact that it uses character n-grams in order to learn word vectors, so it’s able to solve the out-of-vocabulary issue. For all the techniques mentioned above, we used the default training prams provided by the authors. We train a simple LSTM model (dim = 64) based on each of these embeddings and compare effectiveness using cross-validation. According to the result, DataStories pre-trained embeddings demonstrated the best average F1 score. To enrich selected word embeddings with the emotional polarity of the words, we consider performing distant pre-training phrase by a fine-tuning of the embeddings on the automatically labelled distant dataset. The importance of using pre-training was demonstrated in (Deriu et al., 2017). We use the distant dataset to train the simple LSTM network to classify angry, sad, and happy tweets. The embeddings layer was frozen for the first training epoch in order to avoid significant changes in the embeddings weights, and then it was unfrozen for the next 5 epochs. After the training stage, the fine-tuned embeddings was saved for the further training phases and made publicly available. A recurrent neural network (RNN) is a family of artificial neural networks which is specialized in the processing of sequential data. In contrast with traditional neural networks, RRNs are designed to deal with sequential data by sharing their internal weights processing the sequence. For this purpose, the computation graph of RRNs includes cycles, representing the influence of the previous information on the present one. As an extension of RNNs, Long Short-Term Memory networks (LSTMs) have been introduced in 1997 (Hochreiter and Schmidhuber, 1997). In LSTMs recurrent cells are connected in a particular way to avoid vanishing and exploding gradient issues. Traditional LSTMs only preserves information from the past since they process the sequence only in one direction. Bidirectional LSTMs combine output from two hidden LSTM layers moving in opposite directions, where one moves forward through time, and another moves backward through time, thereby enabling to capture information from both past and future states simultaneously (Schuster and Paliwal, 1997). A high-level overview of our approach is provided in Figure 1. The proposed architecture of the neural network consists of the embedding unit and two bidirectional LSTM units (dim = 64). The former LSTM unit is intended to analyze the utterance of the first user (i.e. the first turn and the third turn of the conversation), and the latter is intended to analyze the utterance of the second user (i.e. the second turn). These two units learn not only semantic and sentiment feature representation, but also how to capture user-specific conversation features, which allows classifying emotions more accurately. At the first step, each user utterance is fed into a corresponding bidirectional LSTM unit using pre-trained word embeddings. Next, these three feature maps are concatenated in a flatten feature vector and then passed to a fully connected hidden layer (dim = 30), which analyzes interactions between obtained vectors. Finally, these features proceed through the output layer with the softmax activation function to predict a final class label. To reduce overfitting, regularization layers with Gaussian noise were added after the embedding layer, dropout layers (Srivastava et al., 2014) were added at each LSTM unit (p = 0.2) and before the hidden fully connected layer (p = 0.1). In the process of searching for optimal architecture, we experimented not only with the number of cells in layers, activation functions and regularization parameters but also with the architecture of the neural network. The detailed info about this phrase can be found in the original paper. The model described in the previous section demonstrated the best scores on the dev dataset, so it was used in the final evaluation stage of the competition. On the final test dataset, it achieved 72.59% micro-average F1 score for emotional classes, while the maximum score among all participants was 79.59%. However, this is well above the official baseline released by task organizers, which was 58,68%. The source code of the model and word-embeddings are available at GitHub. github.com The full version of the article and the task description paper can be found at ACL Anthology.The training dataset is located at the official competition group at LinkedIn. Citation: @inproceedings{ smetanin-2019-emosense, title = "{E}mo{S}ense at {S}em{E}val-2019 Task 3: Bidirectional {LSTM} Network for Contextual Emotion Detection in Textual Conversations", author = "Smetanin, Sergey", booktitle = "Proceedings of the 13th International Workshop on Semantic Evaluation", year = "2019", address = "Minneapolis, Minnesota, USA", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/S19-2034", pages = "210--214"}
[ { "code": null, "e": 799, "s": 171, "text": "Nowadays, talking to conversational agents is becoming a daily routine, and it is crucial for dialogue systems to generate responses as human-like as possible. As one of the main aspects, primary attention should be given to providing emotionally aware responses to users. In this article, we are going to describe the recurrent neural network architecture for emotion detection in textual conversations, that participated in SemEval-2019 Task 3 “EmoContext”, that is, an annual workshop on semantic evaluation. The task objective is to classify emotion (i.e. happy, sad, angry, and others) in a 3-turn conversational data set." }, { "code": null, "e": 1241, "s": 799, "text": "The rest of the article is organized as follows. Section 1 gives a brief overview of the EmoContext task and the provided data. Sections 2 and 3 focus on the texts pre-processing and word embeddings, consequently. In section 4, we described the architecture of the LSTM model used in our submission. In conclusion, the final performance of our system and the source code are presented. The model is implemented in Python using Keras library." }, { "code": null, "e": 1744, "s": 1241, "text": "The SemEval-2019 Task 3 “EmoContext” is focused on the contextual emotion detection in textual conversation. In EmoContext, given a textual user utterance along with 2 turns of context in a conversation, we must classify whether the emotion of the next user utterance is “happy”, “sad”, “angry” or “others” (Table 1). There are only two conversation participants: an anonymous person (Tuen-1 and Turn-3) and the AI-based chatbot Ruuh (Turn-2). For a detailed description, see (Chatterjee et al., 2019)." }, { "code": null, "e": 2221, "s": 1744, "text": "During the competition, we had access to 30160 human-labeled texts provided by task organizers, where about 5000 samples each from “angry”, “sad”, “happy” class and 15000 for “others” class (Table 2). Dev and test sets, which were also provided by organizers, in contrast with a train set, have a real-life distribution, which is about 4% for each emotional class and the rest for the “others” class. Data provided by Microsoft and can be found in the official LinkedIn group." }, { "code": null, "e": 2675, "s": 2221, "text": "In addition to this data, we collected 900k English tweets in order to create a distant dataset of 300k tweets for each emotion. To form the distant dataset, we based on the strategy of Go et al. (2009), under which we simply associate tweets with the presence of emotion-related words such as ‘#angry’, ‘#annoyed’, ‘#happy’, ‘#sad, ‘#surprised’, etc. The list of query terms was based on the query terms of SemEval-2018 AIT DISC (Duppada et al., 2018)." }, { "code": null, "e": 2805, "s": 2675, "text": "The key performance metric of EmoContext is a micro-average F1 score for three emotion classes, i.e. ‘sad’, ‘happy’, and ‘angry’." }, { "code": null, "e": 3144, "s": 2805, "text": "Before any training stage, texts were pre-processed by text tool Ekphrasis (Baziotis et al., 2017). This tool helps to perform spell correction, word normalization, segmentation, and allows to specify which tokens should be omitted, normalized or annotated with special tags. We used the following techniques for the pre-processing stage." }, { "code": null, "e": 3267, "s": 3144, "text": "URLs, emails, the date and time, usernames, percentage, currencies, and numbers were replaced with the corresponding tags." }, { "code": null, "e": 3364, "s": 3267, "text": "Repeated, censored, elongated, and capitalized terms were annotated with the corresponding tags." }, { "code": null, "e": 3451, "s": 3364, "text": "Elongated words were automatically corrected based on built-in word statistics corpus." }, { "code": null, "e": 3568, "s": 3451, "text": "Hashtags and contractions unpacking (i.e. word segmentation) was performed based on built-in word statistics corpus." }, { "code": null, "e": 3693, "s": 3568, "text": "A manually created dictionary for replacing terms extracted from the text was used in order to reduce a variety of emotions." }, { "code": null, "e": 3921, "s": 3693, "text": "In addition, Emphasis provides with the tokenizer which is able to identify most emojis, emoticons, and complicated expressions such as censored, emphasized and elongated words as well as dates, times, currencies, and acronyms." }, { "code": null, "e": 5027, "s": 3921, "text": "Word embeddings have become an essential part of any deep-learning approaches for NLP systems. To determine the most suitable vectors for emotions detection task, we try Word2Vec (Mikolov et al., 2013), GloVe (Pennington et al., 2014) and FastText (Joulin et al., 2017) models as well as DataStories pre-trained word vectors (Baziotis et al., 2017). The key concept of Word2Vec is to locate words, which share common contexts in the training corpus, in close proximity in vector space. Both Word2Vec and Glove models learn geometrical encodings of words from their co-occurrence information, but essentially the former is a predictive model, and the latter is a count-based model. In other words, while Word2Vec tries to predict a target word (CBOW architecture) or a context (Skip-gram architecture), i.e. to minimize the loss function, GloVe calculates word vectors doing dimensionality reduction on the co-occurrence counts matrix. FastText is very similar to Word2Vec except for the fact that it uses character n-grams in order to learn word vectors, so it’s able to solve the out-of-vocabulary issue." }, { "code": null, "e": 5351, "s": 5027, "text": "For all the techniques mentioned above, we used the default training prams provided by the authors. We train a simple LSTM model (dim = 64) based on each of these embeddings and compare effectiveness using cross-validation. According to the result, DataStories pre-trained embeddings demonstrated the best average F1 score." }, { "code": null, "e": 6039, "s": 5351, "text": "To enrich selected word embeddings with the emotional polarity of the words, we consider performing distant pre-training phrase by a fine-tuning of the embeddings on the automatically labelled distant dataset. The importance of using pre-training was demonstrated in (Deriu et al., 2017). We use the distant dataset to train the simple LSTM network to classify angry, sad, and happy tweets. The embeddings layer was frozen for the first training epoch in order to avoid significant changes in the embeddings weights, and then it was unfrozen for the next 5 epochs. After the training stage, the fine-tuned embeddings was saved for the further training phases and made publicly available." }, { "code": null, "e": 7109, "s": 6039, "text": "A recurrent neural network (RNN) is a family of artificial neural networks which is specialized in the processing of sequential data. In contrast with traditional neural networks, RRNs are designed to deal with sequential data by sharing their internal weights processing the sequence. For this purpose, the computation graph of RRNs includes cycles, representing the influence of the previous information on the present one. As an extension of RNNs, Long Short-Term Memory networks (LSTMs) have been introduced in 1997 (Hochreiter and Schmidhuber, 1997). In LSTMs recurrent cells are connected in a particular way to avoid vanishing and exploding gradient issues. Traditional LSTMs only preserves information from the past since they process the sequence only in one direction. Bidirectional LSTMs combine output from two hidden LSTM layers moving in opposite directions, where one moves forward through time, and another moves backward through time, thereby enabling to capture information from both past and future states simultaneously (Schuster and Paliwal, 1997)." }, { "code": null, "e": 8401, "s": 7109, "text": "A high-level overview of our approach is provided in Figure 1. The proposed architecture of the neural network consists of the embedding unit and two bidirectional LSTM units (dim = 64). The former LSTM unit is intended to analyze the utterance of the first user (i.e. the first turn and the third turn of the conversation), and the latter is intended to analyze the utterance of the second user (i.e. the second turn). These two units learn not only semantic and sentiment feature representation, but also how to capture user-specific conversation features, which allows classifying emotions more accurately. At the first step, each user utterance is fed into a corresponding bidirectional LSTM unit using pre-trained word embeddings. Next, these three feature maps are concatenated in a flatten feature vector and then passed to a fully connected hidden layer (dim = 30), which analyzes interactions between obtained vectors. Finally, these features proceed through the output layer with the softmax activation function to predict a final class label. To reduce overfitting, regularization layers with Gaussian noise were added after the embedding layer, dropout layers (Srivastava et al., 2014) were added at each LSTM unit (p = 0.2) and before the hidden fully connected layer (p = 0.1)." }, { "code": null, "e": 8693, "s": 8401, "text": "In the process of searching for optimal architecture, we experimented not only with the number of cells in layers, activation functions and regularization parameters but also with the architecture of the neural network. The detailed info about this phrase can be found in the original paper." }, { "code": null, "e": 9099, "s": 8693, "text": "The model described in the previous section demonstrated the best scores on the dev dataset, so it was used in the final evaluation stage of the competition. On the final test dataset, it achieved 72.59% micro-average F1 score for emotional classes, while the maximum score among all participants was 79.59%. However, this is well above the official baseline released by task organizers, which was 58,68%." }, { "code": null, "e": 9173, "s": 9099, "text": "The source code of the model and word-embeddings are available at GitHub." }, { "code": null, "e": 9184, "s": 9173, "text": "github.com" }, { "code": null, "e": 9356, "s": 9184, "text": "The full version of the article and the task description paper can be found at ACL Anthology.The training dataset is located at the official competition group at LinkedIn." }, { "code": null, "e": 9366, "s": 9356, "text": "Citation:" } ]
How to Compare Product Sales By Month in SQL? - GeeksforGeeks
16 Nov, 2021 A monthly sales report represents the state of sales activities in a company per month. It helps the sales team to move in the right direction. Whether you are a sales leader or manager, metrics are immensely important for your company’s success. If your data is stored in a database, you can calculate the monthly sales report using SQL. In this article, we are going to see how we can calculate monthly sales in SQL. 1. GROUP BY Clause 2. Aggregate Functions Let’s first create our demo database. Step 1: Creating the database Create a new database named Product_details and then use that. Query: CREATE DATABASE Product_details; USE Product_details; Output: Step 2: Defining the table Create a table named Products and add these two columns Order_date and Sales. Query: CREATE Table Products ( Order_date date, Sales int); Output: Step 3: Insert rows into the table and Insert these rows in the table. Query: INSERT INTO Products(Order_date,Sales) VALUES('2021-01-01',20),('2021-03-02',32),('2021-02-03',45), ('2021-01-04',31),('2021-03-05',33),('2021-01-06',19), ('2021-04-07',21),('2021-03-08',10),('2021-02-09',40), ('2021-03-10',20),('2021-03-11',26),('2021-04-12',22), ('2021-04-13',10),('2021-01-14',28),('2021-03-15',15), ('2021-01-16',12),('2021-04-17',10),('2021-02-18',18), ('2021-04-19',14),('2021-01-20',16),('2021-02-21',12), ('2021-03-22',51),('2021-02-23',13),('2021-03-24',15), ('2021-02-25',30),('2021-03-26',14),('2021-04-27',16), ('2021-02-28',15),('2021-01-29',20),('2021-01-30',18); Output: Step 4: Viewing Inserted data Query: SELECT * FROM Products; Output: Step 5: Now, let’s make our query to compare the product sales by month. SQL Server provides MONTH and YEAR functions that allow us to find out the month and year respectively, from the given date. We will use these two functions, the GROUP BY function and SUM function to calculate the total sales. Query: SELECT YEAR(Order_date) AS Year, MONTH(Order_date) AS Month,SUM(Sales) AS Total_Sales FROM Products GROUP BY YEAR(Order_date), MONTH(Order_date) ; Here, we are simply grouping up the months and years using the GROUP BY clause and then getting the total sales using the SUM aggregate function. Output: In the above query, we have used the SUM function to calculate the total sales every month. You can also find out the total count of sales every month. For that, replace the SUM function with the COUNT function. Query: SELECT YEAR(Order_date) AS Year,MONTH(Order_date) AS Month,COUNT(Sales) AS Count_Of_Sales FROM Products GROUP BY YEAR(Order_date),MONTH(Order_date); Output: Query: SELECT YEAR(Order_date) AS Year, DATENAME(MONTH, Order_date) AS Month, COUNT(Sales) AS Count_Of_Sales FROM Products GROUP BY YEAR(Order_date), DATENAME(MONTH, Order_date); Output: The DATENAME() function returns a specific part of the date. Here, we used it to return the MONTH part of the Order_date string. We can show this data in decreasing order using the ORDER BY clause. Query: SELECT YEAR(Order_date) AS Year, DATENAME(MONTH, Order_date) AS Month, COUNT(Sales) AS Count_Of_Sales FROM Products GROUP BY YEAR(Order_date), DATENAME(MONTH, Order_date) ORDER BY Count_Of_Sales DESC; Output: From this data report, we can easily tell that the count of sales was the highest in March. Now, you may want to calculate the monthly sales for different years. For that, you don’t have to change anything at all, the query will remain exactly the same. You can also do some experiments by using the WHERE clause to filter out some data or the other aggregate functions. Picked SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL - SELECT from Multiple Tables with MS SQL Server SQL Query to Delete Duplicate Rows
[ { "code": null, "e": 24292, "s": 24264, "text": "\n16 Nov, 2021" }, { "code": null, "e": 24711, "s": 24292, "text": "A monthly sales report represents the state of sales activities in a company per month. It helps the sales team to move in the right direction. Whether you are a sales leader or manager, metrics are immensely important for your company’s success. If your data is stored in a database, you can calculate the monthly sales report using SQL. In this article, we are going to see how we can calculate monthly sales in SQL." }, { "code": null, "e": 24731, "s": 24711, "text": " 1. GROUP BY Clause" }, { "code": null, "e": 24755, "s": 24731, "text": " 2. Aggregate Functions" }, { "code": null, "e": 24793, "s": 24755, "text": "Let’s first create our demo database." }, { "code": null, "e": 24823, "s": 24793, "text": "Step 1: Creating the database" }, { "code": null, "e": 24886, "s": 24823, "text": "Create a new database named Product_details and then use that." }, { "code": null, "e": 24893, "s": 24886, "text": "Query:" }, { "code": null, "e": 24947, "s": 24893, "text": "CREATE DATABASE Product_details; USE Product_details;" }, { "code": null, "e": 24955, "s": 24947, "text": "Output:" }, { "code": null, "e": 24982, "s": 24955, "text": "Step 2: Defining the table" }, { "code": null, "e": 25061, "s": 24982, "text": "Create a table named Products and add these two columns Order_date and Sales. " }, { "code": null, "e": 25068, "s": 25061, "text": "Query:" }, { "code": null, "e": 25122, "s": 25068, "text": "CREATE Table Products ( Order_date date, Sales int); " }, { "code": null, "e": 25130, "s": 25122, "text": "Output:" }, { "code": null, "e": 25201, "s": 25130, "text": "Step 3: Insert rows into the table and Insert these rows in the table." }, { "code": null, "e": 25208, "s": 25201, "text": "Query:" }, { "code": null, "e": 25820, "s": 25208, "text": "INSERT INTO Products(Order_date,Sales) \nVALUES('2021-01-01',20),('2021-03-02',32),('2021-02-03',45), \n('2021-01-04',31),('2021-03-05',33),('2021-01-06',19),\n('2021-04-07',21),('2021-03-08',10),('2021-02-09',40), \n('2021-03-10',20),('2021-03-11',26),('2021-04-12',22), \n('2021-04-13',10),('2021-01-14',28),('2021-03-15',15), \n('2021-01-16',12),('2021-04-17',10),('2021-02-18',18), \n('2021-04-19',14),('2021-01-20',16),('2021-02-21',12),\n('2021-03-22',51),('2021-02-23',13),('2021-03-24',15),\n('2021-02-25',30),('2021-03-26',14),('2021-04-27',16), \n('2021-02-28',15),('2021-01-29',20),('2021-01-30',18); " }, { "code": null, "e": 25828, "s": 25820, "text": "Output:" }, { "code": null, "e": 25858, "s": 25828, "text": "Step 4: Viewing Inserted data" }, { "code": null, "e": 25865, "s": 25858, "text": "Query:" }, { "code": null, "e": 25890, "s": 25865, "text": "SELECT * FROM Products; " }, { "code": null, "e": 25898, "s": 25890, "text": "Output:" }, { "code": null, "e": 25971, "s": 25898, "text": "Step 5: Now, let’s make our query to compare the product sales by month." }, { "code": null, "e": 26198, "s": 25971, "text": "SQL Server provides MONTH and YEAR functions that allow us to find out the month and year respectively, from the given date. We will use these two functions, the GROUP BY function and SUM function to calculate the total sales." }, { "code": null, "e": 26205, "s": 26198, "text": "Query:" }, { "code": null, "e": 26358, "s": 26205, "text": "SELECT YEAR(Order_date) AS Year, \nMONTH(Order_date) AS Month,SUM(Sales) \nAS Total_Sales FROM Products \nGROUP BY YEAR(Order_date), MONTH(Order_date) ; " }, { "code": null, "e": 26506, "s": 26358, "text": "Here, we are simply grouping up the months and years using the GROUP BY clause and then getting the total sales using the SUM aggregate function. " }, { "code": null, "e": 26514, "s": 26506, "text": "Output:" }, { "code": null, "e": 26726, "s": 26514, "text": "In the above query, we have used the SUM function to calculate the total sales every month. You can also find out the total count of sales every month. For that, replace the SUM function with the COUNT function." }, { "code": null, "e": 26733, "s": 26726, "text": "Query:" }, { "code": null, "e": 26889, "s": 26733, "text": "SELECT YEAR(Order_date) AS Year,MONTH(Order_date) \nAS Month,COUNT(Sales) AS Count_Of_Sales \nFROM Products GROUP BY YEAR(Order_date),MONTH(Order_date); " }, { "code": null, "e": 26897, "s": 26889, "text": "Output:" }, { "code": null, "e": 26904, "s": 26897, "text": "Query:" }, { "code": null, "e": 27081, "s": 26904, "text": "SELECT YEAR(Order_date) AS Year, DATENAME(MONTH, Order_date) \n AS Month, COUNT(Sales) AS Count_Of_Sales FROM Products \n GROUP BY YEAR(Order_date), DATENAME(MONTH, Order_date); " }, { "code": null, "e": 27089, "s": 27081, "text": "Output:" }, { "code": null, "e": 27218, "s": 27089, "text": "The DATENAME() function returns a specific part of the date. Here, we used it to return the MONTH part of the Order_date string." }, { "code": null, "e": 27287, "s": 27218, "text": "We can show this data in decreasing order using the ORDER BY clause." }, { "code": null, "e": 27294, "s": 27287, "text": "Query:" }, { "code": null, "e": 27498, "s": 27294, "text": "SELECT YEAR(Order_date) AS Year, DATENAME(MONTH, Order_date) \nAS Month, COUNT(Sales) AS Count_Of_Sales FROM Products GROUP\nBY YEAR(Order_date), DATENAME(MONTH, Order_date) ORDER \nBY Count_Of_Sales DESC; " }, { "code": null, "e": 27506, "s": 27498, "text": "Output:" }, { "code": null, "e": 27599, "s": 27506, "text": "From this data report, we can easily tell that the count of sales was the highest in March. " }, { "code": null, "e": 27878, "s": 27599, "text": "Now, you may want to calculate the monthly sales for different years. For that, you don’t have to change anything at all, the query will remain exactly the same. You can also do some experiments by using the WHERE clause to filter out some data or the other aggregate functions." }, { "code": null, "e": 27885, "s": 27878, "text": "Picked" }, { "code": null, "e": 27896, "s": 27885, "text": "SQL-Server" }, { "code": null, "e": 27900, "s": 27896, "text": "SQL" }, { "code": null, "e": 27904, "s": 27900, "text": "SQL" }, { "code": null, "e": 28002, "s": 27904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28068, "s": 28002, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28100, "s": 28068, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28178, "s": 28100, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28195, "s": 28178, "text": "SQL using Python" }, { "code": null, "e": 28210, "s": 28195, "text": "SQL | Subquery" }, { "code": null, "e": 28246, "s": 28210, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28312, "s": 28246, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 28374, "s": 28312, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 28427, "s": 28374, "text": "SQL - SELECT from Multiple Tables with MS SQL Server" } ]
Python - Sum negative and positive values using GroupBy in Pandas
Let us see how to find the sum of negative and positive values. At first, create a dataframe with positive and negative values − dataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]}) Next, use groupby to group on the basis of Place column − groupRes = dataFrame.groupby(dataFrame['Place']) Use lambda function to return the positive and negative values. We have also added the positive and negative values individually − # lambda function def plus(val): return val[val > 0].sum() def minus(val): return val[val < 0].sum() Following is the complete code − import pandas as pd # create a DataFrame with temperature in celsius dataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]}) print(dataFrame) # using groupby to group on the basis of place groupRes = dataFrame.groupby(dataFrame['Place']) # lambda function def plus(val): return val[val > 0].sum() def minus(val): return val[val < 0].sum() print(groupRes['Temperature'].agg([('negTemp', minus), ('posTemp', plus)])) This will produce the following code − Place Temperature 0 Chicago -2 1 Denver 30 2 Atlanta -5 3 Chicago 10 4 Dallas 30 5 Denver -5 6 Dallas 20 7 Atlanta -10 negTemp posTemp Place Atlanta -15 0 Chicago -2 10 Dallas 0 50 Denver -5 30
[ { "code": null, "e": 1191, "s": 1062, "text": "Let us see how to find the sum of negative and positive values. At first, create a dataframe with positive and negative values −" }, { "code": null, "e": 1362, "s": 1191, "text": "dataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]})" }, { "code": null, "e": 1420, "s": 1362, "text": "Next, use groupby to group on the basis of Place column −" }, { "code": null, "e": 1469, "s": 1420, "text": "groupRes = dataFrame.groupby(dataFrame['Place'])" }, { "code": null, "e": 1600, "s": 1469, "text": "Use lambda function to return the positive and negative values. We have also added the positive and negative values individually −" }, { "code": null, "e": 1707, "s": 1600, "text": "# lambda function\ndef plus(val):\n return val[val > 0].sum()\ndef minus(val):\n return val[val < 0].sum()" }, { "code": null, "e": 1740, "s": 1707, "text": "Following is the complete code −" }, { "code": null, "e": 2280, "s": 1740, "text": "import pandas as pd\n\n# create a DataFrame with temperature in celsius\ndataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]})\nprint(dataFrame)\n\n# using groupby to group on the basis of place\ngroupRes = dataFrame.groupby(dataFrame['Place'])\n\n# lambda function\ndef plus(val):\n return val[val > 0].sum()\ndef minus(val):\n return val[val < 0].sum()\n\nprint(groupRes['Temperature'].agg([('negTemp', minus), ('posTemp', plus)]))" }, { "code": null, "e": 2319, "s": 2280, "text": "This will produce the following code −" }, { "code": null, "e": 2722, "s": 2319, "text": " Place Temperature\n0 Chicago -2\n1 Denver 30\n2 Atlanta -5\n3 Chicago 10\n4 Dallas 30\n5 Denver -5\n6 Dallas 20\n7 Atlanta -10\n negTemp posTemp\nPlace\nAtlanta -15 0\nChicago -2 10\nDallas 0 50\nDenver -5 30" } ]
Python | sympy.sin() method - GeeksforGeeks
19 Jul, 2019 In simpy, sin() method is sine function. Using the sin(x) method in simpy module, we can compute the sine of x. Syntax : sympy.sin(x) Return : Returns the sine of x Code #1:Below is the example using sin() method to find sine function. # importing sympy libraryfrom sympy import * # calling sin() method on expressiongeek1 = sin(-1)geek2 = sin(pi / 3) print(geek1)print(geek2) Output: -sin(1) sqrt(3)/2 Code #2: # importing sympy libraryfrom sympy import * # calling sin() method on expressiongeek = sin(2 + 5j)print(geek) Output: 67.4789152384559 - 30.8794313435882*I SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24358, "s": 24330, "text": "\n19 Jul, 2019" }, { "code": null, "e": 24470, "s": 24358, "text": "In simpy, sin() method is sine function. Using the sin(x) method in simpy module, we can compute the sine of x." }, { "code": null, "e": 24524, "s": 24470, "text": "Syntax : sympy.sin(x)\nReturn : Returns the sine of x " }, { "code": null, "e": 24595, "s": 24524, "text": "Code #1:Below is the example using sin() method to find sine function." }, { "code": "# importing sympy libraryfrom sympy import * # calling sin() method on expressiongeek1 = sin(-1)geek2 = sin(pi / 3) print(geek1)print(geek2)", "e": 24738, "s": 24595, "text": null }, { "code": null, "e": 24746, "s": 24738, "text": "Output:" }, { "code": null, "e": 24765, "s": 24746, "text": "-sin(1)\nsqrt(3)/2\n" }, { "code": null, "e": 24775, "s": 24765, "text": " Code #2:" }, { "code": "# importing sympy libraryfrom sympy import * # calling sin() method on expressiongeek = sin(2 + 5j)print(geek)", "e": 24889, "s": 24775, "text": null }, { "code": null, "e": 24897, "s": 24889, "text": "Output:" }, { "code": null, "e": 24936, "s": 24897, "text": "67.4789152384559 - 30.8794313435882*I\n" }, { "code": null, "e": 24942, "s": 24936, "text": "SymPy" }, { "code": null, "e": 24949, "s": 24942, "text": "Python" }, { "code": null, "e": 25047, "s": 24949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25065, "s": 25047, "text": "Python Dictionary" }, { "code": null, "e": 25100, "s": 25065, "text": "Read a file line by line in Python" }, { "code": null, "e": 25122, "s": 25100, "text": "Enumerate() in Python" }, { "code": null, "e": 25154, "s": 25122, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25184, "s": 25154, "text": "Iterate over a list in Python" }, { "code": null, "e": 25226, "s": 25184, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25252, "s": 25226, "text": "Python String | replace()" }, { "code": null, "e": 25289, "s": 25252, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25332, "s": 25289, "text": "Python program to convert a list to string" } ]
Date and Time - EOMONTH Function
The EOMONTH function returns the serial number for the last day of the month that is the indicated number of months before or after start_date. EOMONTH (start_date, months) A date that represents the starting date. Dates should be entered by using the DATE function, or as results of other formulas or functions. Problems can occur if dates are entered as text. The number of months before or after start_date. A positive value for months yields a future date. A negative value yields a past date. Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900 Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900 If months is not an integer, it is truncated. If months is not an integer, it is truncated. The result will normally be expressed as a number that can be formatted to represent a Date with Format Cells. The result will normally be expressed as a number that can be formatted to represent a Date with Format Cells. If start_date is not a valid date, EOMONTH returns the #NUM! error value. If start_date is not a valid date, EOMONTH returns the #NUM! error value. If start_date plus months yields an invalid date, EOMONTH returns the #NUM! error value. If start_date plus months yields an invalid date, EOMONTH returns the #NUM! error value. If any of the supplied arguments are non-numeric values, EOMONTH returns the #VALUE! error value. If any of the supplied arguments are non-numeric values, EOMONTH returns the #VALUE! error value. Excel 2007, Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 1998, "s": 1854, "text": "The EOMONTH function returns the serial number for the last day of the month that is the indicated number of months before or after start_date." }, { "code": null, "e": 2028, "s": 1998, "text": "EOMONTH (start_date, months)\n" }, { "code": null, "e": 2070, "s": 2028, "text": "A date that represents the starting date." }, { "code": null, "e": 2168, "s": 2070, "text": "Dates should be entered by using the DATE function, or as results of other formulas or functions." }, { "code": null, "e": 2217, "s": 2168, "text": "Problems can occur if dates are entered as text." }, { "code": null, "e": 2266, "s": 2217, "text": "The number of months before or after start_date." }, { "code": null, "e": 2316, "s": 2266, "text": "A positive value for months yields a future date." }, { "code": null, "e": 2353, "s": 2316, "text": "A negative value yields a past date." }, { "code": null, "e": 2587, "s": 2353, "text": "Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900" }, { "code": null, "e": 2821, "s": 2587, "text": "Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900" }, { "code": null, "e": 2867, "s": 2821, "text": "If months is not an integer, it is truncated." }, { "code": null, "e": 2913, "s": 2867, "text": "If months is not an integer, it is truncated." }, { "code": null, "e": 3024, "s": 2913, "text": "The result will normally be expressed as a number that can be formatted to represent a Date with Format Cells." }, { "code": null, "e": 3135, "s": 3024, "text": "The result will normally be expressed as a number that can be formatted to represent a Date with Format Cells." }, { "code": null, "e": 3209, "s": 3135, "text": "If start_date is not a valid date, EOMONTH returns the #NUM! error value." }, { "code": null, "e": 3283, "s": 3209, "text": "If start_date is not a valid date, EOMONTH returns the #NUM! error value." }, { "code": null, "e": 3372, "s": 3283, "text": "If start_date plus months yields an invalid date, EOMONTH returns the #NUM! error value." }, { "code": null, "e": 3461, "s": 3372, "text": "If start_date plus months yields an invalid date, EOMONTH returns the #NUM! error value." }, { "code": null, "e": 3559, "s": 3461, "text": "If any of the supplied arguments are non-numeric values, EOMONTH returns the #VALUE! error value." }, { "code": null, "e": 3657, "s": 3559, "text": "If any of the supplied arguments are non-numeric values, EOMONTH returns the #VALUE! error value." }, { "code": null, "e": 3704, "s": 3657, "text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 3740, "s": 3704, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 3754, "s": 3740, "text": " Arun Motoori" }, { "code": null, "e": 3789, "s": 3754, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3804, "s": 3789, "text": " Pavan Lalwani" }, { "code": null, "e": 3840, "s": 3804, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3849, "s": 3840, "text": " Inf Sid" }, { "code": null, "e": 3885, "s": 3849, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3900, "s": 3885, "text": " Yoda Learning" }, { "code": null, "e": 3935, "s": 3900, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3950, "s": 3935, "text": " William Fiset" }, { "code": null, "e": 3985, "s": 3950, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3999, "s": 3985, "text": " Sasha Miller" }, { "code": null, "e": 4006, "s": 3999, "text": " Print" }, { "code": null, "e": 4017, "s": 4006, "text": " Add Notes" } ]
Priority queue of pairs in C++ (Ordered by first)
Priority queue is an abstract data type for storing a collection of prioritized elements that supports insertion and deletion of an element based upon their priorities, that is, the element with first priority can be removed at any time. The priority queue doesn’t stores elements in linear fashion with respect to their locations like in Stacks, Queues, List, etc. The priority queue ADT(abstract data type) stores elements based upon their priorities. Priority Queue supports the following functions − Size() − it is used to calculate the size of the priority queue as it returns the number of elements in it. Empty() − it return true if the Priority Queue is empty and false otherwise Insert(element) − used to insert the new element into a Priority Queue Min() − it returns the element with the smallest associated key value and display error message if Priority Queue is empty. removeMin() − it removes the element referenced by the min() function. The task is to implement the concept of priority queue of pairs in C++ ordered by the first. We can solve the problem in a similar fashion of heaps, have two ways to solve the problem Max priority or Max heap Min priority or Min heap Heap is a tree structure in which the nodes are arranged in a specific order. There are two types of heaps Min heap and Max heap. In Min heap the root node or the parent node is smaller than its child node, whereas in Max heap the root node or the parent node is larger than its child node. Input: priorityq.push(make_pair(18, 200)) Input: priorityq.push(make_pair(18, 200)) priorityq.push(make_pair(29, 100)) priorityq.push(make_pair(11, 400)) Output: 29 100 Input: priorityq.push(make_pair(10, 200)) priorityq.push(make_pair(20, 100)) priorityq.push(make_pair(19, 400)) Output: 20 100 Through Max priority (Max heap) Start Step 1-> In main function() Define priority_queue<pair<int, int> > priorityq Call priorityq.push(make_pair(18, 200)) Call priorityq.push(make_pair(29, 100)) Call priorityq.push(make_pair(11, 400)) Set pair<int, int> top = priorityq.top() Print top.first and top.second Stop Live Demo #include <bits/stdc++.h> using namespace std; // main program int main() { priority_queue<pair<int, int> > priorityq; priorityq.push(make_pair(18, 200)); priorityq.push(make_pair(29, 100)); priorityq.push(make_pair(11, 400)); pair<int, int> top = priorityq.top(); cout << top.first << " " << top.second; return 0; } 29 100 Start Step 1-> In main function() Define priority_queue<pair<int, int> > priorityq Call pq.push(make_pair(10, 200)) Call pq.push(make_pair(20, 100)) Call pq.push(make_pair(15, 400)) Set pair<int, int> top = pq.top() Print top.first and top.second Stop Live Demo #include <bits/stdc++.h> using namespace std; typedef pair<int, int> pi; // main program int main() { priority_queue<pi, vector<pi>, greater<pi> > pq; pq.push(make_pair(10, 200)); pq.push(make_pair(20, 100)); pq.push(make_pair(15, 400)); pair<int, int> top = pq.top(); cout << top.first << " " << top.second; return 0; } 10 200
[ { "code": null, "e": 1516, "s": 1062, "text": "Priority queue is an abstract data type for storing a collection of prioritized elements that supports insertion and deletion of an element based upon their priorities, that is, the element with first priority can be removed at any time. The priority queue doesn’t stores elements in linear fashion with respect to their locations like in Stacks, Queues, List, etc. The priority queue ADT(abstract data type) stores elements based upon their priorities." }, { "code": null, "e": 1566, "s": 1516, "text": "Priority Queue supports the following functions −" }, { "code": null, "e": 1674, "s": 1566, "text": "Size() − it is used to calculate the size of the priority queue as it returns the number of elements in it." }, { "code": null, "e": 1750, "s": 1674, "text": "Empty() − it return true if the Priority Queue is empty and false otherwise" }, { "code": null, "e": 1821, "s": 1750, "text": "Insert(element) − used to insert the new element into a Priority Queue" }, { "code": null, "e": 1945, "s": 1821, "text": "Min() − it returns the element with the smallest associated key value and display error message if Priority Queue is empty." }, { "code": null, "e": 2016, "s": 1945, "text": "removeMin() − it removes the element referenced by the min() function." }, { "code": null, "e": 2109, "s": 2016, "text": "The task is to implement the concept of priority queue of pairs in C++ ordered by the first." }, { "code": null, "e": 2200, "s": 2109, "text": "We can solve the problem in a similar fashion of heaps, have two ways to solve the problem" }, { "code": null, "e": 2225, "s": 2200, "text": "Max priority or Max heap" }, { "code": null, "e": 2250, "s": 2225, "text": "Min priority or Min heap" }, { "code": null, "e": 2541, "s": 2250, "text": "Heap is a tree structure in which the nodes are arranged in a specific order. There are two types of heaps Min heap and Max heap. In Min heap the root node or the parent node is smaller than its child node, whereas in Max heap the root node or the parent node is larger than its child node." }, { "code": null, "e": 2870, "s": 2541, "text": "Input: priorityq.push(make_pair(18, 200))\nInput: priorityq.push(make_pair(18, 200))\npriorityq.push(make_pair(29, 100))\npriorityq.push(make_pair(11, 400))\nOutput: 29 100\n\nInput: priorityq.push(make_pair(10, 200))\npriorityq.push(make_pair(20, 100))\npriorityq.push(make_pair(19, 400))\nOutput: 20 100\nThrough Max priority (Max heap)" }, { "code": null, "e": 3168, "s": 2870, "text": "Start\nStep 1-> In main function()\n Define priority_queue<pair<int, int> > priorityq\n Call priorityq.push(make_pair(18, 200))\n Call priorityq.push(make_pair(29, 100))\n Call priorityq.push(make_pair(11, 400))\n Set pair<int, int> top = priorityq.top()\n Print top.first and top.second\nStop" }, { "code": null, "e": 3179, "s": 3168, "text": " Live Demo" }, { "code": null, "e": 3516, "s": 3179, "text": "#include <bits/stdc++.h>\nusing namespace std;\n// main program\nint main() {\n priority_queue<pair<int, int> > priorityq;\n priorityq.push(make_pair(18, 200));\n priorityq.push(make_pair(29, 100));\n priorityq.push(make_pair(11, 400));\n pair<int, int> top = priorityq.top();\n cout << top.first << \" \" << top.second;\n return 0;\n}" }, { "code": null, "e": 3523, "s": 3516, "text": "29 100" }, { "code": null, "e": 3793, "s": 3523, "text": "Start\nStep 1-> In main function()\n Define priority_queue<pair<int, int> > priorityq\n Call pq.push(make_pair(10, 200))\n Call pq.push(make_pair(20, 100))\n Call pq.push(make_pair(15, 400))\n Set pair<int, int> top = pq.top()\n Print top.first and top.second\nStop" }, { "code": null, "e": 3804, "s": 3793, "text": " Live Demo" }, { "code": null, "e": 4146, "s": 3804, "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef pair<int, int> pi;\n// main program\nint main() {\n priority_queue<pi, vector<pi>, greater<pi> > pq;\n pq.push(make_pair(10, 200));\n pq.push(make_pair(20, 100));\n pq.push(make_pair(15, 400));\n pair<int, int> top = pq.top();\n cout << top.first << \" \" << top.second;\n return 0;\n}" }, { "code": null, "e": 4153, "s": 4146, "text": "10 200" } ]
A Quick Comparison of Causal-Inference Estimates | by Rumen Iliev | Towards Data Science
1. Introduction As an experimental behavioral scientist, I always thought that understanding the causal directionality of statistical relationships is at the heart of empirical science. I was trained in classical experimental design, where the researcher is assumed to have full control over the environment and whose main worry is how to position different experimental conditions in time or space (e.g. Latin Square Design). Once you leave the safety of the controlled lab experiments, however, inferring causality becomes a major problem which easily jeopardizes the internal validity of your conclusions. Luckily, in the last few decades, there has been tremendous progress in research on statistical causality, both in theory and methods, and now causal inference is becoming a rather common tool in the toolbox of a data scientist. To catch up with current methods I did a quick review and I was somewhat surprised by the plethora of ways for estimating causal effects. In this project I will list the most common methods I found in the literature, apply them to a simplified causal problem, and compare the observed estimates. This comparison is intended as a brief high-level overview and not as a tutorial on causal inferences. For a brief introduction on the topic I recommend Pearl et al. (2016), and for an in-depth coverage an interested reader can check Pearl (2009), Morgan and Winship (2015) or Prof. Jason Roy’s online class (Roy, 2020). 2. An Example Causal Model When using statistical methods to infer causality, typically we are interested in the magnitude of the effect of cause X on an outcome Y. When we are only observing those variables, or if there are challenges with the randomization (e.g. selection bias), we will typically need to account for a broader set of variables. In Figure 1 I present a causal graph for a hypothetical example. The example includes the three main types of additional variables which help us to get an unbiased estimate: backdoor, front door and instrument variables. Figure 1. A hypothetical graphical causal model of cause X influencing outcome Y in the presence of other variables. The causal effect of X on Y can be estimated if we measure any of these three sets: {X, Y, BD}, {X, Y, IV}, or {X, Y, FD} Suppose that X is a binary variable indicating the effect of exercising at least weekly (x = 1 if exercising; x = 0 otherwise) and Y is life expectancy measured on a continuous scale. The effect of X on Y is fully mediated by a variable FD (front door criterion), which in our example might be a body mass index. Further, both Y and X are influenced by variable BD (back door criterion), which in our case could be some set of genetic factors, which do not affect FD directly. Last, X is also influenced by IV (instrumental variables), which for our illustration could be proximity to a sport facility. We can instantiate this causal graph with the following model: IV = U BD = U X = { 0, if IV — BD + U <= 0 1, if IV — BD + U > 0} FD = X + U Y = 65 + FD + BD + U Model 1: Structural Causal Model instantiating the graphical model in Figure 1. The U components are normally distributed error terms (or inputs from exogenous variables) with mean 0 and SD = 2. For the purpose of the current simulation, I randomly generated 10,000 instances from Model 1 and in the next part, I will estimate the causal effect of X on Y using different statistical approaches. Here is the relevant code: generate_df <- function(n = 1000, path_weights) { #generate data frame from path_weights a <- path_weights sd_noise = 2 iv <- rnorm(n, sd = sd_noise) bd <- rnorm(n, sd = sd_noise) x <- rnorm(n) + a[1]*iv + a[2]*bd x <- ifelse(x<=median(x), 0, 1) lm(x~iv + bd) %>% summary fd <- (rnorm(n, sd = sd_noise) + a[3]*x ) lm(fd ~ x) %>% summary() y <- (65 + rnorm(n, sd = sd_noise) + a[4]*fd + a[5]*bd ) lm(y ~ fd + bd) %>% summary() id <- rnorm(n) df <- data.frame( id = id, x = x, y = y, iv = iv, fd = fd, bd = bd) return(df)}path_weights <- c(1,-1,1,1,1)df <- generate_df(n = 10000, path_weights) 3. Naive estimate (Observing X and Y) A naive estimate of the causal effect of X on Y could simply be obtained from the regression coefficient of X predicting Y. In this example, the causal effect is b_naive = -0.97, surprisingly suggesting that exercise shortens life expectancy by almost one year. naive_fit <- lm(y~x, data = df)summary(naive_fit) A naive estimate is useful when a researcher is convinced that there are no BD variables which need to be accounted for (e.g. when X is randomly assigned or as-if randomly assigned). With most observational studies and quasi-experimental designs, however, naive estimates are often not very useful. 4. Back-door variable adjustment (Observing X, Y and BD) If in addition to X and Y you can also measure BD, you can compute an unbiased estimate of the causal effect of X on Y, avoiding the problems that naive estimates have. Here BD is just a single variable, but it could be a set of variables which satisfy the back-door criteria. When reviewing the literature I found the following five methods to estimate causal effects while adjusting for backdoor variables: 4.1 Covariates One way to estimate the causal effect of X on Y is to run a regression model, predicting Y from X and including BD as a covariate. For most researchers who have training in linear regression but not in causal inferences, this is often the most intuitive approach. covariates_fit <- lm(y~x+bd, data = df)summary(covariates_fit) Applying this method to the data from our simulation we find that the causal effect of X on Y is b_covariates = 1.01. Based on this analysis, if you exercise you will live one year longer. Notice that this estimate is not only different than the naive estimate, the two estimates actually have opposite signs and lead to conflicting conclusions (check Simpson’s Paradox) 4.2 Direct Matching The covariates adjustment from above can also be accomplished by directly matching treatment and control participants on their BD scores. The main idea is that the matching procedure will remove the influence of BD on the causal estimate by only comparing control and treatment subjects who are already similar on their BD scores: greedymatch <- Matching::Match(Tr = df$x, M = 1, X = df[,”bd”])matched <- df[unlist(greedymatch[c(“index.treated”, “index.control”)]),]t.test(matched$y[matched$x == 1],matched$y[matched$x == 0], paired = TRUE) When using this method we get b_direct_match = 1.05, which is very close to what we observed when using the covariates method. 4.3 Propensity Score Matching If you have multiple BD variables you need to account for, it might be very challenging to find good matches (check the curse of dimensionality). Instead, you can use propensity score matching, where you first compute the probability for being in the treatment group (a.k.a propensity score, check this paper or this blog post), and then match participants based on those probabilities. ps_fit <- glm(x~bd, data = df, family = “binomial”)df$ps_score <- ps_fit$fitted.valueslogit <- stats::qlogis # rename the function for claritygreedymatch <- Match(Tr = df$x, M = 1, X = logit(df[,”ps_score”]), caliper = .2)matched <- df[unlist(greedymatch[c(“index.treated”, “index.control”)]),]t.test(matched$y[matched$x == 1],matched$y[matched$x == 0], paired = TRUE) The causal effect is estimated to be b_ps_match = 1.05 which is virtually the same as the previous adjusting methods. 4.4 Inverse Probability of Treatment Weighting You can also use weighted regression, where the weights are based on the probability of treatment. Control participants with high propensity scores and treatment participants with low propensity scores receive higher weights, adjusting for the treatment/control imbalance due to the BD variable(s). df$weight <- ifelse(df$x == 1, 1/df$ps_score, 1/(1-df$ps_score))iptw_fit <- lm(y ~ x, data = df, weights = weight)summary(iptw_fit) The estimate for the simulated data was b_iptw = 0.92, very close to the previous estimates. 4.5 Doubly-Robust Estimates This is a more advanced method which allows more room for misspecification of the model. To get an unbiased estimate of the causal effect it is enough to correctly specify either the propensity score model or the outcome regression model. dr_fit <- drgee::drgee(oformula=y~bd, eformula=x~bd, iaformula=~bd, olink=”identity”, elink=”identity”, estimation.method=”dr”, data=df)summary(dr_fit) The causal effect is b_doubly_robust = 1.01, again very similar to the previous other adjustment methods. 5. Instrumental variable (Observing X, Y and IV) What if you know that BD exists, but you cannot measure it? If you can measure variable IV instead, you still can estimate the causal effect of X on Y. This approach is known as the Instrumental Variable method, where the effect of the instrument IV on Y is mediated by X and can be used to estimate the effect of X on Y. A common method to run this analysis is called two-stage regression, where at the first stage we regress X on the instrument IV, and on the second stage, we regress the outcome Y on the residuals from the first stage. stage1_fit <- stats::lm(x~iv, data = df)df$stage1_predict <- predict(stage1_fit, type = “response”)stage2_fit <- stats::lm(y~stage1_predict, data = df)summary(stage2_fit) In our example, the instrumental variable method estimates the causal effect of X on Y to be b_iv = 0.96, very close to the BD adjustment methods. 6. Front-door adjustment (Observing X, Y and FD) Even if we can measure neither IV nor BD, it is still possible to compute an unbiased estimate of the causal effect of X on Y. The front-door adjustment allows us to achieve this by measuring the effect of X on FD and FD on Y. x_fd_fit <- lm(fd~x, data = df)fd_y_fit <- lm(y~fd + x, data = df) # here x is included to block back-door effectsx_fd_fit$coefficients[2]*fd_y_fit$coefficients[2] Using front-door adjustment we estimate the causal effect of X on Y to be b_fd = 1.03. 7. Cross-method agreement While I understand why some of the methods should return equivalent or very close estimates, I still find it both striking and somewhat perplexing that the causal effect of X and Y can be estimated in so many ways. To examine the agreement of the different methods I ran a series of simulations based on the causal graph from Figure 1. I used the same types of relations as the ones outlined in Model 1, but for each simulation, I randomly assigned a random regression coefficient, with absolute values ranging from 0.3 to 3. For reference, for the weaker relationship (coefficients set to 0.3) FD and BD together were explaining 8% of the variance in Y, and the stronger relationship (coefficients set to 3) they were explaining 68% of the variance (based on R2). Figure 2. Correlations between the causal effect estimates from the eight causal inference methods discussed here. I ran 2000 simulations, with 2000 rows each. For each simulation I computed eight different estimates of the causal effect of X on Y, using the methods listed above. Figure 2 depicts the agreement between the different methods. As can be seen in the figure, there is substantial agreement between the methods, with Pearson’s correlations well above 0.9. The naive estimate is also positively correlated with the other methods, yet it often underestimates or overestimates the true causal effect. 8. Caveats and further observations The goal of the current project was to provide a quick overarching example for the main methods for estimating causal effects and to demonstrate that those methods largely agree in their results. In its brevity, however, this example brushed over many important details, some of which I will need to mention explicitly: Here I treated causal effects as an unitary concept, yet there are different types of causal effects. Instrumental variables, for example, estimate Local Average Treatment Effect, while the other methods, as applied here, estimate (Marginal) Average Treatment Effect. Those two effects are not necessarily equal. While the causal graph in Figure 1 and the subsequent model are based on various theoretical principles and assumptions, I only provided external references and did not discuss them here. The different methods here largely agreed in their estimates, but this is partially due to the simple model I used to generate the data. For example, I did not include heterogeneous treatment effects, unbalanced groups or skewed distributions, all of which would have decreased the consensus across methods. Matching methods are sensitive to the particular algorithms used and to the strength of the relationship between X and BD. While experimenting with the magnitude of the causal relations, I noticed that weaker causal effects are associated with a substantial drop in agreement across methods. Instrumental variables estimates were particularly affected by the weak statistical relationships (check Bound, Jaeger, & Baker, 1995) 9. Conclusion I found catching up with the field of causal inferences to be both challenging and exciting. To a novice, the field can seem fragmented, inconsistent and often focused on abstract theories rather than on applications. Yet beyond these initial impressions, it was fascinating to discover that both theories and methods gradually converge and provide researchers with a plethora of creative tools to use in their search for causality. Putting the most common of these tools together helped me to see the convergence of theories and methods and I hope it might be of help to other fellow researchers and data scientists. References Austin, P. C. (2011). An introduction to propensity score methods for reducing the effects of confounding in observational studies. Multivariate behavioral research, 46(3), 399–424. Bellemare, M. F., & Bloem, J. R. (2019). The Paper of How: Estimating Treatment Effects Using the Front-Door Criterion. Bound, J., Jaeger, D. A., & Baker, R. M. (1995). Problems with instrumental variables estimation when the correlation between the instruments and the endogenous explanatory variable is weak. Journal of the American statistical association, 90(430), 443–450. Bound, J., Jaeger, D. A., & Baker, R. M. (1995). Problems with instrumental variables estimation when the correlation between the instruments and the endogenous explanatory variable is weak. Journal of the American statistical association, 90(430), 443–450. Morgan, S. L., & Winship, C. (2015). Counterfactuals and causal inference. Cambridge University Press. Pearl, J. (1993). Bayesian analysis in expert systems: comment: graphical models, causality and intervention. Statistical Science, 8(3), 266–269. Pearl, J. (2009). Causality. Cambridge university press. Pearl, J., Glymour, M., & Jewell, N. P. (2016). Causal inference in statistics: A primer. John Wiley & Sons. Roy, J. (retrieved 2020, April 23) A Crash Course in Causality: Inferring Causal Effects from Observational Data. coursera.org, url: https://www.coursera.org/learn/crash-course-in-causality
[ { "code": null, "e": 188, "s": 172, "text": "1. Introduction" }, { "code": null, "e": 1627, "s": 188, "text": "As an experimental behavioral scientist, I always thought that understanding the causal directionality of statistical relationships is at the heart of empirical science. I was trained in classical experimental design, where the researcher is assumed to have full control over the environment and whose main worry is how to position different experimental conditions in time or space (e.g. Latin Square Design). Once you leave the safety of the controlled lab experiments, however, inferring causality becomes a major problem which easily jeopardizes the internal validity of your conclusions. Luckily, in the last few decades, there has been tremendous progress in research on statistical causality, both in theory and methods, and now causal inference is becoming a rather common tool in the toolbox of a data scientist. To catch up with current methods I did a quick review and I was somewhat surprised by the plethora of ways for estimating causal effects. In this project I will list the most common methods I found in the literature, apply them to a simplified causal problem, and compare the observed estimates. This comparison is intended as a brief high-level overview and not as a tutorial on causal inferences. For a brief introduction on the topic I recommend Pearl et al. (2016), and for an in-depth coverage an interested reader can check Pearl (2009), Morgan and Winship (2015) or Prof. Jason Roy’s online class (Roy, 2020)." }, { "code": null, "e": 1654, "s": 1627, "text": "2. An Example Causal Model" }, { "code": null, "e": 2196, "s": 1654, "text": "When using statistical methods to infer causality, typically we are interested in the magnitude of the effect of cause X on an outcome Y. When we are only observing those variables, or if there are challenges with the randomization (e.g. selection bias), we will typically need to account for a broader set of variables. In Figure 1 I present a causal graph for a hypothetical example. The example includes the three main types of additional variables which help us to get an unbiased estimate: backdoor, front door and instrument variables." }, { "code": null, "e": 2435, "s": 2196, "text": "Figure 1. A hypothetical graphical causal model of cause X influencing outcome Y in the presence of other variables. The causal effect of X on Y can be estimated if we measure any of these three sets: {X, Y, BD}, {X, Y, IV}, or {X, Y, FD}" }, { "code": null, "e": 3038, "s": 2435, "text": "Suppose that X is a binary variable indicating the effect of exercising at least weekly (x = 1 if exercising; x = 0 otherwise) and Y is life expectancy measured on a continuous scale. The effect of X on Y is fully mediated by a variable FD (front door criterion), which in our example might be a body mass index. Further, both Y and X are influenced by variable BD (back door criterion), which in our case could be some set of genetic factors, which do not affect FD directly. Last, X is also influenced by IV (instrumental variables), which for our illustration could be proximity to a sport facility." }, { "code": null, "e": 3101, "s": 3038, "text": "We can instantiate this causal graph with the following model:" }, { "code": null, "e": 3108, "s": 3101, "text": "IV = U" }, { "code": null, "e": 3115, "s": 3108, "text": "BD = U" }, { "code": null, "e": 3144, "s": 3115, "text": "X = { 0, if IV — BD + U <= 0" }, { "code": null, "e": 3167, "s": 3144, "text": "1, if IV — BD + U > 0}" }, { "code": null, "e": 3178, "s": 3167, "text": "FD = X + U" }, { "code": null, "e": 3199, "s": 3178, "text": "Y = 65 + FD + BD + U" }, { "code": null, "e": 3394, "s": 3199, "text": "Model 1: Structural Causal Model instantiating the graphical model in Figure 1. The U components are normally distributed error terms (or inputs from exogenous variables) with mean 0 and SD = 2." }, { "code": null, "e": 3594, "s": 3394, "text": "For the purpose of the current simulation, I randomly generated 10,000 instances from Model 1 and in the next part, I will estimate the causal effect of X on Y using different statistical approaches." }, { "code": null, "e": 3621, "s": 3594, "text": "Here is the relevant code:" }, { "code": null, "e": 4216, "s": 3621, "text": "generate_df <- function(n = 1000, path_weights) { #generate data frame from path_weights a <- path_weights sd_noise = 2 iv <- rnorm(n, sd = sd_noise) bd <- rnorm(n, sd = sd_noise) x <- rnorm(n) + a[1]*iv + a[2]*bd x <- ifelse(x<=median(x), 0, 1) lm(x~iv + bd) %>% summary fd <- (rnorm(n, sd = sd_noise) + a[3]*x ) lm(fd ~ x) %>% summary() y <- (65 + rnorm(n, sd = sd_noise) + a[4]*fd + a[5]*bd ) lm(y ~ fd + bd) %>% summary() id <- rnorm(n) df <- data.frame( id = id, x = x, y = y, iv = iv, fd = fd, bd = bd) return(df)}path_weights <- c(1,-1,1,1,1)df <- generate_df(n = 10000, path_weights)" }, { "code": null, "e": 4254, "s": 4216, "text": "3. Naive estimate (Observing X and Y)" }, { "code": null, "e": 4516, "s": 4254, "text": "A naive estimate of the causal effect of X on Y could simply be obtained from the regression coefficient of X predicting Y. In this example, the causal effect is b_naive = -0.97, surprisingly suggesting that exercise shortens life expectancy by almost one year." }, { "code": null, "e": 4566, "s": 4516, "text": "naive_fit <- lm(y~x, data = df)summary(naive_fit)" }, { "code": null, "e": 4865, "s": 4566, "text": "A naive estimate is useful when a researcher is convinced that there are no BD variables which need to be accounted for (e.g. when X is randomly assigned or as-if randomly assigned). With most observational studies and quasi-experimental designs, however, naive estimates are often not very useful." }, { "code": null, "e": 4922, "s": 4865, "text": "4. Back-door variable adjustment (Observing X, Y and BD)" }, { "code": null, "e": 5331, "s": 4922, "text": "If in addition to X and Y you can also measure BD, you can compute an unbiased estimate of the causal effect of X on Y, avoiding the problems that naive estimates have. Here BD is just a single variable, but it could be a set of variables which satisfy the back-door criteria. When reviewing the literature I found the following five methods to estimate causal effects while adjusting for backdoor variables:" }, { "code": null, "e": 5346, "s": 5331, "text": "4.1 Covariates" }, { "code": null, "e": 5610, "s": 5346, "text": "One way to estimate the causal effect of X on Y is to run a regression model, predicting Y from X and including BD as a covariate. For most researchers who have training in linear regression but not in causal inferences, this is often the most intuitive approach." }, { "code": null, "e": 5673, "s": 5610, "text": "covariates_fit <- lm(y~x+bd, data = df)summary(covariates_fit)" }, { "code": null, "e": 6044, "s": 5673, "text": "Applying this method to the data from our simulation we find that the causal effect of X on Y is b_covariates = 1.01. Based on this analysis, if you exercise you will live one year longer. Notice that this estimate is not only different than the naive estimate, the two estimates actually have opposite signs and lead to conflicting conclusions (check Simpson’s Paradox)" }, { "code": null, "e": 6064, "s": 6044, "text": "4.2 Direct Matching" }, { "code": null, "e": 6395, "s": 6064, "text": "The covariates adjustment from above can also be accomplished by directly matching treatment and control participants on their BD scores. The main idea is that the matching procedure will remove the influence of BD on the causal estimate by only comparing control and treatment subjects who are already similar on their BD scores:" }, { "code": null, "e": 6605, "s": 6395, "text": "greedymatch <- Matching::Match(Tr = df$x, M = 1, X = df[,”bd”])matched <- df[unlist(greedymatch[c(“index.treated”, “index.control”)]),]t.test(matched$y[matched$x == 1],matched$y[matched$x == 0], paired = TRUE)" }, { "code": null, "e": 6732, "s": 6605, "text": "When using this method we get b_direct_match = 1.05, which is very close to what we observed when using the covariates method." }, { "code": null, "e": 6762, "s": 6732, "text": "4.3 Propensity Score Matching" }, { "code": null, "e": 7149, "s": 6762, "text": "If you have multiple BD variables you need to account for, it might be very challenging to find good matches (check the curse of dimensionality). Instead, you can use propensity score matching, where you first compute the probability for being in the treatment group (a.k.a propensity score, check this paper or this blog post), and then match participants based on those probabilities." }, { "code": null, "e": 7518, "s": 7149, "text": "ps_fit <- glm(x~bd, data = df, family = “binomial”)df$ps_score <- ps_fit$fitted.valueslogit <- stats::qlogis # rename the function for claritygreedymatch <- Match(Tr = df$x, M = 1, X = logit(df[,”ps_score”]), caliper = .2)matched <- df[unlist(greedymatch[c(“index.treated”, “index.control”)]),]t.test(matched$y[matched$x == 1],matched$y[matched$x == 0], paired = TRUE)" }, { "code": null, "e": 7636, "s": 7518, "text": "The causal effect is estimated to be b_ps_match = 1.05 which is virtually the same as the previous adjusting methods." }, { "code": null, "e": 7683, "s": 7636, "text": "4.4 Inverse Probability of Treatment Weighting" }, { "code": null, "e": 7982, "s": 7683, "text": "You can also use weighted regression, where the weights are based on the probability of treatment. Control participants with high propensity scores and treatment participants with low propensity scores receive higher weights, adjusting for the treatment/control imbalance due to the BD variable(s)." }, { "code": null, "e": 8114, "s": 7982, "text": "df$weight <- ifelse(df$x == 1, 1/df$ps_score, 1/(1-df$ps_score))iptw_fit <- lm(y ~ x, data = df, weights = weight)summary(iptw_fit)" }, { "code": null, "e": 8207, "s": 8114, "text": "The estimate for the simulated data was b_iptw = 0.92, very close to the previous estimates." }, { "code": null, "e": 8235, "s": 8207, "text": "4.5 Doubly-Robust Estimates" }, { "code": null, "e": 8474, "s": 8235, "text": "This is a more advanced method which allows more room for misspecification of the model. To get an unbiased estimate of the causal effect it is enough to correctly specify either the propensity score model or the outcome regression model." }, { "code": null, "e": 8626, "s": 8474, "text": "dr_fit <- drgee::drgee(oformula=y~bd, eformula=x~bd, iaformula=~bd, olink=”identity”, elink=”identity”, estimation.method=”dr”, data=df)summary(dr_fit)" }, { "code": null, "e": 8732, "s": 8626, "text": "The causal effect is b_doubly_robust = 1.01, again very similar to the previous other adjustment methods." }, { "code": null, "e": 8781, "s": 8732, "text": "5. Instrumental variable (Observing X, Y and IV)" }, { "code": null, "e": 9321, "s": 8781, "text": "What if you know that BD exists, but you cannot measure it? If you can measure variable IV instead, you still can estimate the causal effect of X on Y. This approach is known as the Instrumental Variable method, where the effect of the instrument IV on Y is mediated by X and can be used to estimate the effect of X on Y. A common method to run this analysis is called two-stage regression, where at the first stage we regress X on the instrument IV, and on the second stage, we regress the outcome Y on the residuals from the first stage." }, { "code": null, "e": 9492, "s": 9321, "text": "stage1_fit <- stats::lm(x~iv, data = df)df$stage1_predict <- predict(stage1_fit, type = “response”)stage2_fit <- stats::lm(y~stage1_predict, data = df)summary(stage2_fit)" }, { "code": null, "e": 9639, "s": 9492, "text": "In our example, the instrumental variable method estimates the causal effect of X on Y to be b_iv = 0.96, very close to the BD adjustment methods." }, { "code": null, "e": 9688, "s": 9639, "text": "6. Front-door adjustment (Observing X, Y and FD)" }, { "code": null, "e": 9915, "s": 9688, "text": "Even if we can measure neither IV nor BD, it is still possible to compute an unbiased estimate of the causal effect of X on Y. The front-door adjustment allows us to achieve this by measuring the effect of X on FD and FD on Y." }, { "code": null, "e": 10079, "s": 9915, "text": "x_fd_fit <- lm(fd~x, data = df)fd_y_fit <- lm(y~fd + x, data = df) # here x is included to block back-door effectsx_fd_fit$coefficients[2]*fd_y_fit$coefficients[2]" }, { "code": null, "e": 10166, "s": 10079, "text": "Using front-door adjustment we estimate the causal effect of X on Y to be b_fd = 1.03." }, { "code": null, "e": 10192, "s": 10166, "text": "7. Cross-method agreement" }, { "code": null, "e": 10957, "s": 10192, "text": "While I understand why some of the methods should return equivalent or very close estimates, I still find it both striking and somewhat perplexing that the causal effect of X and Y can be estimated in so many ways. To examine the agreement of the different methods I ran a series of simulations based on the causal graph from Figure 1. I used the same types of relations as the ones outlined in Model 1, but for each simulation, I randomly assigned a random regression coefficient, with absolute values ranging from 0.3 to 3. For reference, for the weaker relationship (coefficients set to 0.3) FD and BD together were explaining 8% of the variance in Y, and the stronger relationship (coefficients set to 3) they were explaining 68% of the variance (based on R2)." }, { "code": null, "e": 11072, "s": 10957, "text": "Figure 2. Correlations between the causal effect estimates from the eight causal inference methods discussed here." }, { "code": null, "e": 11568, "s": 11072, "text": "I ran 2000 simulations, with 2000 rows each. For each simulation I computed eight different estimates of the causal effect of X on Y, using the methods listed above. Figure 2 depicts the agreement between the different methods. As can be seen in the figure, there is substantial agreement between the methods, with Pearson’s correlations well above 0.9. The naive estimate is also positively correlated with the other methods, yet it often underestimates or overestimates the true causal effect." }, { "code": null, "e": 11604, "s": 11568, "text": "8. Caveats and further observations" }, { "code": null, "e": 11924, "s": 11604, "text": "The goal of the current project was to provide a quick overarching example for the main methods for estimating causal effects and to demonstrate that those methods largely agree in their results. In its brevity, however, this example brushed over many important details, some of which I will need to mention explicitly:" }, { "code": null, "e": 12237, "s": 11924, "text": "Here I treated causal effects as an unitary concept, yet there are different types of causal effects. Instrumental variables, for example, estimate Local Average Treatment Effect, while the other methods, as applied here, estimate (Marginal) Average Treatment Effect. Those two effects are not necessarily equal." }, { "code": null, "e": 12425, "s": 12237, "text": "While the causal graph in Figure 1 and the subsequent model are based on various theoretical principles and assumptions, I only provided external references and did not discuss them here." }, { "code": null, "e": 12733, "s": 12425, "text": "The different methods here largely agreed in their estimates, but this is partially due to the simple model I used to generate the data. For example, I did not include heterogeneous treatment effects, unbalanced groups or skewed distributions, all of which would have decreased the consensus across methods." }, { "code": null, "e": 12856, "s": 12733, "text": "Matching methods are sensitive to the particular algorithms used and to the strength of the relationship between X and BD." }, { "code": null, "e": 13160, "s": 12856, "text": "While experimenting with the magnitude of the causal relations, I noticed that weaker causal effects are associated with a substantial drop in agreement across methods. Instrumental variables estimates were particularly affected by the weak statistical relationships (check Bound, Jaeger, & Baker, 1995)" }, { "code": null, "e": 13174, "s": 13160, "text": "9. Conclusion" }, { "code": null, "e": 13792, "s": 13174, "text": "I found catching up with the field of causal inferences to be both challenging and exciting. To a novice, the field can seem fragmented, inconsistent and often focused on abstract theories rather than on applications. Yet beyond these initial impressions, it was fascinating to discover that both theories and methods gradually converge and provide researchers with a plethora of creative tools to use in their search for causality. Putting the most common of these tools together helped me to see the convergence of theories and methods and I hope it might be of help to other fellow researchers and data scientists." }, { "code": null, "e": 13803, "s": 13792, "text": "References" }, { "code": null, "e": 13985, "s": 13803, "text": "Austin, P. C. (2011). An introduction to propensity score methods for reducing the effects of confounding in observational studies. Multivariate behavioral research, 46(3), 399–424." }, { "code": null, "e": 14105, "s": 13985, "text": "Bellemare, M. F., & Bloem, J. R. (2019). The Paper of How: Estimating Treatment Effects Using the Front-Door Criterion." }, { "code": null, "e": 14363, "s": 14105, "text": "Bound, J., Jaeger, D. A., & Baker, R. M. (1995). Problems with instrumental variables estimation when the correlation between the instruments and the endogenous explanatory variable is weak. Journal of the American statistical association, 90(430), 443–450." }, { "code": null, "e": 14621, "s": 14363, "text": "Bound, J., Jaeger, D. A., & Baker, R. M. (1995). Problems with instrumental variables estimation when the correlation between the instruments and the endogenous explanatory variable is weak. Journal of the American statistical association, 90(430), 443–450." }, { "code": null, "e": 14724, "s": 14621, "text": "Morgan, S. L., & Winship, C. (2015). Counterfactuals and causal inference. Cambridge University Press." }, { "code": null, "e": 14870, "s": 14724, "text": "Pearl, J. (1993). Bayesian analysis in expert systems: comment: graphical models, causality and intervention. Statistical Science, 8(3), 266–269." }, { "code": null, "e": 14927, "s": 14870, "text": "Pearl, J. (2009). Causality. Cambridge university press." }, { "code": null, "e": 15036, "s": 14927, "text": "Pearl, J., Glymour, M., & Jewell, N. P. (2016). Causal inference in statistics: A primer. John Wiley & Sons." } ]
How to draw a polygon in HTML5 SVG?
SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG. To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. The points attribute is the x and y coordinates for each corner of the polygon. You can try to run the following code to learn how to draw a polygon in HTML5 SVG. <!DOCTYPE html> <html> <head> <style> #svgelem { position: relative; left: 10%; -webkit-transform: translateX(-20%); -ms-transform: translateX(-20%); transform: translateX(-20%); } </style> <title>HTML5 SVG Polygon</title> </head> <body> <h2>HTML5 SVG Polygon</h2> <svg id="svgelem" width="300" height="300" xmlns="http://www.w3.org/2000/svg"> <polygon points="100, 20 200,180 100,200" style="fill:green;" /> </svg> </body> </html>
[ { "code": null, "e": 1315, "s": 1062, "text": "SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG." }, { "code": null, "e": 1530, "s": 1315, "text": "To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. The points attribute is the x and y coordinates for each corner of the polygon." }, { "code": null, "e": 1613, "s": 1530, "text": "You can try to run the following code to learn how to draw a polygon in HTML5 SVG." }, { "code": null, "e": 2181, "s": 1613, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #svgelem {\n position: relative;\n left: 10%;\n -webkit-transform: translateX(-20%);\n -ms-transform: translateX(-20%);\n transform: translateX(-20%);\n }\n </style>\n <title>HTML5 SVG Polygon</title>\n </head>\n\n <body>\n <h2>HTML5 SVG Polygon</h2>\n <svg id=\"svgelem\" width=\"300\" height=\"300\" xmlns=\"http://www.w3.org/2000/svg\">\n <polygon points=\"100, 20 200,180 100,200\" style=\"fill:green;\" />\n </svg>\n </body>\n</html>" } ]
How to use inline CSS (Style Sheet) in HTML?
To add inline CSS in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with CSS properties such as font-family, font-style, text-decoration, direction, etc. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try the following code to use inline CSS in HTML. Here, we are adding font size to heading using inline CSS Live Demo <!DOCTYPE html> <html> <head> <title>HTML Inline CSS</title> </head> <body> <h1 style=”font-size: 20px;”> Tutorials </h1> <p>We have tutorials on Programming, CMS, Scripting Languages, etc.</p> </body> </html>
[ { "code": null, "e": 1284, "s": 1062, "text": "To add inline CSS in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with CSS properties such as font-family, font-style, text-decoration, direction, etc." }, { "code": null, "e": 1446, "s": 1284, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1562, "s": 1446, "text": "You can try the following code to use inline CSS in HTML. Here, we are adding font size to heading using inline CSS" }, { "code": null, "e": 1572, "s": 1562, "text": "Live Demo" }, { "code": null, "e": 1828, "s": 1572, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Inline CSS</title>\n </head>\n\n <body>\n <h1 style=”font-size: 20px;”>\n Tutorials\n </h1>\n <p>We have tutorials on Programming, CMS, Scripting Languages, etc.</p>\n </body>\n</html>" } ]
DSA using Java - Heap
Heap represents a special tree based data structure used to represent priority queue or for heap sort. We'll going to discuss binary heap tree specifically. Binary heap tree can be classified as a binary tree with two constraints − Completeness − Binary heap tree is a complete binary tree except the last level which may not have all elements but elements from left to right should be filled in. Completeness − Binary heap tree is a complete binary tree except the last level which may not have all elements but elements from left to right should be filled in. Heapness − All parent nodes should be greater or smaller to their children. If parent node is to be greater than its child then it is called Max heap otherwise it is called Min heap. Max heap is used for heap sort and Min heap is used for priority queue. We're considering Min Heap and will use array implementation for the same. Heapness − All parent nodes should be greater or smaller to their children. If parent node is to be greater than its child then it is called Max heap otherwise it is called Min heap. Max heap is used for heap sort and Min heap is used for priority queue. We're considering Min Heap and will use array implementation for the same. Following are basic primary operations of a Min heap which are following. Insert − insert an element in a heap. Insert − insert an element in a heap. Get Minimum − get minimum element from the heap. Get Minimum − get minimum element from the heap. Remove Minimum − remove the minimum element from the heap Remove Minimum − remove the minimum element from the heap Whenever an element is to be inserted. Insert element at the end of the array. Increase the size of heap by 1. Whenever an element is to be inserted. Insert element at the end of the array. Increase the size of heap by 1. Heap up the element while heap property is broken. Compare element with parent's value and swap them if required. public void insert(int value) { size++; intArray[size - 1] = value; heapUp(size - 1); } private void heapUp(int nodeIndex){ int parentIndex, tmp; if (nodeIndex != 0) { parentIndex = getParentIndex(nodeIndex); if (intArray[parentIndex] > intArray[nodeIndex]) { tmp = intArray[parentIndex]; intArray[parentIndex] = intArray[nodeIndex]; intArray[nodeIndex] = tmp; heapUp(parentIndex); } } } Get the first element of the array implementing the heap being root. public int getMinimum(){ return intArray[0]; } Whenever an element is to be removed. Get the last element of the array and reduce size of heap by 1. Whenever an element is to be removed. Get the last element of the array and reduce size of heap by 1. Heap down the element while heap property is broken. Compare element with children's value and swap them if required. public void removeMin() { intArray[0] = intArray[size - 1]; size--; if (size > 0) heapDown(0); } private void heapDown(int nodeIndex){ int leftChildIndex, rightChildIndex, minIndex, tmp; leftChildIndex = getLeftChildIndex(nodeIndex); rightChildIndex = getRightChildIndex(nodeIndex); if (rightChildIndex >= size) { if (leftChildIndex >= size) return; else minIndex = leftChildIndex; } else { if (intArray[leftChildIndex] <= intArray[rightChildIndex]) minIndex = leftChildIndex; else minIndex = rightChildIndex; } if (intArray[nodeIndex] > intArray[minIndex]) { tmp = intArray[minIndex]; intArray[minIndex] = intArray[nodeIndex]; intArray[nodeIndex] = tmp; heapDown(minIndex); } } Heap.java package com.tutorialspoint.datastructure; public class Heap { private int[] intArray; private int size; public Heap(int size){ intArray = new int[size]; } public boolean isEmpty(){ return size == 0; } public int getMinimum(){ return intArray[0]; } public int getLeftChildIndex(int nodeIndex){ return 2*nodeIndex +1; } public int getRightChildIndex(int nodeIndex){ return 2*nodeIndex +2; } public int getParentIndex(int nodeIndex){ return (nodeIndex -1)/2; } public boolean isFull(){ return size == intArray.length; } public void insert(int value) { size++; intArray[size - 1] = value; heapUp(size - 1); } public void removeMin() { intArray[0] = intArray[size - 1]; size--; if (size > 0) heapDown(0); } /** * Heap up the new element,until heap property is broken. * Steps: * 1. Compare node's value with parent's value. * 2. Swap them, If they are in wrong order. * */ private void heapUp(int nodeIndex){ int parentIndex, tmp; if (nodeIndex != 0) { parentIndex = getParentIndex(nodeIndex); if (intArray[parentIndex] > intArray[nodeIndex]) { tmp = intArray[parentIndex]; intArray[parentIndex] = intArray[nodeIndex]; intArray[nodeIndex] = tmp; heapUp(parentIndex); } } } /** * Heap down the root element being least in value,until heap property is broken. * Steps: * 1.If current node has no children, done. * 2.If current node has one children and heap property is broken, * 3.Swap the current node and child node and heap down. * 4.If current node has one children and heap property is broken, find smaller one * 5.Swap the current node and child node and heap down. * */ private void heapDown(int nodeIndex){ int leftChildIndex, rightChildIndex, minIndex, tmp; leftChildIndex = getLeftChildIndex(nodeIndex); rightChildIndex = getRightChildIndex(nodeIndex); if (rightChildIndex >= size) { if (leftChildIndex >= size) return; else minIndex = leftChildIndex; } else { if (intArray[leftChildIndex] <= intArray[rightChildIndex]) minIndex = leftChildIndex; else minIndex = rightChildIndex; } if (intArray[nodeIndex] > intArray[minIndex]) { tmp = intArray[minIndex]; intArray[minIndex] = intArray[nodeIndex]; intArray[nodeIndex] = tmp; heapDown(minIndex); } } } HeapDemo.java package com.tutorialspoint.datastructure; public class HeapDemo { public static void main(String[] args){ Heap heap = new Heap(10); /* 5 //Level 0 * */ heap.insert(5); /* 1 //Level 0 * | * 5---| //Level 1 */ heap.insert(1); /* 1 //Level 0 * | * 5---|---3 //Level 1 */ heap.insert(3); /* 1 //Level 0 * | * 5---|---3 //Level 1 * | * 8--| //Level 2 */ heap.insert(8); /* 1 //Level 0 * | * 5---|---3 //Level 1 * | * 8--|--9 //Level 2 */ heap.insert(9); /* 1 //Level 0 * | * 5---|---3 //Level 1 * | | * 8--|--9 6--| //Level 2 */ heap.insert(6); /* 1 //Level 0 * | * 5---|---2 //Level 1 * | | * 8--|--9 6--|--3 //Level 2 */ heap.insert(2); System.out.println(heap.getMinimum()); heap.removeMin(); /* 2 //Level 0 * | * 5---|---3 //Level 1 * | | * 8--|--9 6--| //Level 2 */ System.out.println(heap.getMinimum()); } } If we compile and run the above program then it would produce following result − 1 2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2168, "text": "Heap represents a special tree based data structure used to represent priority queue or for heap sort. We'll going to discuss binary heap tree specifically." }, { "code": null, "e": 2400, "s": 2325, "text": "Binary heap tree can be classified as a binary tree with two constraints −" }, { "code": null, "e": 2565, "s": 2400, "text": "Completeness − Binary heap tree is a complete binary tree except the last level which may not have all elements but elements from left to right should be filled in." }, { "code": null, "e": 2730, "s": 2565, "text": "Completeness − Binary heap tree is a complete binary tree except the last level which may not have all elements but elements from left to right should be filled in." }, { "code": null, "e": 3060, "s": 2730, "text": "Heapness − All parent nodes should be greater or smaller to their children. If parent node is to be greater than its child then it is called Max heap otherwise it is called Min heap. Max heap is used for heap sort and Min heap is used for priority queue. We're considering Min Heap and will use array implementation for the same." }, { "code": null, "e": 3390, "s": 3060, "text": "Heapness − All parent nodes should be greater or smaller to their children. If parent node is to be greater than its child then it is called Max heap otherwise it is called Min heap. Max heap is used for heap sort and Min heap is used for priority queue. We're considering Min Heap and will use array implementation for the same." }, { "code": null, "e": 3464, "s": 3390, "text": "Following are basic primary operations of a Min heap which are following." }, { "code": null, "e": 3502, "s": 3464, "text": "Insert − insert an element in a heap." }, { "code": null, "e": 3540, "s": 3502, "text": "Insert − insert an element in a heap." }, { "code": null, "e": 3589, "s": 3540, "text": "Get Minimum − get minimum element from the heap." }, { "code": null, "e": 3638, "s": 3589, "text": "Get Minimum − get minimum element from the heap." }, { "code": null, "e": 3696, "s": 3638, "text": "Remove Minimum − remove the minimum element from the heap" }, { "code": null, "e": 3754, "s": 3696, "text": "Remove Minimum − remove the minimum element from the heap" }, { "code": null, "e": 3865, "s": 3754, "text": "Whenever an element is to be inserted. Insert element at the end of the array. Increase the size of heap by 1." }, { "code": null, "e": 3976, "s": 3865, "text": "Whenever an element is to be inserted. Insert element at the end of the array. Increase the size of heap by 1." }, { "code": null, "e": 4090, "s": 3976, "text": "Heap up the element while heap property is broken. Compare element with parent's value and swap them if required." }, { "code": null, "e": 4563, "s": 4090, "text": "public void insert(int value) { \n size++;\n intArray[size - 1] = value;\n heapUp(size - 1);\n}\n\nprivate void heapUp(int nodeIndex){\n int parentIndex, tmp;\n if (nodeIndex != 0) {\n parentIndex = getParentIndex(nodeIndex);\n if (intArray[parentIndex] > intArray[nodeIndex]) {\n tmp = intArray[parentIndex];\n intArray[parentIndex] = intArray[nodeIndex];\n intArray[nodeIndex] = tmp;\n heapUp(parentIndex);\n }\n }\n}" }, { "code": null, "e": 4632, "s": 4563, "text": "Get the first element of the array implementing the heap being root." }, { "code": null, "e": 4682, "s": 4632, "text": "public int getMinimum(){\n return intArray[0];\n}" }, { "code": null, "e": 4784, "s": 4682, "text": "Whenever an element is to be removed. Get the last element of the array and reduce size of heap by 1." }, { "code": null, "e": 4886, "s": 4784, "text": "Whenever an element is to be removed. Get the last element of the array and reduce size of heap by 1." }, { "code": null, "e": 5004, "s": 4886, "text": "Heap down the element while heap property is broken. Compare element with children's value and swap them if required." }, { "code": null, "e": 5807, "s": 5004, "text": "public void removeMin() {\n intArray[0] = intArray[size - 1];\n size--;\n if (size > 0)\n heapDown(0);\n}\n\nprivate void heapDown(int nodeIndex){\n int leftChildIndex, rightChildIndex, minIndex, tmp;\n leftChildIndex = getLeftChildIndex(nodeIndex);\n rightChildIndex = getRightChildIndex(nodeIndex);\n if (rightChildIndex >= size) {\n if (leftChildIndex >= size)\n return;\n else\n minIndex = leftChildIndex;\n } else {\n if (intArray[leftChildIndex] <= intArray[rightChildIndex])\n minIndex = leftChildIndex;\n else\n minIndex = rightChildIndex;\n }\n if (intArray[nodeIndex] > intArray[minIndex]) {\n tmp = intArray[minIndex];\n intArray[minIndex] = intArray[nodeIndex];\n intArray[nodeIndex] = tmp;\n heapDown(minIndex);\n }\n}" }, { "code": null, "e": 5817, "s": 5807, "text": "Heap.java" }, { "code": null, "e": 8470, "s": 5817, "text": "package com.tutorialspoint.datastructure;\n\npublic class Heap {\n private int[] intArray;\n private int size;\n\n public Heap(int size){\n intArray = new int[size];\n }\n\n public boolean isEmpty(){\n return size == 0;\n }\n\n public int getMinimum(){\n return intArray[0];\n }\n\n public int getLeftChildIndex(int nodeIndex){\n return 2*nodeIndex +1;\n }\n\n public int getRightChildIndex(int nodeIndex){\n return 2*nodeIndex +2;\n }\n\n public int getParentIndex(int nodeIndex){\n return (nodeIndex -1)/2;\n }\n\n public boolean isFull(){\n return size == intArray.length;\n }\n\n public void insert(int value) { \n size++;\n intArray[size - 1] = value;\n heapUp(size - 1);\n }\n\n public void removeMin() {\n intArray[0] = intArray[size - 1];\n size--;\n if (size > 0)\n heapDown(0);\n }\n\n /**\n * Heap up the new element,until heap property is broken. \n * Steps:\n * 1. Compare node's value with parent's value. \n * 2. Swap them, If they are in wrong order.\n * */\n private void heapUp(int nodeIndex){\n int parentIndex, tmp;\n if (nodeIndex != 0) {\n parentIndex = getParentIndex(nodeIndex);\n if (intArray[parentIndex] > intArray[nodeIndex]) {\n tmp = intArray[parentIndex];\n intArray[parentIndex] = intArray[nodeIndex];\n intArray[nodeIndex] = tmp;\n heapUp(parentIndex);\n }\n }\n }\n\n /**\n * Heap down the root element being least in value,until heap property is broken. \n * Steps:\n * 1.If current node has no children, done. \n * 2.If current node has one children and heap property is broken, \n * 3.Swap the current node and child node and heap down.\n * 4.If current node has one children and heap property is broken, find smaller one \n * 5.Swap the current node and child node and heap down.\n * */\n private void heapDown(int nodeIndex){\n int leftChildIndex, rightChildIndex, minIndex, tmp;\n leftChildIndex = getLeftChildIndex(nodeIndex);\n rightChildIndex = getRightChildIndex(nodeIndex);\n if (rightChildIndex >= size) {\n if (leftChildIndex >= size)\n return;\n else\n minIndex = leftChildIndex;\n } else {\n if (intArray[leftChildIndex] <= intArray[rightChildIndex])\n minIndex = leftChildIndex;\n else\n minIndex = rightChildIndex;\n }\n if (intArray[nodeIndex] > intArray[minIndex]) {\n tmp = intArray[minIndex];\n intArray[minIndex] = intArray[nodeIndex];\n intArray[nodeIndex] = tmp;\n heapDown(minIndex);\n }\n }\n}\n" }, { "code": null, "e": 8484, "s": 8470, "text": "HeapDemo.java" }, { "code": null, "e": 10519, "s": 8484, "text": "package com.tutorialspoint.datastructure;\n\npublic class HeapDemo {\n public static void main(String[] args){\n Heap heap = new Heap(10);\n /* 5 //Level 0\n * \n */\n heap.insert(5);\n /* 1 //Level 0\n * |\n * 5---| //Level 1\n */\n heap.insert(1);\n /* 1 //Level 0\n * |\n * 5---|---3 //Level 1\n */\n heap.insert(3);\n /* 1 //Level 0\n * |\n * 5---|---3 //Level 1\n * |\n * 8--| //Level 2\n */\n heap.insert(8);\n /* 1 //Level 0\n * |\n * 5---|---3 //Level 1\n * |\n * 8--|--9 //Level 2\n */\n heap.insert(9);\n /* 1 //Level 0\n * |\n * 5---|---3 //Level 1\n * | |\n * 8--|--9 6--| //Level 2\n */\n heap.insert(6);\n /* 1 //Level 0\n * |\n * 5---|---2 //Level 1\n * | |\n * 8--|--9 6--|--3 //Level 2\n */\n heap.insert(2);\n\n System.out.println(heap.getMinimum());\n\n heap.removeMin();\n /* 2 //Level 0\n * |\n * 5---|---3 //Level 1\n * | |\n * 8--|--9 6--| //Level 2\n */\n System.out.println(heap.getMinimum()); \n }\n}\n" }, { "code": null, "e": 10600, "s": 10519, "text": "If we compile and run the above program then it would produce following result −" }, { "code": null, "e": 10605, "s": 10600, "text": "1\n2\n" }, { "code": null, "e": 10612, "s": 10605, "text": " Print" }, { "code": null, "e": 10623, "s": 10612, "text": " Add Notes" } ]
Java.util.Hashtable Class
The java.util.Hashtable class implements a hashtable, which maps keys to values.Following are the important points about Hashtable − In this any non-null object can be used as a key or as a value. In this any non-null object can be used as a key or as a value. If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table. If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table. Following is the declaration for java.util.Hashtable class − public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable Hashtable() This constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75). Hashtable(int initialCapacity) This constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75). Hashtable(int initialCapacity, float loadFactor) This constructs a new, empty hashtable with the specified initial capacity and the specified load factor. Hashtable(Map<? extends K,? extends V> t) This constructs a new hashtable with the same mappings as the given Map. This method clears this hashtable so that it contains no keys. This method creates a shallow copy of this hashtable. This method tests if some key maps into the specified value in this hashtable. This method tests if the specified object is a key in this hashtable. This method returns true if this hashtable maps one or more keys to this value. This method returns an enumeration of the values in this hashtable. This method returns a Set view of the mappings contained in this map. This method compares the specified Object with this Map for equality, as per the definition in the Map interface. This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. This method returns the hash code value for this Map as per the definition in the Map interface. This method tests if this hashtable maps no keys to values. This method returns an enumeration of the keys in this hashtable. This method returns a Set view of the keys contained in this map. This method maps the specified key to the specified value in this hashtable. This method copies all of the mappings from the specified map to this hashtable. This method increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently. This method removes the key (and its corresponding value) from this hashtable. This method returns the number of keys in this hashtable. This method returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). This method returns a Collection view of the values contained in this map. This class inherits methods from the following classes − java.util.Object Print Add Notes Bookmark this page
[ { "code": null, "e": 2800, "s": 2667, "text": "The java.util.Hashtable class implements a hashtable, which maps keys to values.Following are the important points about Hashtable −" }, { "code": null, "e": 2864, "s": 2800, "text": "In this any non-null object can be used as a key or as a value." }, { "code": null, "e": 2928, "s": 2864, "text": "In this any non-null object can be used as a key or as a value." }, { "code": null, "e": 3151, "s": 2928, "text": "If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table." }, { "code": null, "e": 3374, "s": 3151, "text": "If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table." }, { "code": null, "e": 3435, "s": 3374, "text": "Following is the declaration for java.util.Hashtable class −" }, { "code": null, "e": 3539, "s": 3435, "text": "public class Hashtable<K,V>\n extends Dictionary<K,V>\n implements Map<K,V>, Cloneable, Serializable\n" }, { "code": null, "e": 3551, "s": 3539, "text": "Hashtable()" }, { "code": null, "e": 3651, "s": 3551, "text": "This constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75)." }, { "code": null, "e": 3682, "s": 3651, "text": "Hashtable(int initialCapacity)" }, { "code": null, "e": 3789, "s": 3682, "text": "This constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75)." }, { "code": null, "e": 3838, "s": 3789, "text": "Hashtable(int initialCapacity, float loadFactor)" }, { "code": null, "e": 3944, "s": 3838, "text": "This constructs a new, empty hashtable with the specified initial capacity and the specified load factor." }, { "code": null, "e": 3986, "s": 3944, "text": "Hashtable(Map<? extends K,? extends V> t)" }, { "code": null, "e": 4059, "s": 3986, "text": "This constructs a new hashtable with the same mappings as the given Map." }, { "code": null, "e": 4122, "s": 4059, "text": "This method clears this hashtable so that it contains no keys." }, { "code": null, "e": 4176, "s": 4122, "text": "This method creates a shallow copy of this hashtable." }, { "code": null, "e": 4255, "s": 4176, "text": "This method tests if some key maps into the specified value in this hashtable." }, { "code": null, "e": 4325, "s": 4255, "text": "This method tests if the specified object is a key in this hashtable." }, { "code": null, "e": 4405, "s": 4325, "text": "This method returns true if this hashtable maps one or more keys to this value." }, { "code": null, "e": 4473, "s": 4405, "text": "This method returns an enumeration of the values in this hashtable." }, { "code": null, "e": 4543, "s": 4473, "text": "This method returns a Set view of the mappings contained in this map." }, { "code": null, "e": 4657, "s": 4543, "text": "This method compares the specified Object with this Map for equality, as per the definition in the Map interface." }, { "code": null, "e": 4778, "s": 4657, "text": "This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key." }, { "code": null, "e": 4875, "s": 4778, "text": "This method returns the hash code value for this Map as per the definition in the Map interface." }, { "code": null, "e": 4935, "s": 4875, "text": "This method tests if this hashtable maps no keys to values." }, { "code": null, "e": 5001, "s": 4935, "text": "This method returns an enumeration of the keys in this hashtable." }, { "code": null, "e": 5067, "s": 5001, "text": "This method returns a Set view of the keys contained in this map." }, { "code": null, "e": 5144, "s": 5067, "text": "This method maps the specified key to the specified value in this hashtable." }, { "code": null, "e": 5225, "s": 5144, "text": "This method copies all of the mappings from the specified map to this hashtable." }, { "code": null, "e": 5371, "s": 5225, "text": "This method increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently." }, { "code": null, "e": 5450, "s": 5371, "text": "This method removes the key (and its corresponding value) from this hashtable." }, { "code": null, "e": 5508, "s": 5450, "text": "This method returns the number of keys in this hashtable." }, { "code": null, "e": 5691, "s": 5508, "text": "This method returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters \", \" (comma and space)." }, { "code": null, "e": 5766, "s": 5691, "text": "This method returns a Collection view of the values contained in this map." }, { "code": null, "e": 5823, "s": 5766, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 5840, "s": 5823, "text": "java.util.Object" }, { "code": null, "e": 5847, "s": 5840, "text": " Print" }, { "code": null, "e": 5858, "s": 5847, "text": " Add Notes" } ]
hidden.bs.modal Bootstrap Event
The hidden.bs.modal event in Bootstrap fires when the modal is completely hidden. Hide the modal on button click − $("#button1").click(function(){ $("#newModal").modal("hide"); }); After you will hide it, use the hidden.bs.modal Bootstrap event to generate an alert before the modal completely hides − $("#newModal").on('hidden.bs.modal', function () { alert('The modal is completely hidden now!'); }); You can try to run the following code to implement the hidden.bs.modal event − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <style> #button1 { width: 140px; padding: 20px; bottom: 150px; z-index: 9999; font-size:15px; position: absolute; margin: 0 auto; } </style> </head> <body> <div class="container"> <h2>Sample</h2> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <button type="button" class="btn btn-default btn-lg" id="button1">Click to hide</button> <div class="modal fade" id="newModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Information</h4> </div> <div class="modal-body"> <p>Crucial Information about the Examination.</p> </div> </div> </div> </div> </div> <script> $(document).ready(function(){ $("#newModal").modal("show"); $("#button1").click(function(){ $("#newModal").modal("hide"); }); $("#newModal").on('hide.bs.modal', function () { alert('The modal is about to be hidden!'); }); $("#newModal").on('hidden.bs.modal', function () { alert('The modal is completely hidden now!'); }); }); </script> </body> </html>
[ { "code": null, "e": 1144, "s": 1062, "text": "The hidden.bs.modal event in Bootstrap fires when the modal is completely hidden." }, { "code": null, "e": 1177, "s": 1144, "text": "Hide the modal on button click −" }, { "code": null, "e": 1245, "s": 1177, "text": "$(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"hide\");\n});" }, { "code": null, "e": 1366, "s": 1245, "text": "After you will hide it, use the hidden.bs.modal Bootstrap event to generate an alert before the modal completely hides −" }, { "code": null, "e": 1469, "s": 1366, "text": "$(\"#newModal\").on('hidden.bs.modal', function () {\n alert('The modal is completely hidden now!');\n});" }, { "code": null, "e": 1548, "s": 1469, "text": "You can try to run the following code to implement the hidden.bs.modal event −" }, { "code": null, "e": 1558, "s": 1548, "text": "Live Demo" }, { "code": null, "e": 3565, "s": 1558, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n <style>\n #button1 {\n width: 140px;\n padding: 20px;\n bottom: 150px;\n z-index: 9999;\n font-size:15px;\n position: absolute;\n margin: 0 auto;\n }\n </style>\n </head>\n\n<body>\n <div class=\"container\">\n <h2>Sample</h2>\n <p>This is demo text.</p>\n <p>This is demo text.</p> \n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">Click to hide</button>\n <div class=\"modal fade\" id=\"newModal\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Information</h4>\n </div>\n <div class=\"modal-body\">\n <p>Crucial Information about the Examination.</p>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n<script>\n$(document).ready(function(){\n $(\"#newModal\").modal(\"show\");\n\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"hide\");\n });\n $(\"#newModal\").on('hide.bs.modal', function () {\n alert('The modal is about to be hidden!');\n });\n $(\"#newModal\").on('hidden.bs.modal', function () {\n alert('The modal is completely hidden now!');\n });\n});\n</script>\n\n</body>\n</html>" } ]
Ruby | Math log() function - GeeksforGeeks
07 Jan, 2020 The log() function in Ruby returns the logarithm value of X. The second parameter is the base given by the user to which the logarithm value is returned. In case its not given, then the default base is e. Syntax: Math.log(X, base) Parameter: The function takes one mandatory parameter X whose logarithm value is to be returned and a non-mandatory parameter base, to whose base is the logarithm. Return Value: The function returns the logarithm value of X. Example 1: # Ruby program for log() function # Assigning valuesval1 = 213val2 = 256base2 = 2 val3 = 27 base3 = 3 val4 = 100 base4 = 10 # Prints the value returned by log() puts Math.log(val1) puts Math.log(val2, base2) puts Math.log(val3, base3) puts Math.log(val4, base4) Output: 5.3612921657094255 8.0 3.0 2.0 Example 2: # Ruby program for log() function # Assigning valuesval1 = 10 val2 = 256base2 = 4 val3 = 27 base3 = 10 val4 = 105 base4 = 7 # Prints the value returned by log() puts Math.log(val1) puts Math.log(val2, base2) puts Math.log(val3, base3) puts Math.log(val4, base4) Output: 2.302585092994046 4.0 1.4313637641589871 2.3916625094004957 Reference: https://devdocs.io/ruby~2.5/math#method-c-log Ruby Math-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Array slice() function Ruby | Array count() operation Ruby | Enumerator each_with_index function Ruby | Array select() function Global Variable in Ruby Ruby | Hash delete() function Ruby | String gsub! Method Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | Case Statement Include v/s Extend in Ruby
[ { "code": null, "e": 23888, "s": 23860, "text": "\n07 Jan, 2020" }, { "code": null, "e": 24093, "s": 23888, "text": "The log() function in Ruby returns the logarithm value of X. The second parameter is the base given by the user to which the logarithm value is returned. In case its not given, then the default base is e." }, { "code": null, "e": 24119, "s": 24093, "text": "Syntax: Math.log(X, base)" }, { "code": null, "e": 24283, "s": 24119, "text": "Parameter: The function takes one mandatory parameter X whose logarithm value is to be returned and a non-mandatory parameter base, to whose base is the logarithm." }, { "code": null, "e": 24344, "s": 24283, "text": "Return Value: The function returns the logarithm value of X." }, { "code": null, "e": 24355, "s": 24344, "text": "Example 1:" }, { "code": "# Ruby program for log() function # Assigning valuesval1 = 213val2 = 256base2 = 2 val3 = 27 base3 = 3 val4 = 100 base4 = 10 # Prints the value returned by log() puts Math.log(val1) puts Math.log(val2, base2) puts Math.log(val3, base3) puts Math.log(val4, base4)", "e": 24625, "s": 24355, "text": null }, { "code": null, "e": 24633, "s": 24625, "text": "Output:" }, { "code": null, "e": 24664, "s": 24633, "text": "5.3612921657094255\n8.0\n3.0\n2.0" }, { "code": null, "e": 24675, "s": 24664, "text": "Example 2:" }, { "code": "# Ruby program for log() function # Assigning valuesval1 = 10 val2 = 256base2 = 4 val3 = 27 base3 = 10 val4 = 105 base4 = 7 # Prints the value returned by log() puts Math.log(val1) puts Math.log(val2, base2) puts Math.log(val3, base3) puts Math.log(val4, base4)", "e": 24946, "s": 24675, "text": null }, { "code": null, "e": 24954, "s": 24946, "text": "Output:" }, { "code": null, "e": 25015, "s": 24954, "text": "2.302585092994046\n4.0\n1.4313637641589871\n2.3916625094004957\n" }, { "code": null, "e": 25072, "s": 25015, "text": "Reference: https://devdocs.io/ruby~2.5/math#method-c-log" }, { "code": null, "e": 25088, "s": 25072, "text": "Ruby Math-class" }, { "code": null, "e": 25101, "s": 25088, "text": "Ruby-Methods" }, { "code": null, "e": 25106, "s": 25101, "text": "Ruby" }, { "code": null, "e": 25204, "s": 25106, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25213, "s": 25204, "text": "Comments" }, { "code": null, "e": 25226, "s": 25213, "text": "Old Comments" }, { "code": null, "e": 25256, "s": 25226, "text": "Ruby | Array slice() function" }, { "code": null, "e": 25287, "s": 25256, "text": "Ruby | Array count() operation" }, { "code": null, "e": 25330, "s": 25287, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 25361, "s": 25330, "text": "Ruby | Array select() function" }, { "code": null, "e": 25385, "s": 25361, "text": "Global Variable in Ruby" }, { "code": null, "e": 25415, "s": 25385, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 25442, "s": 25415, "text": "Ruby | String gsub! Method" }, { "code": null, "e": 25510, "s": 25442, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" }, { "code": null, "e": 25532, "s": 25510, "text": "Ruby | Case Statement" } ]
MySQL query to select multiple rows effectively?
You need to use index to select multiple rows effectively. Let us first create a table − mysql> create table DemoTable1501 -> ( -> Id int NOT NULL PRIMARY KEY, -> URL text -> ); Query OK, 0 rows affected (0.62 sec) Here is the query to create index − mysql> create index id_index on DemoTable1501(Id); Query OK, 0 rows affected (0.23 sec) Records: 0 Duplicates: 0 Warnings: 0 Insert some records in the table using insert command − mysql> insert into DemoTable1501 values(101,'www.facebook.com'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1501 values(110,'www.google.com'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1501 values(220,'www.gmail.com'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable1501 values(350,'www.youtube.com'); Query OK, 1 row affected (0.08 sec) Display all records from the table using select statement − mysql> select * from DemoTable1501; This will produce the following output − +-----+------------------+ | Id | URL | +-----+------------------+ | 101 | www.facebook.com | | 110 | www.google.com | | 220 | www.gmail.com | | 350 | www.youtube.com | +-----+------------------+ 4 rows in set (0.00 sec) Following is the query to select multiple rows efficiently − mysql> select * from DemoTable1501 -> where Id in(101,220,350); This will produce the following output − +-----+------------------+ | Id | URL | +-----+------------------+ | 101 | www.facebook.com | | 220 | www.gmail.com | | 350 | www.youtube.com | +-----+------------------+ 3 rows in set (0.00 sec) To prove this, use the SHOW command in which the Handler_read_key uses 3 out of 4 Ids − mysql> SHOW STATUS LIKE 'Handler_%'; This will produce the following output − +----------------------------+-------+ | Variable_name | Value | +----------------------------+-------+ | Handler_commit | 1 | | Handler_delete | 0 | | Handler_discover | 0 | | Handler_external_lock | 2 | | Handler_mrr_init | 0 | | Handler_prepare | 0 | | Handler_read_first | 0 | | Handler_read_key | 3 | | Handler_read_last | 0 | | Handler_read_next | 0 | | Handler_read_prev | 0 | | Handler_read_rnd | 0 | | Handler_read_rnd_next | 0 | | Handler_rollback | 0 | | Handler_savepoint | 0 | | Handler_savepoint_rollback | 0 | | Handler_update | 0 | | Handler_write | 0 | +----------------------------+-------+ 18 rows in set (0.00 sec)
[ { "code": null, "e": 1151, "s": 1062, "text": "You need to use index to select multiple rows effectively. Let us first create a table −" }, { "code": null, "e": 1289, "s": 1151, "text": "mysql> create table DemoTable1501\n -> (\n -> Id int NOT NULL PRIMARY KEY,\n -> URL text\n -> );\nQuery OK, 0 rows affected (0.62 sec)" }, { "code": null, "e": 1325, "s": 1289, "text": "Here is the query to create index −" }, { "code": null, "e": 1452, "s": 1325, "text": "mysql> create index id_index on DemoTable1501(Id);\nQuery OK, 0 rows affected (0.23 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1508, "s": 1452, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1906, "s": 1508, "text": "mysql> insert into DemoTable1501 values(101,'www.facebook.com');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1501 values(110,'www.google.com');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable1501 values(220,'www.gmail.com');\nQuery OK, 1 row affected (0.06 sec)\nmysql> insert into DemoTable1501 values(350,'www.youtube.com');\nQuery OK, 1 row affected (0.08 sec)" }, { "code": null, "e": 1966, "s": 1906, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2002, "s": 1966, "text": "mysql> select * from DemoTable1501;" }, { "code": null, "e": 2043, "s": 2002, "text": "This will produce the following output −" }, { "code": null, "e": 2284, "s": 2043, "text": "+-----+------------------+\n| Id | URL |\n+-----+------------------+\n| 101 | www.facebook.com |\n| 110 | www.google.com |\n| 220 | www.gmail.com |\n| 350 | www.youtube.com |\n+-----+------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2345, "s": 2284, "text": "Following is the query to select multiple rows efficiently −" }, { "code": null, "e": 2412, "s": 2345, "text": "mysql> select * from DemoTable1501\n -> where Id in(101,220,350);" }, { "code": null, "e": 2453, "s": 2412, "text": "This will produce the following output −" }, { "code": null, "e": 2666, "s": 2453, "text": "+-----+------------------+\n| Id | URL |\n+-----+------------------+\n| 101 | www.facebook.com |\n| 220 | www.gmail.com |\n| 350 | www.youtube.com |\n+-----+------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2754, "s": 2666, "text": "To prove this, use the SHOW command in which the Handler_read_key uses 3 out of 4 Ids −" }, { "code": null, "e": 2791, "s": 2754, "text": "mysql> SHOW STATUS LIKE 'Handler_%';" }, { "code": null, "e": 2832, "s": 2791, "text": "This will produce the following output −" }, { "code": null, "e": 3716, "s": 2832, "text": "+----------------------------+-------+\n| Variable_name | Value |\n+----------------------------+-------+\n| Handler_commit | 1 |\n| Handler_delete | 0 |\n| Handler_discover | 0 |\n| Handler_external_lock | 2 |\n| Handler_mrr_init | 0 |\n| Handler_prepare | 0 |\n| Handler_read_first | 0 |\n| Handler_read_key | 3 |\n| Handler_read_last | 0 |\n| Handler_read_next | 0 |\n| Handler_read_prev | 0 |\n| Handler_read_rnd | 0 |\n| Handler_read_rnd_next | 0 |\n| Handler_rollback | 0 |\n| Handler_savepoint | 0 |\n| Handler_savepoint_rollback | 0 |\n| Handler_update | 0 |\n| Handler_write | 0 |\n+----------------------------+-------+\n18 rows in set (0.00 sec)" } ]
HyperOpt: Hyperparameter Tuning based on Bayesian Optimization | by Fernando López | Towards Data Science
Finding the optimal hyperparameter configuration for a given function should not be based entirely on intuition or the experience of some. On the contrary, the search for such an optimal configuration must be supported by approaches that guarantee such optimality. Among so many approaches, we can find some based on exhaustive searches (e.g. Grid Search and Random Search [1]), or under an optimization paradigm such as Genetic Algorithms (e.g. TPOT [2]) and Bayesian Optimization [3]. Let’s talk about HyperOpt, a tool that was designed to automate the search for optimal hyperparameter configuration based on a Bayesian Optimization and supported by the SMBO (Sequential Model-Based Global Optimization) methodology. So, this blog will be divided as follows: What is HyperOpt? What is HyperOpt-Sklearn? HyperOpt in practice HyperOpt-Sklearn in practice HyperOpt is an open-source python library created by James Bergstra in 2011 [4]. HyperOpt is a tool that allows the automation of the search for the optimal hyperparameters of a machine learning model. HyperOpt is based on Bayesian Optimization supported by a SMBO methodology adapted to work with different algorithms such as: Tree of Parzen Estimators (TPE), Adaptive Tree of Parzen Estimators (ATPE) and Gaussian Processes (GP) [5]. The approach of Bayesian Optimization focuses on a probability model P(score| configuration), which is updated through an iterative process of querying a history “H” of (score, configuration) whose objective is the maximization of the score given a configuration “c”. HyperOpt takes Bayesian Optimization as its premise by making some variations in the sampling process, the definition and narrow down of the search space and the algorithms for maximizing the probability model [4]. HyperOpt requires 4 essential components for the optimization of hyperparameters: the search space, the loss function, the optimization algorithm and a database for storing the history (score, configuration). The search space will be determined by a continuous and convex function. The loss function is that function that needs to be optimized, which is obtained by evaluating the model with the “c” configuration. The optimization algorithm is based on the SMBO methodology with the variants given by the GP, TPE and ATPE algorithms. The “H” database stores a set of tuples (score, configuration) obtained through the iterations of the optimization algorithm. In Figure 2 we can see a graphic description of how HyperOpt works. Given the usability and scalability of HyperOpt, an extension was created that incorporates various scikit-learn components in order to optimize machine learning pipelines with large amounts of parameters, this extension is called HyperOpt-Sklearn which we will talk about in the next section, let’s go for it! HyperOpt-Sklearn was introduced in 2014 [6]. HyperOpt-Sklearn is built on top of HyperOpt and is designed to work with various components of the scikit-learn suite. HyperOpt-Sklearn was created with the objective of optimizing machine learning pipelines, addressing specifically the phases of data transformation, model selection and hyperparameter optimization. HyperOpt-Sklearn unifies the advantages of HyperOpt with the usability and flexibility of the scikit-learn framework, in this sense, HyperOpt-Sklearn is designed to tackle classification and regression tasks. In figure 3 we can see the components of an ML pipeline optimized by HyperOpt-Sklearn. In short, HyperOpt was designed to optimize hyperparameters of one or several given functions under the paradigm of Bayesian optimization. On the other hand, HyperOpt-Sklearn was developed to optimize different components of a machine learning pipeline using HyperOpt as the core and taking various components from the scikit-learn suite. Now let’s see how we use them in practice. Now that we understand how HyperOpt works and what its components are, let’s look at a basic implementation. For this example, we are going to use the function shown in Figure 4. As we can see, the minimum of the function is given when the value of x = -0.5. Let’s see how to find this value in HyperOpt. HyperOpt requires 4 parameters for a basic implementation which are: the function to be optimized, the search space, the optimizer algorithm and the number of iterations. So the implementation would look like this: As we can see, we are defining each component that HyperOpt requires to optimize a dummy function. In line 7 the definition of the function to be optimized is performed. In line 11 the definition of the search space is carried out, in this case only one search space was defined for the value of “x”, however, for functions with more than one variable, it will be required to define a search space for each variable, likewise such search space will depend on the type of function to be optimized. In this case, for didactic purposes, a search space was defined from -2 to 2. Finally, on line 18, the class that hosts the optimization process is initialized. Such function receives as parameters the function to be optimized, the search space, the optimization algorithm (in this case it is Tree-structured of Parzen Estimators) and the number of iterations. When executing the previous code snippet we obtain the value of “x” that optimizes the function: Optimal value of x: {'x': -0.5000806428004325} The previous implementation is a basic example of how HyperOpt works and what its main components are. The optimization of more elaborate functions will require the adequate definition of the search space as well as the optimizer. HyperOpt provides a set of search space initializers which you can find here. Great, we have already seen how HyperOpt works in a basic implementation, now let’s see how HyperOpt-Sklearn works for Machine Learning pipeline optimization. The way to implement HyperOpt-Sklearn is quite similar to HyperOpt. Since HyperOpt-Sklearn is focused on optimizing machine learning pipelines, the 3 essential parameters that are required are: the type of preprocessor, the machine learning model (i.e. classifier or regressor) and the optimizer. It is important to mention that each of these three basic elements are customizable according to the needs of each problem. The preprocessors adapted in HyperOpt Sklearn are: PCA, TfidfVectorizer, StandardScalar, MinMaxScalar, Normalizer, OneHotEncoder. The classifiers adapted in HyperOpt Sklearn are: SVC, LinearSVC KNeightborsClassifier. RandomForestClassifier, ExtraTreesClassifier SGDClassifier, MultinomialNB, BernoulliRBM, ColumnKMeans. For the purposes of this blog, let’s look at two basic implementations of HyperOpt-Sklearn in a classification problem. In this example we will work with the well known breast cancer dataset. As we can see, in line 22 we are defining the classifier that will be implemented, in this case the instruction is to search over all the classifiers defined by HyperOpt-Sklearn (in practice this is not recommended due to the computation time needed for the optimization, since this is a practical example, doing a full search is not a determining factor). In line 23 the type of transformation that the data will receive is defined, in this case the instruction to use the complete suite of transformers implemented by HyperOpt-Sklearn (as you can guess, only those that fit the dataset are tested, e.g. text transformers are not applied to a numeric dataset). In line 24 the optimizer is defined, in this case it is TPE. The rest of the lines determine the number of iterations and the time limit for each evaluation. When executing the code snippet 2 we obtain Train score: 0.9723618090452262Test score: 0.9824561403508771 The optimal configuration is: {'learner': ExtraTreesClassifier(max_features=None, min_samples_leaf=9, n_estimators=19, n_jobs=1, random_state=3, verbose=False), 'preprocs': (MinMaxScaler(feature_range=(-1.0, 1.0)),), 'ex_preprocs': ()} Well, we have obtained an optimal configuration by doing a search across the entire spectrum that HyperOpt-Sklearn covers for a classification problem. Now let’s see how we would narrow down the search space by using a specific classifier. For this example we will also use the breast cancer dataset. However, this time we will use a single classifier of which we will try to optimize each of its parameters by defining a search space for each one. In this example we are using SGD as a classifier for which we want to optimize the loss parameter as well as the alpha value. As we can see, in line 23 we are defining a search space for loss, such a search space is defined by three different values (hinge, log, huber) with a probability value that is considered when selecting one of these three values. On the other hand, in line 29 we are defining the search space for the alpha value, in this case a log function is implemented which is bounded by a lower and upper limit. Finally, on line 33, the class that will host the optimization process is defined. The parameters it receives are the classifier (with their respective parameters and search spaces), the optimizer, the number of iterations, and the designated time for each evaluation. When executing the code snippet 3we obtain Train score: 0.9522613065326633Test score: 0.9473684210526315 The optimal configuration found is: {'learner': SGDClassifier(alpha=0.08612797536101766, class_weight='balanced', eta0=6.478871110431366e-05, l1_ratio=0.20803307323675568, learning_rate='invscaling', loss='log', max_iter=18547873.0, n_jobs=1, power_t=0.1770890191026292, random_state=0, tol=0.000332542442869532, verbose=False), 'preprocs': (PCA(n_components=8),), 'ex_preprocs': ()} HyperOpt-Sklearn configurations and customizations will always depend on the type of problem to be solved, the data types as well as the available computing power. In this blog we saw what HyperOpt is, its purpose, how it works and what its main components are. Likewise, we saw one of the main extensions of HyperOpt which is HyperOpt-Sklearn, its components and how it works. HyperOpt is an alternative for the optimization of hyperparameters, either in specific functions or optimizing pipelines of machine learning. One of the great advantages of HyperOpt is the implementation of Bayesian optimization with specific adaptations, which makes HyperOpt a tool to consider for tuning hyperparameters. [1] Tuning the hyper-parameters of an estimator [2] TPOT: Pipelines Optimization with Genetic Algorithms [3] A Tutorial on Bayesian Optimization [4] Making a Science of Model Search: Hyperparameter Optimization in Hundreds of Dimensions for Vision Architectures [5] Algorithms for Hyper-Parameter Optimization [6] Hyperopt-Sklearn: Automatic Hyperparameter Configuration for Scikit-Learn
[ { "code": null, "e": 659, "s": 172, "text": "Finding the optimal hyperparameter configuration for a given function should not be based entirely on intuition or the experience of some. On the contrary, the search for such an optimal configuration must be supported by approaches that guarantee such optimality. Among so many approaches, we can find some based on exhaustive searches (e.g. Grid Search and Random Search [1]), or under an optimization paradigm such as Genetic Algorithms (e.g. TPOT [2]) and Bayesian Optimization [3]." }, { "code": null, "e": 934, "s": 659, "text": "Let’s talk about HyperOpt, a tool that was designed to automate the search for optimal hyperparameter configuration based on a Bayesian Optimization and supported by the SMBO (Sequential Model-Based Global Optimization) methodology. So, this blog will be divided as follows:" }, { "code": null, "e": 952, "s": 934, "text": "What is HyperOpt?" }, { "code": null, "e": 978, "s": 952, "text": "What is HyperOpt-Sklearn?" }, { "code": null, "e": 999, "s": 978, "text": "HyperOpt in practice" }, { "code": null, "e": 1028, "s": 999, "text": "HyperOpt-Sklearn in practice" }, { "code": null, "e": 1464, "s": 1028, "text": "HyperOpt is an open-source python library created by James Bergstra in 2011 [4]. HyperOpt is a tool that allows the automation of the search for the optimal hyperparameters of a machine learning model. HyperOpt is based on Bayesian Optimization supported by a SMBO methodology adapted to work with different algorithms such as: Tree of Parzen Estimators (TPE), Adaptive Tree of Parzen Estimators (ATPE) and Gaussian Processes (GP) [5]." }, { "code": null, "e": 1947, "s": 1464, "text": "The approach of Bayesian Optimization focuses on a probability model P(score| configuration), which is updated through an iterative process of querying a history “H” of (score, configuration) whose objective is the maximization of the score given a configuration “c”. HyperOpt takes Bayesian Optimization as its premise by making some variations in the sampling process, the definition and narrow down of the search space and the algorithms for maximizing the probability model [4]." }, { "code": null, "e": 2676, "s": 1947, "text": "HyperOpt requires 4 essential components for the optimization of hyperparameters: the search space, the loss function, the optimization algorithm and a database for storing the history (score, configuration). The search space will be determined by a continuous and convex function. The loss function is that function that needs to be optimized, which is obtained by evaluating the model with the “c” configuration. The optimization algorithm is based on the SMBO methodology with the variants given by the GP, TPE and ATPE algorithms. The “H” database stores a set of tuples (score, configuration) obtained through the iterations of the optimization algorithm. In Figure 2 we can see a graphic description of how HyperOpt works." }, { "code": null, "e": 2987, "s": 2676, "text": "Given the usability and scalability of HyperOpt, an extension was created that incorporates various scikit-learn components in order to optimize machine learning pipelines with large amounts of parameters, this extension is called HyperOpt-Sklearn which we will talk about in the next section, let’s go for it!" }, { "code": null, "e": 3646, "s": 2987, "text": "HyperOpt-Sklearn was introduced in 2014 [6]. HyperOpt-Sklearn is built on top of HyperOpt and is designed to work with various components of the scikit-learn suite. HyperOpt-Sklearn was created with the objective of optimizing machine learning pipelines, addressing specifically the phases of data transformation, model selection and hyperparameter optimization. HyperOpt-Sklearn unifies the advantages of HyperOpt with the usability and flexibility of the scikit-learn framework, in this sense, HyperOpt-Sklearn is designed to tackle classification and regression tasks. In figure 3 we can see the components of an ML pipeline optimized by HyperOpt-Sklearn." }, { "code": null, "e": 4028, "s": 3646, "text": "In short, HyperOpt was designed to optimize hyperparameters of one or several given functions under the paradigm of Bayesian optimization. On the other hand, HyperOpt-Sklearn was developed to optimize different components of a machine learning pipeline using HyperOpt as the core and taking various components from the scikit-learn suite. Now let’s see how we use them in practice." }, { "code": null, "e": 4333, "s": 4028, "text": "Now that we understand how HyperOpt works and what its components are, let’s look at a basic implementation. For this example, we are going to use the function shown in Figure 4. As we can see, the minimum of the function is given when the value of x = -0.5. Let’s see how to find this value in HyperOpt." }, { "code": null, "e": 4548, "s": 4333, "text": "HyperOpt requires 4 parameters for a basic implementation which are: the function to be optimized, the search space, the optimizer algorithm and the number of iterations. So the implementation would look like this:" }, { "code": null, "e": 5503, "s": 4548, "text": "As we can see, we are defining each component that HyperOpt requires to optimize a dummy function. In line 7 the definition of the function to be optimized is performed. In line 11 the definition of the search space is carried out, in this case only one search space was defined for the value of “x”, however, for functions with more than one variable, it will be required to define a search space for each variable, likewise such search space will depend on the type of function to be optimized. In this case, for didactic purposes, a search space was defined from -2 to 2. Finally, on line 18, the class that hosts the optimization process is initialized. Such function receives as parameters the function to be optimized, the search space, the optimization algorithm (in this case it is Tree-structured of Parzen Estimators) and the number of iterations. When executing the previous code snippet we obtain the value of “x” that optimizes the function:" }, { "code": null, "e": 5550, "s": 5503, "text": "Optimal value of x: {'x': -0.5000806428004325}" }, { "code": null, "e": 5859, "s": 5550, "text": "The previous implementation is a basic example of how HyperOpt works and what its main components are. The optimization of more elaborate functions will require the adequate definition of the search space as well as the optimizer. HyperOpt provides a set of search space initializers which you can find here." }, { "code": null, "e": 6018, "s": 5859, "text": "Great, we have already seen how HyperOpt works in a basic implementation, now let’s see how HyperOpt-Sklearn works for Machine Learning pipeline optimization." }, { "code": null, "e": 6439, "s": 6018, "text": "The way to implement HyperOpt-Sklearn is quite similar to HyperOpt. Since HyperOpt-Sklearn is focused on optimizing machine learning pipelines, the 3 essential parameters that are required are: the type of preprocessor, the machine learning model (i.e. classifier or regressor) and the optimizer. It is important to mention that each of these three basic elements are customizable according to the needs of each problem." }, { "code": null, "e": 6759, "s": 6439, "text": "The preprocessors adapted in HyperOpt Sklearn are: PCA, TfidfVectorizer, StandardScalar, MinMaxScalar, Normalizer, OneHotEncoder. The classifiers adapted in HyperOpt Sklearn are: SVC, LinearSVC KNeightborsClassifier. RandomForestClassifier, ExtraTreesClassifier SGDClassifier, MultinomialNB, BernoulliRBM, ColumnKMeans." }, { "code": null, "e": 6951, "s": 6759, "text": "For the purposes of this blog, let’s look at two basic implementations of HyperOpt-Sklearn in a classification problem. In this example we will work with the well known breast cancer dataset." }, { "code": null, "e": 7771, "s": 6951, "text": "As we can see, in line 22 we are defining the classifier that will be implemented, in this case the instruction is to search over all the classifiers defined by HyperOpt-Sklearn (in practice this is not recommended due to the computation time needed for the optimization, since this is a practical example, doing a full search is not a determining factor). In line 23 the type of transformation that the data will receive is defined, in this case the instruction to use the complete suite of transformers implemented by HyperOpt-Sklearn (as you can guess, only those that fit the dataset are tested, e.g. text transformers are not applied to a numeric dataset). In line 24 the optimizer is defined, in this case it is TPE. The rest of the lines determine the number of iterations and the time limit for each evaluation." }, { "code": null, "e": 7815, "s": 7771, "text": "When executing the code snippet 2 we obtain" }, { "code": null, "e": 7877, "s": 7815, "text": "Train score: 0.9723618090452262Test score: 0.9824561403508771" }, { "code": null, "e": 7907, "s": 7877, "text": "The optimal configuration is:" }, { "code": null, "e": 8113, "s": 7907, "text": "{'learner': ExtraTreesClassifier(max_features=None, min_samples_leaf=9, n_estimators=19, n_jobs=1, random_state=3, verbose=False), 'preprocs': (MinMaxScaler(feature_range=(-1.0, 1.0)),), 'ex_preprocs': ()}" }, { "code": null, "e": 8353, "s": 8113, "text": "Well, we have obtained an optimal configuration by doing a search across the entire spectrum that HyperOpt-Sklearn covers for a classification problem. Now let’s see how we would narrow down the search space by using a specific classifier." }, { "code": null, "e": 8562, "s": 8353, "text": "For this example we will also use the breast cancer dataset. However, this time we will use a single classifier of which we will try to optimize each of its parameters by defining a search space for each one." }, { "code": null, "e": 9359, "s": 8562, "text": "In this example we are using SGD as a classifier for which we want to optimize the loss parameter as well as the alpha value. As we can see, in line 23 we are defining a search space for loss, such a search space is defined by three different values (hinge, log, huber) with a probability value that is considered when selecting one of these three values. On the other hand, in line 29 we are defining the search space for the alpha value, in this case a log function is implemented which is bounded by a lower and upper limit. Finally, on line 33, the class that will host the optimization process is defined. The parameters it receives are the classifier (with their respective parameters and search spaces), the optimizer, the number of iterations, and the designated time for each evaluation." }, { "code": null, "e": 9402, "s": 9359, "text": "When executing the code snippet 3we obtain" }, { "code": null, "e": 9464, "s": 9402, "text": "Train score: 0.9522613065326633Test score: 0.9473684210526315" }, { "code": null, "e": 9500, "s": 9464, "text": "The optimal configuration found is:" }, { "code": null, "e": 9852, "s": 9500, "text": "{'learner': SGDClassifier(alpha=0.08612797536101766, class_weight='balanced', eta0=6.478871110431366e-05, l1_ratio=0.20803307323675568, learning_rate='invscaling', loss='log', max_iter=18547873.0, n_jobs=1, power_t=0.1770890191026292, random_state=0, tol=0.000332542442869532, verbose=False), 'preprocs': (PCA(n_components=8),), 'ex_preprocs': ()}" }, { "code": null, "e": 10016, "s": 9852, "text": "HyperOpt-Sklearn configurations and customizations will always depend on the type of problem to be solved, the data types as well as the available computing power." }, { "code": null, "e": 10230, "s": 10016, "text": "In this blog we saw what HyperOpt is, its purpose, how it works and what its main components are. Likewise, we saw one of the main extensions of HyperOpt which is HyperOpt-Sklearn, its components and how it works." }, { "code": null, "e": 10554, "s": 10230, "text": "HyperOpt is an alternative for the optimization of hyperparameters, either in specific functions or optimizing pipelines of machine learning. One of the great advantages of HyperOpt is the implementation of Bayesian optimization with specific adaptations, which makes HyperOpt a tool to consider for tuning hyperparameters." }, { "code": null, "e": 10602, "s": 10554, "text": "[1] Tuning the hyper-parameters of an estimator" }, { "code": null, "e": 10659, "s": 10602, "text": "[2] TPOT: Pipelines Optimization with Genetic Algorithms" }, { "code": null, "e": 10699, "s": 10659, "text": "[3] A Tutorial on Bayesian Optimization" }, { "code": null, "e": 10816, "s": 10699, "text": "[4] Making a Science of Model Search: Hyperparameter Optimization in Hundreds of Dimensions for Vision Architectures" }, { "code": null, "e": 10864, "s": 10816, "text": "[5] Algorithms for Hyper-Parameter Optimization" } ]
How Does MySQL Process order by and limit in a Query? - GeeksforGeeks
13 Sep, 2021 In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers. Syntax: SELECT column1, column2, ... FROM table_name LIMIT offset, count; The Limit clause accepts one or two parameters, whenever two parameters are specified, the first is the offset and the second denotes the count whereas whenever only one parameter is specified, it denotes the number of rows to be returned from the beginning of the result set. Offset: It is used to specify the offset of the first row to be returned. Count: It is used to specify the maximum number of rows to be returned. Syntax: SELECT expressions FROM tables [WHERE conditions] [ORDER BY expression [ ASC | DESC ]] LIMIT row_count_number; expressions: The columns or calculations that you wish to retrieve. tables: The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions: These are optional conditions that must be met for the records to be selected. ORDER BY expression: These are optional statements used to return the result in ascending or descending order. LIMIT row_count_number: Specifies a limited number of rows to be returned based on row_count_number. Let’s understand this syntax using an example. Say we have a relation, Student. Create a database in MySQL: Query: -- create CREATE TABLE Student ( Id INTEGER PRIMARY KEY, name TEXT NOT NULL, score Number NOT NULL, branch TEXT ); Insert data into a table: Query: -- insert INSERT INTO Student VALUES (55, 'Bhargavi', '81','civil'); INSERT INTO Student VALUES (56, 'Nikita', '75','IT'); INSERT INTO Student VALUES (57, 'Riddhi', '100','CSE'); INSERT INTO Student VALUES (58, 'Shreya', '94','civil'); Output: Query: SELECT * FROM Student ORDER BY Score DESC LIMIT 2; Output: The LIMIT operator can be used in situations such as the above, where we need to find the top 2 students having maximum scores and do not want to use any conditional statements. ORDER BY Score DESC has sorted the record in descending order and using LIMIT 2 we got the first 2 rows from the sorted results. We can also include some situations using the WHERE clause in the above example. Suppose if we don’t want the Civil branch in our result set and want the first 2 students to have low Scores. We can write queries like : Query: SELECT * FROM Student WHERE Branch != 'Civil' ORDER BY Score LIMIT 2; Output: The above query will select all the students according to the imposed condition (i.e. all students except Civil branch students will be selected) then the results would be sorted by Score in ascending order (The ORDER BY keyword sorts the records in ascending order by default). Finally, the first 2 rows would be returned by the above query. Blogathon-2021 mysql Picked Blogathon DBMS How To SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date How to Install Tkinter in Windows? How to Create a Table With Multiple Foreign Keys in SQL? SQL Query to Create Table With a Primary Key SQL | Join (Inner, Left, Right and Full Joins) ACID Properties in DBMS SQL | WITH clause Normal Forms in DBMS SQL query to find second highest salary?
[ { "code": null, "e": 24836, "s": 24808, "text": "\n13 Sep, 2021" }, { "code": null, "e": 25087, "s": 24836, "text": "In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers." }, { "code": null, "e": 25095, "s": 25087, "text": "Syntax:" }, { "code": null, "e": 25124, "s": 25095, "text": "SELECT column1, column2, ..." }, { "code": null, "e": 25140, "s": 25124, "text": "FROM table_name" }, { "code": null, "e": 25161, "s": 25140, "text": "LIMIT offset, count;" }, { "code": null, "e": 25438, "s": 25161, "text": "The Limit clause accepts one or two parameters, whenever two parameters are specified, the first is the offset and the second denotes the count whereas whenever only one parameter is specified, it denotes the number of rows to be returned from the beginning of the result set." }, { "code": null, "e": 25512, "s": 25438, "text": "Offset: It is used to specify the offset of the first row to be returned." }, { "code": null, "e": 25584, "s": 25512, "text": "Count: It is used to specify the maximum number of rows to be returned." }, { "code": null, "e": 25592, "s": 25584, "text": "Syntax:" }, { "code": null, "e": 25611, "s": 25592, "text": "SELECT expressions" }, { "code": null, "e": 25623, "s": 25611, "text": "FROM tables" }, { "code": null, "e": 25642, "s": 25623, "text": "[WHERE conditions]" }, { "code": null, "e": 25679, "s": 25642, "text": "[ORDER BY expression [ ASC | DESC ]]" }, { "code": null, "e": 25703, "s": 25679, "text": "LIMIT row_count_number;" }, { "code": null, "e": 25771, "s": 25703, "text": "expressions: The columns or calculations that you wish to retrieve." }, { "code": null, "e": 25890, "s": 25771, "text": "tables: The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause." }, { "code": null, "e": 25988, "s": 25890, "text": "WHERE conditions: These are optional conditions that must be met for the records to be selected." }, { "code": null, "e": 26099, "s": 25988, "text": "ORDER BY expression: These are optional statements used to return the result in ascending or descending order." }, { "code": null, "e": 26200, "s": 26099, "text": "LIMIT row_count_number: Specifies a limited number of rows to be returned based on row_count_number." }, { "code": null, "e": 26282, "s": 26202, "text": "Let’s understand this syntax using an example. Say we have a relation, Student." }, { "code": null, "e": 26310, "s": 26282, "text": "Create a database in MySQL:" }, { "code": null, "e": 26317, "s": 26310, "text": "Query:" }, { "code": null, "e": 26441, "s": 26317, "text": "-- create\nCREATE TABLE Student (\n Id INTEGER PRIMARY KEY,\n name TEXT NOT NULL,\n score Number NOT NULL,\n branch TEXT \n);" }, { "code": null, "e": 26467, "s": 26441, "text": "Insert data into a table:" }, { "code": null, "e": 26474, "s": 26467, "text": "Query:" }, { "code": null, "e": 26710, "s": 26474, "text": "-- insert\nINSERT INTO Student VALUES (55, 'Bhargavi', '81','civil');\nINSERT INTO Student VALUES (56, 'Nikita', '75','IT');\nINSERT INTO Student VALUES (57, 'Riddhi', '100','CSE');\nINSERT INTO Student VALUES (58, 'Shreya', '94','civil');" }, { "code": null, "e": 26718, "s": 26710, "text": "Output:" }, { "code": null, "e": 26725, "s": 26718, "text": "Query:" }, { "code": null, "e": 26776, "s": 26725, "text": "SELECT * FROM Student ORDER BY Score DESC LIMIT 2;" }, { "code": null, "e": 26784, "s": 26776, "text": "Output:" }, { "code": null, "e": 27091, "s": 26784, "text": "The LIMIT operator can be used in situations such as the above, where we need to find the top 2 students having maximum scores and do not want to use any conditional statements. ORDER BY Score DESC has sorted the record in descending order and using LIMIT 2 we got the first 2 rows from the sorted results." }, { "code": null, "e": 27282, "s": 27091, "text": "We can also include some situations using the WHERE clause in the above example. Suppose if we don’t want the Civil branch in our result set and want the first 2 students to have low Scores." }, { "code": null, "e": 27310, "s": 27282, "text": "We can write queries like :" }, { "code": null, "e": 27317, "s": 27310, "text": "Query:" }, { "code": null, "e": 27388, "s": 27317, "text": "SELECT * FROM Student WHERE Branch != 'Civil' ORDER BY Score LIMIT 2;" }, { "code": null, "e": 27396, "s": 27388, "text": "Output:" }, { "code": null, "e": 27739, "s": 27396, "text": "The above query will select all the students according to the imposed condition (i.e. all students except Civil branch students will be selected) then the results would be sorted by Score in ascending order (The ORDER BY keyword sorts the records in ascending order by default). Finally, the first 2 rows would be returned by the above query." }, { "code": null, "e": 27754, "s": 27739, "text": "Blogathon-2021" }, { "code": null, "e": 27760, "s": 27754, "text": "mysql" }, { "code": null, "e": 27767, "s": 27760, "text": "Picked" }, { "code": null, "e": 27777, "s": 27767, "text": "Blogathon" }, { "code": null, "e": 27782, "s": 27777, "text": "DBMS" }, { "code": null, "e": 27789, "s": 27782, "text": "How To" }, { "code": null, "e": 27793, "s": 27789, "text": "SQL" }, { "code": null, "e": 27798, "s": 27793, "text": "DBMS" }, { "code": null, "e": 27802, "s": 27798, "text": "SQL" }, { "code": null, "e": 27900, "s": 27802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27909, "s": 27900, "text": "Comments" }, { "code": null, "e": 27922, "s": 27909, "text": "Old Comments" }, { "code": null, "e": 27963, "s": 27922, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 28001, "s": 27963, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 28036, "s": 28001, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 28093, "s": 28036, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28138, "s": 28093, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 28185, "s": 28138, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 28209, "s": 28185, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28227, "s": 28209, "text": "SQL | WITH clause" }, { "code": null, "e": 28248, "s": 28227, "text": "Normal Forms in DBMS" } ]
How to use null value as key in Java HashMap
Yes, you can set null as key in Java HashMap. For this, let’s first create a HashMap with key and value pair − Map<String,String>map = new HashMap<>(); map.put("Football", "A"); map.put("Squash", "B"); map.put("Cricket", "C"); map.put("Hockey", "D"); map.put("Rugby", "E"); Now, let’s add null value as key − map.put(null, "H"); You can try to get the value for key as “null” − map.get(null); Live Demo import java.util.HashMap; import java.util.Map; public class Demo { public static final void main(String[] args) { Map<String,String>map = new HashMap<>(); map.put("Football", "A"); map.put("Squash", "B"); map.put("Cricket", "C"); map.put("Hockey", "D"); map.put("Rugby", "E"); map.put("Golf", "F"); map.put("Archery", "G"); System.out.println("Size of HashMap = " + map.size()); map.put(null, "H"); System.out.println("Updated Size of HashMap = " + map.size()); System.out.println("For null = " + map.get(null)); } } Size of HashMap = 7 Updated Size of HashMap = 8 For null = H
[ { "code": null, "e": 1173, "s": 1062, "text": "Yes, you can set null as key in Java HashMap. For this, let’s first create a HashMap with key and value pair −" }, { "code": null, "e": 1336, "s": 1173, "text": "Map<String,String>map = new HashMap<>();\nmap.put(\"Football\", \"A\");\nmap.put(\"Squash\", \"B\");\nmap.put(\"Cricket\", \"C\");\nmap.put(\"Hockey\", \"D\");\nmap.put(\"Rugby\", \"E\");" }, { "code": null, "e": 1371, "s": 1336, "text": "Now, let’s add null value as key −" }, { "code": null, "e": 1391, "s": 1371, "text": "map.put(null, \"H\");" }, { "code": null, "e": 1440, "s": 1391, "text": "You can try to get the value for key as “null” −" }, { "code": null, "e": 1455, "s": 1440, "text": "map.get(null);" }, { "code": null, "e": 1466, "s": 1455, "text": " Live Demo" }, { "code": null, "e": 2062, "s": 1466, "text": "import java.util.HashMap;\nimport java.util.Map;\npublic class Demo {\n public static final void main(String[] args) {\n Map<String,String>map = new HashMap<>();\n map.put(\"Football\", \"A\");\n map.put(\"Squash\", \"B\");\n map.put(\"Cricket\", \"C\");\n map.put(\"Hockey\", \"D\");\n map.put(\"Rugby\", \"E\");\n map.put(\"Golf\", \"F\");\n map.put(\"Archery\", \"G\");\n System.out.println(\"Size of HashMap = \" + map.size());\n map.put(null, \"H\");\n System.out.println(\"Updated Size of HashMap = \" + map.size());\n System.out.println(\"For null = \" + map.get(null));\n }\n}" }, { "code": null, "e": 2123, "s": 2062, "text": "Size of HashMap = 7\nUpdated Size of HashMap = 8\nFor null = H" } ]
Jackson Annotations - @JsonSubTypes
@JsonSubTypes is used to indicate subtypes of types annotated. import java.io.IOException; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]) throws IOException{ Shape shape = new JacksonTester.Circle("CustomCircle", 1); String result = new ObjectMapper() .writerWithDefaultPrettyPrinter() .writeValueAsString(shape); System.out.println(result); String json = "{\"name\":\"CustomCircle\",\"radius\":1.0, \"type\":\"circle\"}"; Circle circle = new ObjectMapper().readerFor(Shape.class).readValue(json); System.out.println(circle.name); } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Square.class, name = "square"), @JsonSubTypes.Type(value = Circle.class, name = "circle") }) static class Shape { public String name; Shape(String name) { this.name = name; } } @JsonTypeName("square") static class Square extends Shape { public double length; Square(){ this(null,0.0); } Square(String name, double length){ super(name); this.length = length; } } @JsonTypeName("circle") static class Circle extends Shape { public double radius; Circle(){ this(null,0.0); } Circle(String name, double radius){ super(name); this.radius = radius; } } } { "type" : "circle", "name" : "CustomCircle", "radius" : 1.0 } CustomCircle Print Add Notes Bookmark this page
[ { "code": null, "e": 2538, "s": 2475, "text": "@JsonSubTypes is used to indicate subtypes of types annotated." }, { "code": null, "e": 4250, "s": 2538, "text": "import java.io.IOException;\n\nimport com.fasterxml.jackson.annotation.JsonSubTypes;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo.As;\nimport com.fasterxml.jackson.annotation.JsonTypeName;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]) throws IOException{\n Shape shape = new JacksonTester.Circle(\"CustomCircle\", 1);\n String result = new ObjectMapper()\n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(shape);\n System.out.println(result); \n String json = \"{\\\"name\\\":\\\"CustomCircle\\\",\\\"radius\\\":1.0, \\\"type\\\":\\\"circle\\\"}\";\n Circle circle = new ObjectMapper().readerFor(Shape.class).readValue(json);\n System.out.println(circle.name);\n }\n @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, \n include = As.PROPERTY, property = \"type\") @JsonSubTypes({\n \n @JsonSubTypes.Type(value = Square.class, name = \"square\"),\n @JsonSubTypes.Type(value = Circle.class, name = \"circle\")\n })\n static class Shape {\n public String name; \n Shape(String name) {\n this.name = name;\n }\n }\n @JsonTypeName(\"square\")\n static class Square extends Shape {\n public double length;\n Square(){\n this(null,0.0);\n }\n Square(String name, double length){\n super(name);\n this.length = length;\n }\n }\n @JsonTypeName(\"circle\")\n static class Circle extends Shape {\n public double radius; \n Circle(){\n this(null,0.0);\n }\n Circle(String name, double radius){\n super(name);\n this.radius = radius;\n }\n } \n}" }, { "code": null, "e": 4336, "s": 4250, "text": "{\n \"type\" : \"circle\",\n \"name\" : \"CustomCircle\",\n \"radius\" : 1.0\n}\nCustomCircle\n" }, { "code": null, "e": 4343, "s": 4336, "text": " Print" }, { "code": null, "e": 4354, "s": 4343, "text": " Add Notes" } ]
How to Set the Default Text of Tkinter Entry Widget? - GeeksforGeeks
11 Dec, 2020 The Tkinter Entry widget does not have any text attribute that can be used to set the default text. Therefore, default text must be added to any text field in Tkinter using the following methods: Insert method stringvar method Method 1: Using the insert method The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . Next a Entry widget ‘textBox ‘ is created on the root widget. The insert() method is called on the Entry widget. The insert() method takes two arguments. The first argument is the position of the string and the second argument is the text itself. Since the text must be there by default in the Entry widget, the position of the text is set to 0. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application. Below is the implementation: Python3 import tkinter as tk root = tk.Tk()root.geometry("200x100") textBox = tk.Entry(root)textBox.insert(0, "This is the default text")textBox.pack()root.mainloop() Output Method 2: Using the stringvar method The second method to add a default text to the Entry widget in Tkinter is the StringVar() method. The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . A text variable is a string variable and is its value is set to the default text. Next, an Entry widget ‘textBox ‘ is created on the root widget. The textvariable attribute of the Entry widget is assigned the value of the text variable. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application. Below is the implementation: Python3 import tkinter as tk root = tk.Tk()root.geometry("200x100") text = tk.StringVar()text.set("This is the default text")textBox = tk.Entry(root,textvariable = text) textBox.pack() root.mainloop() Output Python-tkinter Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n11 Dec, 2020" }, { "code": null, "e": 24489, "s": 24292, "text": "The Tkinter Entry widget does not have any text attribute that can be used to set the default text. Therefore, default text must be added to any text field in Tkinter using the following methods:" }, { "code": null, "e": 24503, "s": 24489, "text": "Insert method" }, { "code": null, "e": 24520, "s": 24503, "text": "stringvar method" }, { "code": null, "e": 24554, "s": 24520, "text": "Method 1: Using the insert method" }, { "code": null, "e": 25218, "s": 24554, "text": "The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . Next a Entry widget ‘textBox ‘ is created on the root widget. The insert() method is called on the Entry widget. The insert() method takes two arguments. The first argument is the position of the string and the second argument is the text itself. Since the text must be there by default in the Entry widget, the position of the text is set to 0. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application." }, { "code": null, "e": 25247, "s": 25218, "text": "Below is the implementation:" }, { "code": null, "e": 25255, "s": 25247, "text": "Python3" }, { "code": "import tkinter as tk root = tk.Tk()root.geometry(\"200x100\") textBox = tk.Entry(root)textBox.insert(0, \"This is the default text\")textBox.pack()root.mainloop()", "e": 25418, "s": 25255, "text": null }, { "code": null, "e": 25425, "s": 25418, "text": "Output" }, { "code": null, "e": 25462, "s": 25425, "text": "Method 2: Using the stringvar method" }, { "code": null, "e": 26115, "s": 25462, "text": "The second method to add a default text to the Entry widget in Tkinter is the StringVar() method. The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . A text variable is a string variable and is its value is set to the default text. Next, an Entry widget ‘textBox ‘ is created on the root widget. The textvariable attribute of the Entry widget is assigned the value of the text variable. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application." }, { "code": null, "e": 26144, "s": 26115, "text": "Below is the implementation:" }, { "code": null, "e": 26152, "s": 26144, "text": "Python3" }, { "code": "import tkinter as tk root = tk.Tk()root.geometry(\"200x100\") text = tk.StringVar()text.set(\"This is the default text\")textBox = tk.Entry(root,textvariable = text) textBox.pack() root.mainloop()", "e": 26351, "s": 26152, "text": null }, { "code": null, "e": 26358, "s": 26351, "text": "Output" }, { "code": null, "e": 26373, "s": 26358, "text": "Python-tkinter" }, { "code": null, "e": 26397, "s": 26373, "text": "Technical Scripter 2020" }, { "code": null, "e": 26404, "s": 26397, "text": "Python" }, { "code": null, "e": 26423, "s": 26404, "text": "Technical Scripter" }, { "code": null, "e": 26521, "s": 26423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26553, "s": 26521, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26595, "s": 26553, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26651, "s": 26595, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26693, "s": 26651, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26748, "s": 26693, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26779, "s": 26748, "text": "Python | os.path.join() method" }, { "code": null, "e": 26801, "s": 26779, "text": "Defaultdict in Python" }, { "code": null, "e": 26830, "s": 26801, "text": "Create a directory in Python" }, { "code": null, "e": 26869, "s": 26830, "text": "Python | Get unique values from a list" } ]
flag.Bool() Function in Golang With Examples - GeeksforGeeks
19 May, 2020 Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string. Syntax: func Bool(name string, value bool, usage string) *bool Parameters: This function accepts three parameters as mentioned above and described below: name: It is a string that specifies the name to be used for the flag. value: It is a boolean value that specifies the default value to be used by the flag. usage: It is a string that specifies the usage or help message to be shown for the flag. Return Value: It returns an address of the boolean variable that stores the value of the flag defined. Below programs illustrate the flag.Bool() function: Example 1: // Golang program to illustrate// the flag.Bool() Functionpackage main import ( "flag" "fmt") func main() { // Define a bool flag boolArgPtr := flag.Bool("arg1", false, "This is a bool argument") // Parse command line // into the defined flags flag.Parse() fmt.Println("Bool Arg:", *boolArgPtr)} Output: Specifying the flag value$ go run ex1.go -arg1=true Bool Arg: true $ go run ex1.go -arg1=true Bool Arg: true Not specifying the flag value (Default Value)$ go run ex1.go Bool Arg: false $ go run ex1.go Bool Arg: false Example 2: // Golang program to illustrate// the flag.Bool() Functionpackage main import ( "flag" "fmt") func main() { // Define multiple bool arguments plainArgPtr := flag.Bool("plaintext", false, "Enable plaintext") jsonArgPtr := flag.Bool("json", false, "Enable JSON") csvArgPtr := flag.Bool("csv", false, "Enable CSV") // Parse command line into the defined flags flag.Parse() fmt.Println("Enable plaintext:", *plainArgPtr) fmt.Println("Enable JSON:", *jsonArgPtr) fmt.Println("Enable CSV:", *csvArgPtr)} Output Specifying some flag values$ go run ex2.go -plaintext=true -csv=true Enable plaintext: true Enable JSON: false Enable CSV: true $ go run ex2.go -plaintext=true -csv=true Enable plaintext: true Enable JSON: false Enable CSV: true Not specifying any flag value (Default Values)$ go run ex2.go Enable plaintext: false Enable JSON: false Enable CSV: false $ go run ex2.go Enable plaintext: false Enable JSON: false Enable CSV: false Golang-Misc Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Parse JSON in Golang? Defer Keyword in Golang Time Durations in Golang Loops in Go Language time.Parse() Function in Golang With Examples Anonymous function in Go Language Strings in Golang Class and Object in Golang How to iterate over an Array using for loop in Golang? Structures in Golang
[ { "code": null, "e": 24460, "s": 24432, "text": "\n19 May, 2020" }, { "code": null, "e": 24782, "s": 24460, "text": "Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string." }, { "code": null, "e": 24790, "s": 24782, "text": "Syntax:" }, { "code": null, "e": 24845, "s": 24790, "text": "func Bool(name string, value bool, usage string) *bool" }, { "code": null, "e": 24936, "s": 24845, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 25006, "s": 24936, "text": "name: It is a string that specifies the name to be used for the flag." }, { "code": null, "e": 25092, "s": 25006, "text": "value: It is a boolean value that specifies the default value to be used by the flag." }, { "code": null, "e": 25181, "s": 25092, "text": "usage: It is a string that specifies the usage or help message to be shown for the flag." }, { "code": null, "e": 25284, "s": 25181, "text": "Return Value: It returns an address of the boolean variable that stores the value of the flag defined." }, { "code": null, "e": 25336, "s": 25284, "text": "Below programs illustrate the flag.Bool() function:" }, { "code": null, "e": 25347, "s": 25336, "text": "Example 1:" }, { "code": "// Golang program to illustrate// the flag.Bool() Functionpackage main import ( \"flag\" \"fmt\") func main() { // Define a bool flag boolArgPtr := flag.Bool(\"arg1\", false, \"This is a bool argument\") // Parse command line // into the defined flags flag.Parse() fmt.Println(\"Bool Arg:\", *boolArgPtr)}", "e": 25674, "s": 25347, "text": null }, { "code": null, "e": 25682, "s": 25674, "text": "Output:" }, { "code": null, "e": 25749, "s": 25682, "text": "Specifying the flag value$ go run ex1.go -arg1=true\nBool Arg: true" }, { "code": null, "e": 25791, "s": 25749, "text": "$ go run ex1.go -arg1=true\nBool Arg: true" }, { "code": null, "e": 25869, "s": 25791, "text": "Not specifying the flag value (Default Value)$ go run ex1.go\nBool Arg: false\n" }, { "code": null, "e": 25902, "s": 25869, "text": "$ go run ex1.go\nBool Arg: false\n" }, { "code": null, "e": 25913, "s": 25902, "text": "Example 2:" }, { "code": "// Golang program to illustrate// the flag.Bool() Functionpackage main import ( \"flag\" \"fmt\") func main() { // Define multiple bool arguments plainArgPtr := flag.Bool(\"plaintext\", false, \"Enable plaintext\") jsonArgPtr := flag.Bool(\"json\", false, \"Enable JSON\") csvArgPtr := flag.Bool(\"csv\", false, \"Enable CSV\") // Parse command line into the defined flags flag.Parse() fmt.Println(\"Enable plaintext:\", *plainArgPtr) fmt.Println(\"Enable JSON:\", *jsonArgPtr) fmt.Println(\"Enable CSV:\", *csvArgPtr)}", "e": 26452, "s": 25913, "text": null }, { "code": null, "e": 26459, "s": 26452, "text": "Output" }, { "code": null, "e": 26588, "s": 26459, "text": "Specifying some flag values$ go run ex2.go -plaintext=true -csv=true\nEnable plaintext: true\nEnable JSON: false\nEnable CSV: true\n" }, { "code": null, "e": 26690, "s": 26588, "text": "$ go run ex2.go -plaintext=true -csv=true\nEnable plaintext: true\nEnable JSON: false\nEnable CSV: true\n" }, { "code": null, "e": 26814, "s": 26690, "text": "Not specifying any flag value (Default Values)$ go run ex2.go\nEnable plaintext: false\nEnable JSON: false\nEnable CSV: false\n" }, { "code": null, "e": 26892, "s": 26814, "text": "$ go run ex2.go\nEnable plaintext: false\nEnable JSON: false\nEnable CSV: false\n" }, { "code": null, "e": 26904, "s": 26892, "text": "Golang-Misc" }, { "code": null, "e": 26916, "s": 26904, "text": "Go Language" }, { "code": null, "e": 27014, "s": 26916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27023, "s": 27014, "text": "Comments" }, { "code": null, "e": 27036, "s": 27023, "text": "Old Comments" }, { "code": null, "e": 27065, "s": 27036, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 27089, "s": 27065, "text": "Defer Keyword in Golang" }, { "code": null, "e": 27114, "s": 27089, "text": "Time Durations in Golang" }, { "code": null, "e": 27135, "s": 27114, "text": "Loops in Go Language" }, { "code": null, "e": 27181, "s": 27135, "text": "time.Parse() Function in Golang With Examples" }, { "code": null, "e": 27215, "s": 27181, "text": "Anonymous function in Go Language" }, { "code": null, "e": 27233, "s": 27215, "text": "Strings in Golang" }, { "code": null, "e": 27260, "s": 27233, "text": "Class and Object in Golang" }, { "code": null, "e": 27315, "s": 27260, "text": "How to iterate over an Array using for loop in Golang?" } ]
Data science you need to know! A/B testing | by Michael Barber | Towards Data Science
This is part 2 of a 5-part series of posts aiming to quickly introduce some core concepts in data science and data analysis, with a specific focus on areas that I feel are overlooked or treated briefly in other materials. This post outlines A/B testing, and the steps necessary to plan and build your own robust A/B test. This post will suit data scientists working in product development, and product managers hoping to communicate better with their data scientists. The humble A/B test (also known as a randomised controlled trial, or RCT, in the other sciences) is a powerful tool for product development. As well as being perhaps the most accurate tool for estimating effect size (and therefore ROI), it is also able to provide us with causality, a very elusive thing in data science! With causality we can finally lay to rest the “correlation vs causation” argument, and prove that our new product actually works. Imagine that you are CEO of Amazon, and trying to work out whether rearranging your website into a new format affects conversion rate (i.e. the proportion of visitors to Amazon who become customers): One approach would be to run both versions to selected customers and and make a judgement based on these numbers alone: In this case we would conclude that Layout B is superior to Layout A. However, such a simple approach suffers from two possible errors that statistics students will be very familiar with: Type I error — or falsely concluding that your intervention was successful (which here might be falsely concluding that layout B is better than Layout A). Also known as a false positive result. Type II error — falsely concluding that your intervention was not successful. Also known as a false negative result. These errors derive from a problem we touched on in a previous post ; namely, trying to draw conclusions about a population (in this case, all Amazon customers) from a sample (in this case, the visitors who participated in our layout trial). An A/B test will enable us to accurately quantify our effect size and errors, and so calculate the probability that we have made a type I or type II error. I would argue that only once we understand the true effect size and robustness of our results, can we proceed to making business-impact decisions. To phrase this another way, we should only estimate the ROI (return on investment) of a new product once we understand our effect size and errors. This post will outline the design principles of A/B tests and how to ensure that a trial is effective and cost-efficient. We will be relying on the concepts introduced in our last post (statistical power and p-values), so feel free to jump back a post if these need refreshing. Once you understand A/B testing in data science you will also understand randomised trials, which are commonly used in: Medicine, to understand if a drug works or not Economics, to understand human behaviour Foreign aid and charitable work (the reputable ones at least), to understand which interventions are most effective at alleviating problems (health, poverty, etc) We might start thinking about an A/B test based on a question or idea from a colleague. For example, we might have a hunch that SMS reminders for loan repayments will reduce loan defaults. With a little bit of work we can take this question and turn it into a hypothesis and then an A/B test that will evaluate the exact gain (or lack of gain) that results from the new SMS system To do this, we first need to form our question as a hypothesis, we then need to work out our randomization strategy, sample size and finally our method of measurement. A hypothesis is a formal statement describing the relationship you want to test. A hypothesis must be a simple, clear and testable statement (more on test-ability below) that contrasts a control sample (e.g. Layout A) with a treatment sample (e.g. Layout B). To form a hypothesis, we re-phrase “does an SMS system improve repayment” into two statements, a null hypothesis and an alternative hypothesis: Null hypothesis (H0) : The null hypothesis usually states that there is no difference between treatment and control groups. (To put this another way, we’re saying our treatment outcome will be statistically similar to our control outcome ) Alternative hypothesis (H1): The alternative hypothesis states that there is a difference between treatment and control groups. (In other words, the treatment outcome will be statistically different to the control outcome) Notably, a hypothesis should include reference to the population under study (Amazon.com US visitors, London bank customers etc), the intervention (website layout A and B, targeted loan repayment SMS), the comparison group (what are comparing to), the outcome (what will you measure) and the time (at what point will you measure it). Population, Intervention, Comparison, Outcome, Time = PICOT. Remember PICOT when defining your hypotheses. To give an example of a well formed hypothesis from our Amazon example: Null hypothesis (H0): Amazon.com visitors that receive Layout B will not have higher end-of-visit conversion rates compares to visitors that receive Layout A Alternative hypothesis (H1): Amazon.com visitors that receive Layout B will have higher end-of-visit conversion rates compared to visitors that receive layout A Note that the above clearly states our PICOT: Population: individuals who have visited the Amazon.com site Intervention: new website layout (Layout B) Comparison: visitors receiving Layout A Outcome: Conversion rate Time: End of visit to Amazon.com We can contrast this with a weak hypothesis from an agricultural context, such as: H0: Banks with nicer colours will not effect loan repayment H1: Banks with nicer colours will effect loan repayment Why is this so bad? Take a moment to think before reading on. There is no clear definition of “nicer colours”, my nice and your nice might not match. This is an example of a poor intervention definition from PICOT What banks? Where, and what level? Do we mean bank branches, if so, are we studying all branches around the world or just those in Manchester city centre? This is a poor population specification How are we measuring this? Loan default rates, days past due, total branch losses? This is an example of outcome specification from PICOT. A strong hypothesis will hold the A/B test together and provide guidance on the design and analysis. You can see that the above hypothesis is useless for these tasks. Returning to our Amazon example, once we have a well formed hypothesis we can think about randomisation strategies. To extend our example from above, we could randomise our visitors in two ways: Randomly assign visitors to Layout A or B Allow visitors to opt-in to new layout betas What would be the difference between these two setups? Before we answer this question, let us examine the reasons why we randomize in an A/B test. Randomization in an A/B test serves two related purposes: Distributing co-variates evenlyEliminating statistical biasCo-variates are factors that might influence your outcome variable, for example, visitor geolocation, gender and risk-appetite. Note that some of these are observable and measurable (such as location and gender) and some of these are unobservable (such as risk appetite, which is difficult to measure).Statistical bias can occur when your sample is substantially different from your target population. In an A/B test we are assuming our sample is representative of our population, deviations from this assumption can lead us to an incorrect understanding of our population and generating conclusions that look robust but are actually invalid! Distributing co-variates evenly Eliminating statistical bias Co-variates are factors that might influence your outcome variable, for example, visitor geolocation, gender and risk-appetite. Note that some of these are observable and measurable (such as location and gender) and some of these are unobservable (such as risk appetite, which is difficult to measure). Statistical bias can occur when your sample is substantially different from your target population. In an A/B test we are assuming our sample is representative of our population, deviations from this assumption can lead us to an incorrect understanding of our population and generating conclusions that look robust but are actually invalid! Common forms of bias at this stage of A/B test design (which also effect our co-variate distributions) are: Randomization bias — bias due to poor randomization resulting in unbalanced Treatment/Control groups (e.g. Texan visitors are over-represented in our treatment visitors vs. our control visitors). This allows some co-variates (e.g. being Texan) to exert more influence in one group than another. Selection bias — bias would also result if we were to allow visitors to assign themselves to Treatment/Control groups. This is because there may be unobservable co-variates that are associated with a Treatment/Control choice. For example, visitors with more risk appetite and might select themselves into the beta testing group, and so our Treatment visitors might have both a treatment effect and a risk appetite effect Both of these will lead to what is called confounding bias, this means it will be difficult to untangle effects that are due to poor randomisation vs. effects that are due to the actual intervention. However, if each participant has an equal chance of being randomly assigned to a Treatment/Control group then randomization will be free of bias. This will result in both observable (e.g. location) and unobservable co-variates (such as risk appetite) being spread equally to Treatment and Control groups. It is this spreading of co-variates that allows us to understand causality. To revisit our example at the top of this section, our choice between two strategies: Randomly assign visitors to Layout A or BAllow visitors to opt-in to new layout tests Randomly assign visitors to Layout A or B Allow visitors to opt-in to new layout tests Which of these now seems like a better strategy from a statistical point of view? Whilst there might be logistical or organizational reasons why we can’t do the former strategy, it is certainly a more statistically robust trial. This is because we have complete control to assign visitors (and therefore co-variates) to each group. If we used strategy 2, allowing visitors to opt-in to new layouts, then there would likely be unobservable factors at play that might weaken our A/B test and confound effects from unobservable factors with our outcome variable. It is therefore important to select treatment and control groups totally randomly, the best way to achieve this is by letting R do the work for you. I have included a function below that will do this for you. Please note the use of the set.seed function — we will be using random numbers to assign our participants to Treatment/Control status and so set.seed will make this randomness reproducible. Let’s now look at the function to assign Treatment/Control status, which I have here called RCT_random: #lets first make up a fake list of IDS from 1 to 1000 and 1000 random variables drawn from a normal distributiondf = data.frame("ID"=seq(1,1000), "randomvariable"=rnorm(1000))#lets now make a function to do the work - you can copy paste this function into your own scripts# it needs to be given a dataframe and a list of naming options# Options might be "treatment" and "control", or if there are more than 2 options then it might be "Control", "treatment1", "treatment2", or just "LayoutA", "LayoutB"RCT_random = function(dataframey, values_to_add){ set.seed(111) dataframey$values_to_add[sample(1:nrow(dataframey), nrow(dataframey), FALSE)] <- rep(values_to_add) colnames(dataframey)[which(colnames(dataframey)=="values_to_add")] = "Status" return(dataframey) }# so this will take the dataframe called "df" and randomly assign each ROW to "Treatment" or "control"df_new = RCT_random(df, c("Treatment","Control")) We have now taken our original dataframe and randomly assigned Treatment and Control status to them with my function “RCT_random”: We should now double-check our randomization to ensure it has proceeded as expected, to do this we can look at the distributions of the most important key variables. It is also possible to run an appropriate hypothesis test to assess whether the distributions are different. For these hypothesis tests we will set our P-value threshold to 0.01 (and not the 0.05 that is commonly used), this is due to the multiple comparison problem that we will cover in another post. Let’s now look at the summary statistics for Treatment and Control groups and make sure that “randomvariable” is similar: They look pretty similar! So far so good, randomization has been successful. Let’s look at some examples of randomization strategies for below and try to decide whether they are proper or improper randomization: Participants are allowed to decide whether to be in a treatment or control groupAny participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control.Participants east of my office are assigned to control, participants west of my office are assigned to treatmentWe flip a coin to decide whether a participant is control or treatment Participants are allowed to decide whether to be in a treatment or control group Any participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control. Participants east of my office are assigned to control, participants west of my office are assigned to treatment We flip a coin to decide whether a participant is control or treatment Which of the above are truly randomized? Take a moment to think about this before continuing on to the suggested answers below. Participants are allowed to decide whether to be in a treatment or control group. This is not random, as participants may have a reason for choosing a group which would lead to self-selection biasAny participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control. Almost random, but not quite! The issue here is that there might be some unknown factor associated with national ID that influences our results. If we 100% knew that national IDs were made randomly then this would be fine, however as we cannot know that we should use an alternative methodParticipants east of my office are assigned to control, participants west of my office are assigned to treatment. This is a terrible idea, this will likely lead to confounding bias as there are likely to be geographical differences between participants east and westWe flip a coin to decide whether a participant is control or treatment, Heads means treatment, Tails means Control.This is the only truly random system, as it is based only on chance Participants are allowed to decide whether to be in a treatment or control group. This is not random, as participants may have a reason for choosing a group which would lead to self-selection bias Any participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control. Almost random, but not quite! The issue here is that there might be some unknown factor associated with national ID that influences our results. If we 100% knew that national IDs were made randomly then this would be fine, however as we cannot know that we should use an alternative method Participants east of my office are assigned to control, participants west of my office are assigned to treatment. This is a terrible idea, this will likely lead to confounding bias as there are likely to be geographical differences between participants east and west We flip a coin to decide whether a participant is control or treatment, Heads means treatment, Tails means Control.This is the only truly random system, as it is based only on chance Sometimes, we won’t be able to randomise at the individual level but we will still want to measure at that level. For example, if we were to randomly assess the impact of incentives for bank staff on customer loan repayment rates then it would not be possible to randomise at the customer levels (as these share banks and therefore bank staff) and we would instead need to randomise at the bank level whilst still measuring the customer level outcome (repayment rate). The process of randomizing at one level but measuring at another causes complications in our A/B test design. Specifically, the inherent similarity of customers sharing a bank (in the above example) will lead us to have narrower distributions and under-estimate our errors. This, in turn, will have knock on effects for our study power and our study results (i.e. we’ll have a higher rate of false positives due to false confidence in our data). The concept that individuals treated in groups will behave similarly is known as clustering and our solution is to use a cluster randomized trial or cluster A/B test. A cluster randomized trial is similar to an A/B test but our unit of randomization becomes the cluster rather than the individual (so in the above example, the bank is the cluster). We can measure clustering with the intra-cluster correlation or ICC which will tell us how correlated the responses of individuals within a cluster are. ICC runs from 0 (no correlation between members of the same cluster) to 1.0 (complete correlation). A higher correlation causes more analysis headaches, so we want this to be 0! ICC can cause our distributions to seem narrower than they really are, this, in turn, will have knock-on effects on our statistical power, coefficients, confidence intervals and p-values. It essentially leads to a false confidence in our results. You should be able to rationalize why under-estimating our errors would lead to these effects using the concepts outlined in a previous post. It is possible to calculate the ICC before a trial using historical data. This estimated ICC will enable you to adjust your methods as necessary to produce a robust trial. Let’s first look at how we can calculate ICCs: # make some fake data#this data will have an ID number, variableA (our variable of interest), the bank name and the district namedf = data.frame(ID=seq(1,100), variableA=rnorm(100,500,50), bank_name=c("first_bank","second_bank","third_bank","last_bank"), District=c("A","B"))library(knitr)kable(df[1:5,], format="markdown", align="c") We can calculate the ICC using the snippet of code below: ICC_CI <- function(cluster_level,outcomevar, dataf){ #load libraryrequire(ICC) set.seed(123) si = round(dim(dataf)[1]*0.66) values_f <- c() for(i in seq(1:50)){ samp_f = dataf[sample(nrow(dataf), si), ] x_f = ICCbare(cluster_level,outcomevar,samp_f) values_f <- c(values_f, x_f) } # note that 1.96StDevs = 95% confidence interval bounds in a normal dist. ret = data.frame("Mean ICC" = round(mean(values_f, na.rm=TRUE),3), "CI" = round(1.96*sd(values_f, na.rm=TRUE),3)) ret$Significant = ifelse(ret$Mean.ICC > ret$CI, "Y", "N") return( ret) }stored_ICC <- ICC_CI("bank_name", "variableA", df) We can see from this calculation that our ICC between customers in the same bank is (0.022 +/- 0.081). As the confidence intervals (CI) cross zero we can see that this is not significant (hence “Significant = N”). In other words, it appears that banks account for a negligible amount of similarity between customers. However, if we have a significant ICC then we will need to adjust our trial design and analysis plans to mitigate ICC effects. We generally have two options here: Option 1: Calculate a summary metric for each cluster (e.g. cluster mean). Each cluster then provides only one data point and allows us to continue with the assumption that our data is independent, we can then proceed with standard statistical tools (e.g. T-test) as normal. So if we have 500 individuals in 45 groups, we end up with 45 data points. This means that our power, sample size and analysis calculations also need to be carried out at the cluster level. It also means that we can simply analyse our data at the cluster level and ignore ICC from here on out (as we essentially set ICC = 1.0 and proceed with this assumption). Use the ICC with the number of individuals to work out our new sample size. For option 2, we will continue to calculate power, sample size and analysis metrics at the individual level but with some corrections to account for the falsely narrow distributions. For our sample size, we will inflate it with the ICC_correction function below: ICC_correction <- function(samplesize, num_clusters, ICC_estimate){ average_cluster_size = samplesize/num_clusters factor_inflate = 1 + (average_cluster_size - 1) * ICC_estimate return(data.frame("New sample size"=round(samplesize*factor_inflate), "Old sample size"=samplesize ))}ICC_correction(200, 50, 0.2) So an initial sample size of 200 customers, with 30 clusters (banks) and an ICC of 0.2 would lead to a new sample size of 320. Note how a relatively small ICC increases our sample size by more than 50%. We can also explore the difference between adding new clusters vs new individuals in existing clusters. For example: scenario1 <- ICC_correction(200,20,0.2)$New.sample.size #average 10 farmers per cluster, and 20 clustersscenario2 <- ICC_correction(200,40,0.2)$New.sample.size # average 5 farmers per cluster, and 40 clusters `scenario1= 560 ` `scenario2= 360` We can see that doubling the number of clusters (but keeping the number of participants the same, so that customers are just spread out to more clusters) leads to a sizable reduction in corrected sample size. I’ve run a simulation below that will plot the relationship between adding new individuals (to existing clusters) vs adding new clusters and how this effects sample size (holding power constant at 0.8): In general, we can see that adding new clusters rather than new individuals to existing clusters, inflates our corrected sample size to a lesser extent (there is a link to this simulation code at the bottom of this post). By adding new clusters, we are minimising the amount of total variance explained by within-cluster variance, thus gaining information. Another intuitive explanation is that if I already have 10 individuals in a single cluster, and we have non-zero ICC, then every additional individual in that cluster provides less and less information and her characteristics are more and more predictable based on cluster averages. NB. In the next post, we will look at the actual analysis of ICC data with fixed and random effect modelling. Once we have a testable hypothesis and a randomization strategy, we will want to think about data analysis. Generally, we will test the effectiveness of an intervention with a hypothesis test. This hypothesis test will yield a p-value, which is the probability that our data could generated purely by chance — in other words, the probability that we wrongly reject H0 (a false positive result). When using a hypothesis test we must set an acceptable rate of false positives, aka a p-value threshold or alpha level. The most common p-value threshold is 0.05 (a pretty arbitrary number). This means that we are willing to accept a 5% risk of generating a false positive and wrongly concluding that there is a difference between our treatments when in fact there is not. We can demonstrate this below, if we randomly test two *samples* from identical *populations* then 5% of the time we will mistakenly identify the samples as being from different populations: In some cases we might want to set a threshold of 0.01 (1%) or 0.1 (10%). Generally speaking, the more unwilling we are to be incorrect, the lower the threshold. So for an intervention that might have adverse effects on customers, we would want to be very sure of the positive effects (0.01 threshold) and unwilling to accept negative effects (0.1 threshold). Note that the lower our threshold the larger the sample size needed to detect any effect. As always, full R code for these figures is available at the bottom of this post. Combining the materials from this post and post #1 gives us a good theoretical foundation for sample size calculations. However a common question I want to address here is: “where do I get the data from for a sample size calculation?”. We can use the Amazon layout trial example from above to understand how to answer this question. The main piece of information needed before a sample size calculation is an estimate of intervention effect size. There are generally two ways we can derive an effect size estimate for our calculations: Analyse historical data or pilot studies set a minimum detectable effect (MDE) The first of these involves literature review and/or a small pilot study to estimate the differences between treatment and control groups. Note that if you are using pilot data, then the estimate of effect size is likely to be very rough, so I recommend halving the effect size to be conservative and using that for calculations. If you are using literature values then again, treat them cautiously and consider any literature value to be an upper estimate of effect size (this is due to the Winner’s curse phenomenon which will be covered in a later post). Perhaps the most business-savvy approach to this question utilises MDEs. The MDE approach will ask “what is the minimum effect that I would need to see for the intervention to be worthwhile?”, we would then set the effect size to that value. The reasoning here is that if the return on investment (ROI) of a proposed intervention is negative (or very small) then we don’t need to be able to precisely measure such a small value to make a decision. For example, implementing Layout B across Amazon.com might be quite expensive. We could calculate that the implementation would cost approximately $20,000 of staff time, in which case we would only care about being able to detect effects greater than $20,000. For arguments sake, let’s say that $20,000 corresponds to a 2% point bump in conversion rate in the US market, we then set our MDE to 2 points and our effect size to 2 points for our calculations. The MDE approach can be very powerful. Use it wisely during both pre-analysis (to estimate sample size) and post-analysis to say what size effect we would have been able to detect with a power of 0.8. You can see a worked example below for pre-analysis MDE, I have also included a function plot_MDE which you can use on your own data. #make some fake data, let's pretend its baseline datadat <- data.frame("mean.client.expenditure" = rnorm(1000,100,10))#this function will plot MDE for various differences# differs is a list of intervention effects that you want to considerplot_MDE <- function(historical_data, differs){ #initialise empty vecp <- c()#remember our effect size function from post 1?cohen_d <- function(d1,d2) { m1 <- mean(d1, na.rm=TRUE) m2 <- mean(d2, na.rm=TRUE) s1 <- sd(d1, na.rm=TRUE) s2 <- sd(d2, na.rm=TRUE) spo <- sqrt((s1**2 + s2**2)/2) d <- (m1 - m2)/spo rpb <- d / sqrt((d**2)+4) ret <- list("rpb" = rpb, "effectsi" = d) return(ret) } #load libsrequire(pwr)for(i in seq(1:length(differs) ) ) { samp1 <- historical_data xnu = differs[[i]] #this is a better version if you can understand it: samp2 <- samp1 + rnorm(length(samp1), xnu, xnu/10) #add some noise inp <- cohen_d(samp1, samp2) p[i] <- pwr.2p.test(h=inp$effectsi , sig.level=0.05, power=0.8, n=NULL)$n }require(ggplot2)print(ggplot() + geom_point(aes(x=p, y= differs), size=3, color="blue", shape=1) + geom_line(aes(x=p, y=differs), size=1.2, color="blue") + xlab("Sample size")+ ylab("MDE") + ggtitle("Minimum detectable effect vs. sample size"))library(knitr)mde_tab = data.frame("MDE"=differs, "Sample size"=p)kable(mde_tab, digits=2) }#set some differences for the loop, here, 1,2,5 (etc) are dollar increasesdiffs <- c(1,2,5,7.5,10,15,20,25)#plotplot_MDE(dat$mean.client.expenditure, diffs) Note that this function will give you the Y-axis in whatever units you gave to the function (in this case, US dollars). You can use the MDE to calculate an initial sample size and then use the ICC correction to obtain the ICC-corrected sample size for that MDE. The final part of the A/B test is the measurement itself. This is often a neglected part of test design and therefore a major source of later analysis issues. Any hypothesis needs to have a good measurement strategy to be useful. I want to take a tangent to describe some analysis I did on an A/B test looking at airtime usage (aka phone credit) in Malawi for a telecommunication company to illustrate the pitfalls here. This A/B test examined the effect of a new product on airtime usage. During the A/B test, we asked people to recall how much money they had spent in the last month on airtime, and unbeknownst to them, we also had data from the telecommunications company on the actual amount spent by the same customers. When we compared the two metrics, we found there was very little correlation! Furthermore, when we looked at who was most likely to over-estimate their airtime spend, we found it was young, urban males. Now consider — had we only had the self-reported data, we would have thought that young urban men were big spenders on airtime, drawn many conclusions from this, and found many “statistically significant” (in terms of P-values of < 0.05) relationships! We would have made many recommendations to the telecommunications company about the new product, and our results would have held up to thorough statistical interrogation. In short — there would have been very little way to know we were wrong, but we would have been wrong nevertheless! The moral of this story is that the best statistics in the world will not save a trial from poor measurement. The other moral is that self-reported data is often terrible (beware survey-heavy NGOs!), as it is influenced by how people want to be perceived ( perhaps by the interviewer, by the community, or by their own embarrassment about “low” airtime spends). It is vital to spend some time thinking about the caveats and weaknesses of measurement strategies, and then to try to mitigate those weaknesses as much as possible (e.g. through obtaining corroborating data as above). Finally, once the data is collected and analysed, it’s important to make it accessible and reproducible. This means writing clean code (ideally in R-markdown or Jupyter notebook) and saving the raw data on company servers. Every data scientist in a company new to big data has witnessed the litany of random CSV files and analysis scripts strewn across dozens of employee hard-drives. A system for storing such files and scripts for possible future use is necessary, and deserves its own blog post entirely! If you liked this post, or found is useful, then please clap so I know! We have now seen the key parts of an A/B test: Hypothesis: A good hypothesis is testable and measurable. It must have a clearly defined evaluation criteria (e.g. are we measuring the average or the median? At the individual or group level?). Randomization: We must randomize using R and ensuring our Treatment and Control groups are balanced. We can use RCT_random function to achieve this. We should also account for cluster effects and use the correct unit of randomization. It is possible to calculate the ICC and adjust sample size accordingly, it is also fair to assume an ICC of 1.0 and have the sample size calculated from the number of clusters Power: Know your statistical power, sample size and MDE before and after a trial (see previous post) Measurement: Measurements must be robust and reliable, think about the ways that we might be inaccurate and try to minimize the importance of self-reported metrics in any study you design! You can view a fuller version of this post (complete with all R code) on my GitHub Linear models, mixed-effect models, and more on hypothesis testing! Originally published at michael-bar.github.io.
[ { "code": null, "e": 269, "s": 47, "text": "This is part 2 of a 5-part series of posts aiming to quickly introduce some core concepts in data science and data analysis, with a specific focus on areas that I feel are overlooked or treated briefly in other materials." }, { "code": null, "e": 369, "s": 269, "text": "This post outlines A/B testing, and the steps necessary to plan and build your own robust A/B test." }, { "code": null, "e": 515, "s": 369, "text": "This post will suit data scientists working in product development, and product managers hoping to communicate better with their data scientists." }, { "code": null, "e": 656, "s": 515, "text": "The humble A/B test (also known as a randomised controlled trial, or RCT, in the other sciences) is a powerful tool for product development." }, { "code": null, "e": 966, "s": 656, "text": "As well as being perhaps the most accurate tool for estimating effect size (and therefore ROI), it is also able to provide us with causality, a very elusive thing in data science! With causality we can finally lay to rest the “correlation vs causation” argument, and prove that our new product actually works." }, { "code": null, "e": 1166, "s": 966, "text": "Imagine that you are CEO of Amazon, and trying to work out whether rearranging your website into a new format affects conversion rate (i.e. the proportion of visitors to Amazon who become customers):" }, { "code": null, "e": 1286, "s": 1166, "text": "One approach would be to run both versions to selected customers and and make a judgement based on these numbers alone:" }, { "code": null, "e": 1356, "s": 1286, "text": "In this case we would conclude that Layout B is superior to Layout A." }, { "code": null, "e": 1474, "s": 1356, "text": "However, such a simple approach suffers from two possible errors that statistics students will be very familiar with:" }, { "code": null, "e": 1668, "s": 1474, "text": "Type I error — or falsely concluding that your intervention was successful (which here might be falsely concluding that layout B is better than Layout A). Also known as a false positive result." }, { "code": null, "e": 1785, "s": 1668, "text": "Type II error — falsely concluding that your intervention was not successful. Also known as a false negative result." }, { "code": null, "e": 2027, "s": 1785, "text": "These errors derive from a problem we touched on in a previous post ; namely, trying to draw conclusions about a population (in this case, all Amazon customers) from a sample (in this case, the visitors who participated in our layout trial)." }, { "code": null, "e": 2183, "s": 2027, "text": "An A/B test will enable us to accurately quantify our effect size and errors, and so calculate the probability that we have made a type I or type II error." }, { "code": null, "e": 2477, "s": 2183, "text": "I would argue that only once we understand the true effect size and robustness of our results, can we proceed to making business-impact decisions. To phrase this another way, we should only estimate the ROI (return on investment) of a new product once we understand our effect size and errors." }, { "code": null, "e": 2755, "s": 2477, "text": "This post will outline the design principles of A/B tests and how to ensure that a trial is effective and cost-efficient. We will be relying on the concepts introduced in our last post (statistical power and p-values), so feel free to jump back a post if these need refreshing." }, { "code": null, "e": 2875, "s": 2755, "text": "Once you understand A/B testing in data science you will also understand randomised trials, which are commonly used in:" }, { "code": null, "e": 2922, "s": 2875, "text": "Medicine, to understand if a drug works or not" }, { "code": null, "e": 2963, "s": 2922, "text": "Economics, to understand human behaviour" }, { "code": null, "e": 3126, "s": 2963, "text": "Foreign aid and charitable work (the reputable ones at least), to understand which interventions are most effective at alleviating problems (health, poverty, etc)" }, { "code": null, "e": 3507, "s": 3126, "text": "We might start thinking about an A/B test based on a question or idea from a colleague. For example, we might have a hunch that SMS reminders for loan repayments will reduce loan defaults. With a little bit of work we can take this question and turn it into a hypothesis and then an A/B test that will evaluate the exact gain (or lack of gain) that results from the new SMS system" }, { "code": null, "e": 3675, "s": 3507, "text": "To do this, we first need to form our question as a hypothesis, we then need to work out our randomization strategy, sample size and finally our method of measurement." }, { "code": null, "e": 3934, "s": 3675, "text": "A hypothesis is a formal statement describing the relationship you want to test. A hypothesis must be a simple, clear and testable statement (more on test-ability below) that contrasts a control sample (e.g. Layout A) with a treatment sample (e.g. Layout B)." }, { "code": null, "e": 4078, "s": 3934, "text": "To form a hypothesis, we re-phrase “does an SMS system improve repayment” into two statements, a null hypothesis and an alternative hypothesis:" }, { "code": null, "e": 4318, "s": 4078, "text": "Null hypothesis (H0) : The null hypothesis usually states that there is no difference between treatment and control groups. (To put this another way, we’re saying our treatment outcome will be statistically similar to our control outcome )" }, { "code": null, "e": 4541, "s": 4318, "text": "Alternative hypothesis (H1): The alternative hypothesis states that there is a difference between treatment and control groups. (In other words, the treatment outcome will be statistically different to the control outcome)" }, { "code": null, "e": 4875, "s": 4541, "text": "Notably, a hypothesis should include reference to the population under study (Amazon.com US visitors, London bank customers etc), the intervention (website layout A and B, targeted loan repayment SMS), the comparison group (what are comparing to), the outcome (what will you measure) and the time (at what point will you measure it)." }, { "code": null, "e": 4982, "s": 4875, "text": "Population, Intervention, Comparison, Outcome, Time = PICOT. Remember PICOT when defining your hypotheses." }, { "code": null, "e": 5054, "s": 4982, "text": "To give an example of a well formed hypothesis from our Amazon example:" }, { "code": null, "e": 5212, "s": 5054, "text": "Null hypothesis (H0): Amazon.com visitors that receive Layout B will not have higher end-of-visit conversion rates compares to visitors that receive Layout A" }, { "code": null, "e": 5373, "s": 5212, "text": "Alternative hypothesis (H1): Amazon.com visitors that receive Layout B will have higher end-of-visit conversion rates compared to visitors that receive layout A" }, { "code": null, "e": 5419, "s": 5373, "text": "Note that the above clearly states our PICOT:" }, { "code": null, "e": 5480, "s": 5419, "text": "Population: individuals who have visited the Amazon.com site" }, { "code": null, "e": 5524, "s": 5480, "text": "Intervention: new website layout (Layout B)" }, { "code": null, "e": 5564, "s": 5524, "text": "Comparison: visitors receiving Layout A" }, { "code": null, "e": 5589, "s": 5564, "text": "Outcome: Conversion rate" }, { "code": null, "e": 5622, "s": 5589, "text": "Time: End of visit to Amazon.com" }, { "code": null, "e": 5705, "s": 5622, "text": "We can contrast this with a weak hypothesis from an agricultural context, such as:" }, { "code": null, "e": 5765, "s": 5705, "text": "H0: Banks with nicer colours will not effect loan repayment" }, { "code": null, "e": 5821, "s": 5765, "text": "H1: Banks with nicer colours will effect loan repayment" }, { "code": null, "e": 5883, "s": 5821, "text": "Why is this so bad? Take a moment to think before reading on." }, { "code": null, "e": 6035, "s": 5883, "text": "There is no clear definition of “nicer colours”, my nice and your nice might not match. This is an example of a poor intervention definition from PICOT" }, { "code": null, "e": 6230, "s": 6035, "text": "What banks? Where, and what level? Do we mean bank branches, if so, are we studying all branches around the world or just those in Manchester city centre? This is a poor population specification" }, { "code": null, "e": 6369, "s": 6230, "text": "How are we measuring this? Loan default rates, days past due, total branch losses? This is an example of outcome specification from PICOT." }, { "code": null, "e": 6536, "s": 6369, "text": "A strong hypothesis will hold the A/B test together and provide guidance on the design and analysis. You can see that the above hypothesis is useless for these tasks." }, { "code": null, "e": 6731, "s": 6536, "text": "Returning to our Amazon example, once we have a well formed hypothesis we can think about randomisation strategies. To extend our example from above, we could randomise our visitors in two ways:" }, { "code": null, "e": 6773, "s": 6731, "text": "Randomly assign visitors to Layout A or B" }, { "code": null, "e": 6818, "s": 6773, "text": "Allow visitors to opt-in to new layout betas" }, { "code": null, "e": 6965, "s": 6818, "text": "What would be the difference between these two setups? Before we answer this question, let us examine the reasons why we randomize in an A/B test." }, { "code": null, "e": 7023, "s": 6965, "text": "Randomization in an A/B test serves two related purposes:" }, { "code": null, "e": 7725, "s": 7023, "text": "Distributing co-variates evenlyEliminating statistical biasCo-variates are factors that might influence your outcome variable, for example, visitor geolocation, gender and risk-appetite. Note that some of these are observable and measurable (such as location and gender) and some of these are unobservable (such as risk appetite, which is difficult to measure).Statistical bias can occur when your sample is substantially different from your target population. In an A/B test we are assuming our sample is representative of our population, deviations from this assumption can lead us to an incorrect understanding of our population and generating conclusions that look robust but are actually invalid!" }, { "code": null, "e": 7757, "s": 7725, "text": "Distributing co-variates evenly" }, { "code": null, "e": 7786, "s": 7757, "text": "Eliminating statistical bias" }, { "code": null, "e": 8089, "s": 7786, "text": "Co-variates are factors that might influence your outcome variable, for example, visitor geolocation, gender and risk-appetite. Note that some of these are observable and measurable (such as location and gender) and some of these are unobservable (such as risk appetite, which is difficult to measure)." }, { "code": null, "e": 8430, "s": 8089, "text": "Statistical bias can occur when your sample is substantially different from your target population. In an A/B test we are assuming our sample is representative of our population, deviations from this assumption can lead us to an incorrect understanding of our population and generating conclusions that look robust but are actually invalid!" }, { "code": null, "e": 8538, "s": 8430, "text": "Common forms of bias at this stage of A/B test design (which also effect our co-variate distributions) are:" }, { "code": null, "e": 8833, "s": 8538, "text": "Randomization bias — bias due to poor randomization resulting in unbalanced Treatment/Control groups (e.g. Texan visitors are over-represented in our treatment visitors vs. our control visitors). This allows some co-variates (e.g. being Texan) to exert more influence in one group than another." }, { "code": null, "e": 9254, "s": 8833, "text": "Selection bias — bias would also result if we were to allow visitors to assign themselves to Treatment/Control groups. This is because there may be unobservable co-variates that are associated with a Treatment/Control choice. For example, visitors with more risk appetite and might select themselves into the beta testing group, and so our Treatment visitors might have both a treatment effect and a risk appetite effect" }, { "code": null, "e": 9454, "s": 9254, "text": "Both of these will lead to what is called confounding bias, this means it will be difficult to untangle effects that are due to poor randomisation vs. effects that are due to the actual intervention." }, { "code": null, "e": 9835, "s": 9454, "text": "However, if each participant has an equal chance of being randomly assigned to a Treatment/Control group then randomization will be free of bias. This will result in both observable (e.g. location) and unobservable co-variates (such as risk appetite) being spread equally to Treatment and Control groups. It is this spreading of co-variates that allows us to understand causality." }, { "code": null, "e": 9921, "s": 9835, "text": "To revisit our example at the top of this section, our choice between two strategies:" }, { "code": null, "e": 10007, "s": 9921, "text": "Randomly assign visitors to Layout A or BAllow visitors to opt-in to new layout tests" }, { "code": null, "e": 10049, "s": 10007, "text": "Randomly assign visitors to Layout A or B" }, { "code": null, "e": 10094, "s": 10049, "text": "Allow visitors to opt-in to new layout tests" }, { "code": null, "e": 10176, "s": 10094, "text": "Which of these now seems like a better strategy from a statistical point of view?" }, { "code": null, "e": 10654, "s": 10176, "text": "Whilst there might be logistical or organizational reasons why we can’t do the former strategy, it is certainly a more statistically robust trial. This is because we have complete control to assign visitors (and therefore co-variates) to each group. If we used strategy 2, allowing visitors to opt-in to new layouts, then there would likely be unobservable factors at play that might weaken our A/B test and confound effects from unobservable factors with our outcome variable." }, { "code": null, "e": 11053, "s": 10654, "text": "It is therefore important to select treatment and control groups totally randomly, the best way to achieve this is by letting R do the work for you. I have included a function below that will do this for you. Please note the use of the set.seed function — we will be using random numbers to assign our participants to Treatment/Control status and so set.seed will make this randomness reproducible." }, { "code": null, "e": 11157, "s": 11053, "text": "Let’s now look at the function to assign Treatment/Control status, which I have here called RCT_random:" }, { "code": null, "e": 12079, "s": 11157, "text": "#lets first make up a fake list of IDS from 1 to 1000 and 1000 random variables drawn from a normal distributiondf = data.frame(\"ID\"=seq(1,1000), \"randomvariable\"=rnorm(1000))#lets now make a function to do the work - you can copy paste this function into your own scripts# it needs to be given a dataframe and a list of naming options# Options might be \"treatment\" and \"control\", or if there are more than 2 options then it might be \"Control\", \"treatment1\", \"treatment2\", or just \"LayoutA\", \"LayoutB\"RCT_random = function(dataframey, values_to_add){ set.seed(111) dataframey$values_to_add[sample(1:nrow(dataframey), nrow(dataframey), FALSE)] <- rep(values_to_add) colnames(dataframey)[which(colnames(dataframey)==\"values_to_add\")] = \"Status\" return(dataframey) }# so this will take the dataframe called \"df\" and randomly assign each ROW to \"Treatment\" or \"control\"df_new = RCT_random(df, c(\"Treatment\",\"Control\"))" }, { "code": null, "e": 12120, "s": 12079, "text": "We have now taken our original dataframe" }, { "code": null, "e": 12210, "s": 12120, "text": "and randomly assigned Treatment and Control status to them with my function “RCT_random”:" }, { "code": null, "e": 12679, "s": 12210, "text": "We should now double-check our randomization to ensure it has proceeded as expected, to do this we can look at the distributions of the most important key variables. It is also possible to run an appropriate hypothesis test to assess whether the distributions are different. For these hypothesis tests we will set our P-value threshold to 0.01 (and not the 0.05 that is commonly used), this is due to the multiple comparison problem that we will cover in another post." }, { "code": null, "e": 12801, "s": 12679, "text": "Let’s now look at the summary statistics for Treatment and Control groups and make sure that “randomvariable” is similar:" }, { "code": null, "e": 12878, "s": 12801, "text": "They look pretty similar! So far so good, randomization has been successful." }, { "code": null, "e": 13013, "s": 12878, "text": "Let’s look at some examples of randomization strategies for below and try to decide whether they are proper or improper randomization:" }, { "code": null, "e": 13443, "s": 13013, "text": "Participants are allowed to decide whether to be in a treatment or control groupAny participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control.Participants east of my office are assigned to control, participants west of my office are assigned to treatmentWe flip a coin to decide whether a participant is control or treatment" }, { "code": null, "e": 13524, "s": 13443, "text": "Participants are allowed to decide whether to be in a treatment or control group" }, { "code": null, "e": 13692, "s": 13524, "text": "Any participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control." }, { "code": null, "e": 13805, "s": 13692, "text": "Participants east of my office are assigned to control, participants west of my office are assigned to treatment" }, { "code": null, "e": 13876, "s": 13805, "text": "We flip a coin to decide whether a participant is control or treatment" }, { "code": null, "e": 14004, "s": 13876, "text": "Which of the above are truly randomized? Take a moment to think about this before continuing on to the suggested answers below." }, { "code": null, "e": 15106, "s": 14004, "text": "Participants are allowed to decide whether to be in a treatment or control group. This is not random, as participants may have a reason for choosing a group which would lead to self-selection biasAny participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control. Almost random, but not quite! The issue here is that there might be some unknown factor associated with national ID that influences our results. If we 100% knew that national IDs were made randomly then this would be fine, however as we cannot know that we should use an alternative methodParticipants east of my office are assigned to control, participants west of my office are assigned to treatment. This is a terrible idea, this will likely lead to confounding bias as there are likely to be geographical differences between participants east and westWe flip a coin to decide whether a participant is control or treatment, Heads means treatment, Tails means Control.This is the only truly random system, as it is based only on chance" }, { "code": null, "e": 15303, "s": 15106, "text": "Participants are allowed to decide whether to be in a treatment or control group. This is not random, as participants may have a reason for choosing a group which would lead to self-selection bias" }, { "code": null, "e": 15761, "s": 15303, "text": "Any participant with a national ID number ending in an odd number is assigned to treatment, any participant with an ID ending in an even number is assigned to control. Almost random, but not quite! The issue here is that there might be some unknown factor associated with national ID that influences our results. If we 100% knew that national IDs were made randomly then this would be fine, however as we cannot know that we should use an alternative method" }, { "code": null, "e": 16028, "s": 15761, "text": "Participants east of my office are assigned to control, participants west of my office are assigned to treatment. This is a terrible idea, this will likely lead to confounding bias as there are likely to be geographical differences between participants east and west" }, { "code": null, "e": 16211, "s": 16028, "text": "We flip a coin to decide whether a participant is control or treatment, Heads means treatment, Tails means Control.This is the only truly random system, as it is based only on chance" }, { "code": null, "e": 16680, "s": 16211, "text": "Sometimes, we won’t be able to randomise at the individual level but we will still want to measure at that level. For example, if we were to randomly assess the impact of incentives for bank staff on customer loan repayment rates then it would not be possible to randomise at the customer levels (as these share banks and therefore bank staff) and we would instead need to randomise at the bank level whilst still measuring the customer level outcome (repayment rate)." }, { "code": null, "e": 17293, "s": 16680, "text": "The process of randomizing at one level but measuring at another causes complications in our A/B test design. Specifically, the inherent similarity of customers sharing a bank (in the above example) will lead us to have narrower distributions and under-estimate our errors. This, in turn, will have knock on effects for our study power and our study results (i.e. we’ll have a higher rate of false positives due to false confidence in our data). The concept that individuals treated in groups will behave similarly is known as clustering and our solution is to use a cluster randomized trial or cluster A/B test." }, { "code": null, "e": 17806, "s": 17293, "text": "A cluster randomized trial is similar to an A/B test but our unit of randomization becomes the cluster rather than the individual (so in the above example, the bank is the cluster). We can measure clustering with the intra-cluster correlation or ICC which will tell us how correlated the responses of individuals within a cluster are. ICC runs from 0 (no correlation between members of the same cluster) to 1.0 (complete correlation). A higher correlation causes more analysis headaches, so we want this to be 0!" }, { "code": null, "e": 18195, "s": 17806, "text": "ICC can cause our distributions to seem narrower than they really are, this, in turn, will have knock-on effects on our statistical power, coefficients, confidence intervals and p-values. It essentially leads to a false confidence in our results. You should be able to rationalize why under-estimating our errors would lead to these effects using the concepts outlined in a previous post." }, { "code": null, "e": 18367, "s": 18195, "text": "It is possible to calculate the ICC before a trial using historical data. This estimated ICC will enable you to adjust your methods as necessary to produce a robust trial." }, { "code": null, "e": 18414, "s": 18367, "text": "Let’s first look at how we can calculate ICCs:" }, { "code": null, "e": 18750, "s": 18414, "text": "# make some fake data#this data will have an ID number, variableA (our variable of interest), the bank name and the district namedf = data.frame(ID=seq(1,100), variableA=rnorm(100,500,50), bank_name=c(\"first_bank\",\"second_bank\",\"third_bank\",\"last_bank\"), District=c(\"A\",\"B\"))library(knitr)kable(df[1:5,], format=\"markdown\", align=\"c\")" }, { "code": null, "e": 18808, "s": 18750, "text": "We can calculate the ICC using the snippet of code below:" }, { "code": null, "e": 19420, "s": 18808, "text": "ICC_CI <- function(cluster_level,outcomevar, dataf){ #load libraryrequire(ICC) set.seed(123) si = round(dim(dataf)[1]*0.66) values_f <- c() for(i in seq(1:50)){ samp_f = dataf[sample(nrow(dataf), si), ] x_f = ICCbare(cluster_level,outcomevar,samp_f) values_f <- c(values_f, x_f) } # note that 1.96StDevs = 95% confidence interval bounds in a normal dist. ret = data.frame(\"Mean ICC\" = round(mean(values_f, na.rm=TRUE),3), \"CI\" = round(1.96*sd(values_f, na.rm=TRUE),3)) ret$Significant = ifelse(ret$Mean.ICC > ret$CI, \"Y\", \"N\") return( ret) }stored_ICC <- ICC_CI(\"bank_name\", \"variableA\", df)" }, { "code": null, "e": 19737, "s": 19420, "text": "We can see from this calculation that our ICC between customers in the same bank is (0.022 +/- 0.081). As the confidence intervals (CI) cross zero we can see that this is not significant (hence “Significant = N”). In other words, it appears that banks account for a negligible amount of similarity between customers." }, { "code": null, "e": 19900, "s": 19737, "text": "However, if we have a significant ICC then we will need to adjust our trial design and analysis plans to mitigate ICC effects. We generally have two options here:" }, { "code": null, "e": 20175, "s": 19900, "text": "Option 1: Calculate a summary metric for each cluster (e.g. cluster mean). Each cluster then provides only one data point and allows us to continue with the assumption that our data is independent, we can then proceed with standard statistical tools (e.g. T-test) as normal." }, { "code": null, "e": 20536, "s": 20175, "text": "So if we have 500 individuals in 45 groups, we end up with 45 data points. This means that our power, sample size and analysis calculations also need to be carried out at the cluster level. It also means that we can simply analyse our data at the cluster level and ignore ICC from here on out (as we essentially set ICC = 1.0 and proceed with this assumption)." }, { "code": null, "e": 20612, "s": 20536, "text": "Use the ICC with the number of individuals to work out our new sample size." }, { "code": null, "e": 20795, "s": 20612, "text": "For option 2, we will continue to calculate power, sample size and analysis metrics at the individual level but with some corrections to account for the falsely narrow distributions." }, { "code": null, "e": 20875, "s": 20795, "text": "For our sample size, we will inflate it with the ICC_correction function below:" }, { "code": null, "e": 21195, "s": 20875, "text": "ICC_correction <- function(samplesize, num_clusters, ICC_estimate){ average_cluster_size = samplesize/num_clusters factor_inflate = 1 + (average_cluster_size - 1) * ICC_estimate return(data.frame(\"New sample size\"=round(samplesize*factor_inflate), \"Old sample size\"=samplesize ))}ICC_correction(200, 50, 0.2)" }, { "code": null, "e": 21398, "s": 21195, "text": "So an initial sample size of 200 customers, with 30 clusters (banks) and an ICC of 0.2 would lead to a new sample size of 320. Note how a relatively small ICC increases our sample size by more than 50%." }, { "code": null, "e": 21515, "s": 21398, "text": "We can also explore the difference between adding new clusters vs new individuals in existing clusters. For example:" }, { "code": null, "e": 21725, "s": 21515, "text": "scenario1 <- ICC_correction(200,20,0.2)$New.sample.size #average 10 farmers per cluster, and 20 clustersscenario2 <- ICC_correction(200,40,0.2)$New.sample.size # average 5 farmers per cluster, and 40 clusters" }, { "code": null, "e": 21743, "s": 21725, "text": "`scenario1= 560 `" }, { "code": null, "e": 21760, "s": 21743, "text": "`scenario2= 360`" }, { "code": null, "e": 21969, "s": 21760, "text": "We can see that doubling the number of clusters (but keeping the number of participants the same, so that customers are just spread out to more clusters) leads to a sizable reduction in corrected sample size." }, { "code": null, "e": 22172, "s": 21969, "text": "I’ve run a simulation below that will plot the relationship between adding new individuals (to existing clusters) vs adding new clusters and how this effects sample size (holding power constant at 0.8):" }, { "code": null, "e": 22394, "s": 22172, "text": "In general, we can see that adding new clusters rather than new individuals to existing clusters, inflates our corrected sample size to a lesser extent (there is a link to this simulation code at the bottom of this post)." }, { "code": null, "e": 22812, "s": 22394, "text": "By adding new clusters, we are minimising the amount of total variance explained by within-cluster variance, thus gaining information. Another intuitive explanation is that if I already have 10 individuals in a single cluster, and we have non-zero ICC, then every additional individual in that cluster provides less and less information and her characteristics are more and more predictable based on cluster averages." }, { "code": null, "e": 22922, "s": 22812, "text": "NB. In the next post, we will look at the actual analysis of ICC data with fixed and random effect modelling." }, { "code": null, "e": 23317, "s": 22922, "text": "Once we have a testable hypothesis and a randomization strategy, we will want to think about data analysis. Generally, we will test the effectiveness of an intervention with a hypothesis test. This hypothesis test will yield a p-value, which is the probability that our data could generated purely by chance — in other words, the probability that we wrongly reject H0 (a false positive result)." }, { "code": null, "e": 23690, "s": 23317, "text": "When using a hypothesis test we must set an acceptable rate of false positives, aka a p-value threshold or alpha level. The most common p-value threshold is 0.05 (a pretty arbitrary number). This means that we are willing to accept a 5% risk of generating a false positive and wrongly concluding that there is a difference between our treatments when in fact there is not." }, { "code": null, "e": 23881, "s": 23690, "text": "We can demonstrate this below, if we randomly test two *samples* from identical *populations* then 5% of the time we will mistakenly identify the samples as being from different populations:" }, { "code": null, "e": 24331, "s": 23881, "text": "In some cases we might want to set a threshold of 0.01 (1%) or 0.1 (10%). Generally speaking, the more unwilling we are to be incorrect, the lower the threshold. So for an intervention that might have adverse effects on customers, we would want to be very sure of the positive effects (0.01 threshold) and unwilling to accept negative effects (0.1 threshold). Note that the lower our threshold the larger the sample size needed to detect any effect." }, { "code": null, "e": 24413, "s": 24331, "text": "As always, full R code for these figures is available at the bottom of this post." }, { "code": null, "e": 24746, "s": 24413, "text": "Combining the materials from this post and post #1 gives us a good theoretical foundation for sample size calculations. However a common question I want to address here is: “where do I get the data from for a sample size calculation?”. We can use the Amazon layout trial example from above to understand how to answer this question." }, { "code": null, "e": 24949, "s": 24746, "text": "The main piece of information needed before a sample size calculation is an estimate of intervention effect size. There are generally two ways we can derive an effect size estimate for our calculations:" }, { "code": null, "e": 24990, "s": 24949, "text": "Analyse historical data or pilot studies" }, { "code": null, "e": 25028, "s": 24990, "text": "set a minimum detectable effect (MDE)" }, { "code": null, "e": 25586, "s": 25028, "text": "The first of these involves literature review and/or a small pilot study to estimate the differences between treatment and control groups. Note that if you are using pilot data, then the estimate of effect size is likely to be very rough, so I recommend halving the effect size to be conservative and using that for calculations. If you are using literature values then again, treat them cautiously and consider any literature value to be an upper estimate of effect size (this is due to the Winner’s curse phenomenon which will be covered in a later post)." }, { "code": null, "e": 25659, "s": 25586, "text": "Perhaps the most business-savvy approach to this question utilises MDEs." }, { "code": null, "e": 26034, "s": 25659, "text": "The MDE approach will ask “what is the minimum effect that I would need to see for the intervention to be worthwhile?”, we would then set the effect size to that value. The reasoning here is that if the return on investment (ROI) of a proposed intervention is negative (or very small) then we don’t need to be able to precisely measure such a small value to make a decision." }, { "code": null, "e": 26491, "s": 26034, "text": "For example, implementing Layout B across Amazon.com might be quite expensive. We could calculate that the implementation would cost approximately $20,000 of staff time, in which case we would only care about being able to detect effects greater than $20,000. For arguments sake, let’s say that $20,000 corresponds to a 2% point bump in conversion rate in the US market, we then set our MDE to 2 points and our effect size to 2 points for our calculations." }, { "code": null, "e": 26826, "s": 26491, "text": "The MDE approach can be very powerful. Use it wisely during both pre-analysis (to estimate sample size) and post-analysis to say what size effect we would have been able to detect with a power of 0.8. You can see a worked example below for pre-analysis MDE, I have also included a function plot_MDE which you can use on your own data." }, { "code": null, "e": 28298, "s": 26826, "text": "#make some fake data, let's pretend its baseline datadat <- data.frame(\"mean.client.expenditure\" = rnorm(1000,100,10))#this function will plot MDE for various differences# differs is a list of intervention effects that you want to considerplot_MDE <- function(historical_data, differs){ #initialise empty vecp <- c()#remember our effect size function from post 1?cohen_d <- function(d1,d2) { m1 <- mean(d1, na.rm=TRUE) m2 <- mean(d2, na.rm=TRUE) s1 <- sd(d1, na.rm=TRUE) s2 <- sd(d2, na.rm=TRUE) spo <- sqrt((s1**2 + s2**2)/2) d <- (m1 - m2)/spo rpb <- d / sqrt((d**2)+4) ret <- list(\"rpb\" = rpb, \"effectsi\" = d) return(ret) } #load libsrequire(pwr)for(i in seq(1:length(differs) ) ) { samp1 <- historical_data xnu = differs[[i]] #this is a better version if you can understand it: samp2 <- samp1 + rnorm(length(samp1), xnu, xnu/10) #add some noise inp <- cohen_d(samp1, samp2) p[i] <- pwr.2p.test(h=inp$effectsi , sig.level=0.05, power=0.8, n=NULL)$n }require(ggplot2)print(ggplot() + geom_point(aes(x=p, y= differs), size=3, color=\"blue\", shape=1) + geom_line(aes(x=p, y=differs), size=1.2, color=\"blue\") + xlab(\"Sample size\")+ ylab(\"MDE\") + ggtitle(\"Minimum detectable effect vs. sample size\"))library(knitr)mde_tab = data.frame(\"MDE\"=differs, \"Sample size\"=p)kable(mde_tab, digits=2) }#set some differences for the loop, here, 1,2,5 (etc) are dollar increasesdiffs <- c(1,2,5,7.5,10,15,20,25)#plotplot_MDE(dat$mean.client.expenditure, diffs)" }, { "code": null, "e": 28560, "s": 28298, "text": "Note that this function will give you the Y-axis in whatever units you gave to the function (in this case, US dollars). You can use the MDE to calculate an initial sample size and then use the ICC correction to obtain the ICC-corrected sample size for that MDE." }, { "code": null, "e": 28790, "s": 28560, "text": "The final part of the A/B test is the measurement itself. This is often a neglected part of test design and therefore a major source of later analysis issues. Any hypothesis needs to have a good measurement strategy to be useful." }, { "code": null, "e": 28981, "s": 28790, "text": "I want to take a tangent to describe some analysis I did on an A/B test looking at airtime usage (aka phone credit) in Malawi for a telecommunication company to illustrate the pitfalls here." }, { "code": null, "e": 29488, "s": 28981, "text": "This A/B test examined the effect of a new product on airtime usage. During the A/B test, we asked people to recall how much money they had spent in the last month on airtime, and unbeknownst to them, we also had data from the telecommunications company on the actual amount spent by the same customers. When we compared the two metrics, we found there was very little correlation! Furthermore, when we looked at who was most likely to over-estimate their airtime spend, we found it was young, urban males." }, { "code": null, "e": 30027, "s": 29488, "text": "Now consider — had we only had the self-reported data, we would have thought that young urban men were big spenders on airtime, drawn many conclusions from this, and found many “statistically significant” (in terms of P-values of < 0.05) relationships! We would have made many recommendations to the telecommunications company about the new product, and our results would have held up to thorough statistical interrogation. In short — there would have been very little way to know we were wrong, but we would have been wrong nevertheless!" }, { "code": null, "e": 30389, "s": 30027, "text": "The moral of this story is that the best statistics in the world will not save a trial from poor measurement. The other moral is that self-reported data is often terrible (beware survey-heavy NGOs!), as it is influenced by how people want to be perceived ( perhaps by the interviewer, by the community, or by their own embarrassment about “low” airtime spends)." }, { "code": null, "e": 30608, "s": 30389, "text": "It is vital to spend some time thinking about the caveats and weaknesses of measurement strategies, and then to try to mitigate those weaknesses as much as possible (e.g. through obtaining corroborating data as above)." }, { "code": null, "e": 30831, "s": 30608, "text": "Finally, once the data is collected and analysed, it’s important to make it accessible and reproducible. This means writing clean code (ideally in R-markdown or Jupyter notebook) and saving the raw data on company servers." }, { "code": null, "e": 31116, "s": 30831, "text": "Every data scientist in a company new to big data has witnessed the litany of random CSV files and analysis scripts strewn across dozens of employee hard-drives. A system for storing such files and scripts for possible future use is necessary, and deserves its own blog post entirely!" }, { "code": null, "e": 31188, "s": 31116, "text": "If you liked this post, or found is useful, then please clap so I know!" }, { "code": null, "e": 31235, "s": 31188, "text": "We have now seen the key parts of an A/B test:" }, { "code": null, "e": 31430, "s": 31235, "text": "Hypothesis: A good hypothesis is testable and measurable. It must have a clearly defined evaluation criteria (e.g. are we measuring the average or the median? At the individual or group level?)." }, { "code": null, "e": 31841, "s": 31430, "text": "Randomization: We must randomize using R and ensuring our Treatment and Control groups are balanced. We can use RCT_random function to achieve this. We should also account for cluster effects and use the correct unit of randomization. It is possible to calculate the ICC and adjust sample size accordingly, it is also fair to assume an ICC of 1.0 and have the sample size calculated from the number of clusters" }, { "code": null, "e": 31942, "s": 31841, "text": "Power: Know your statistical power, sample size and MDE before and after a trial (see previous post)" }, { "code": null, "e": 32131, "s": 31942, "text": "Measurement: Measurements must be robust and reliable, think about the ways that we might be inaccurate and try to minimize the importance of self-reported metrics in any study you design!" }, { "code": null, "e": 32214, "s": 32131, "text": "You can view a fuller version of this post (complete with all R code) on my GitHub" }, { "code": null, "e": 32282, "s": 32214, "text": "Linear models, mixed-effect models, and more on hypothesis testing!" } ]
How to compare DateTime Column with only Date not time in MySQL?
To compare DateTime column with only Date, you need to use the Date() method. Following is the syntax. Below, you need to date in the 'yourDateValue': select *from yourTableName where Date(yourColumnName)='yourDateValue'; Let us first create a table: mysql> create table DemoTable ( ArrivalTime datetime ); Query OK, 0 rows affected (0.74 sec) Following is the query to insert some records in the table using insert command: mysql> insert into DemoTable values('2019-01-31 02:34:56'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('2019-04-09 18:20:58'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('2019-05-11 19:45:23'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('2019-02-03 21:10:02'); Query OK, 1 row affected (0.16 sec) Following is the query to display records from the table using select command: mysql> select *from DemoTable; This will produce the following output with date and time record: +---------------------+ | ArrivalTime | +---------------------+ | 2019-01-31 02:34:56 | | 2019-04-09 18:20:58 | 2019-05-11 19:45:23 | | 2019-02-03 21:10:02 | +---------------------+ 4 rows in set (0.00 sec) Following is the query to compare only date not time. Here, we are comparing the date: mysql> select *from DemoTable where Date(ArrivalTime)='2019-04-09'; This will produce the following output: +---------------------+ | ArrivalTime | +---------------------+ | 2019-04-09 18:20:58 | +---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1213, "s": 1062, "text": "To compare DateTime column with only Date, you need to use the Date() method. Following is the syntax. Below, you need to date in the 'yourDateValue':" }, { "code": null, "e": 1284, "s": 1213, "text": "select *from yourTableName where Date(yourColumnName)='yourDateValue';" }, { "code": null, "e": 1313, "s": 1284, "text": "Let us first create a table:" }, { "code": null, "e": 1409, "s": 1313, "text": "mysql> create table DemoTable\n(\n ArrivalTime datetime\n);\nQuery OK, 0 rows affected (0.74 sec)" }, { "code": null, "e": 1490, "s": 1409, "text": "Following is the query to insert some records in the table using insert command:" }, { "code": null, "e": 1874, "s": 1490, "text": "mysql> insert into DemoTable values('2019-01-31 02:34:56');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable values('2019-04-09 18:20:58');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('2019-05-11 19:45:23');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('2019-02-03 21:10:02');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1953, "s": 1874, "text": "Following is the query to display records from the table using select command:" }, { "code": null, "e": 1984, "s": 1953, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2050, "s": 1984, "text": "This will produce the following output with date and time record:" }, { "code": null, "e": 2267, "s": 2050, "text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2019-01-31 02:34:56 |\n| 2019-04-09 18:20:58 |\n2019-05-11 19:45:23 |\n| 2019-02-03 21:10:02 |\n+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2354, "s": 2267, "text": "Following is the query to compare only date not time. Here, we are comparing the date:" }, { "code": null, "e": 2422, "s": 2354, "text": "mysql> select *from DemoTable where Date(ArrivalTime)='2019-04-09';" }, { "code": null, "e": 2462, "s": 2422, "text": "This will produce the following output:" }, { "code": null, "e": 2606, "s": 2462, "text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2019-04-09 18:20:58 |\n+---------------------+\n1 row in set (0.00 sec)" } ]
How to set timeout for ajax by using jQuery? - GeeksforGeeks
13 Dec, 2021 In web programming, the Ajax is used so that the resultant data is shown in the one part of the web page, without reloading the page. The user needs to perform the Ajax request and wants the result within a timeframe. In this scenario, the jquery timeout feature is used in the code. Session timeout has been a very common feature in Ajax-based web applications.In responsive interface, the programmer needs to delay the ajax request to achieve some task before the response. This can be achieved by using jQuery setTimeout() function. This function executes the given Ajax code after some amount of given time.Syntax : $.ajax(page_url); $.ajax(page_url,[options]); Parameters: page_url: This parameter is used to submit data or retrieve data. options: This parameter is used to hold the other configuration settings required for ajax request. Below example illustrates the approach:Example 1: Code snippet: $.ajax({ url: "test.php", error: function(){ //Error code }, success: function(){ //Success code } timeout: 5000 // sets timeout to 5 seconds }); The success function is executed if the request succeeds. Or sometimes if an error occurred, its better to respond quickly than waiting for a longer time.This is handled in the error function. The below program, explains the implementation of timeout option in the ajax part of code. The timeout is the number which specifies time in milliseconds for the request to be handled. Program: HTML FIle: html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Set timeout for ajax using jQuery</title> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script language="javascript"> var ajaxObject = null; // ajaxcall function will handle ajax call function ajaxCall() { var dataquery = 'true'; if (ajaxObject != null) { ajaxObject.abort(); $("#ajaxOutput") .html("Ajax aborted for initialization again! "); ajaxObject = null; } // creating ajax call ajaxObject = $.ajax({ // setting the url url: "data.php", data: { dataquery: '' }, // Set to 5 seconds for timeout limit timeout: 5000, //Check for success message in ajaxOutput div success: (function(response, responseStatus) { if (responseStatus == 'success') { $("#ajaxOutput").html(response); } }), // Check for existence of file statusCode: { 404: function() { $("#ajaxOutput") .html("File does not exists!"); } }, // If the time exceeds 5 seconds // then throw error message error: function(xhr, textStatus, errorThrown) { if (textStatus == 'timeout') { $("#ajaxOutput") .html("Error : Timeout for this call!"); } } }); } </script></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> Set timeout for ajax using jQuery </b> <div class="height"> </div> <div> <button type="button" onclick="ajaxCall()"> Send Data </button> <div class="height"> </div> <div id="ajaxOutput"> </div> </div> </body> </html> PHP File: The following PHP file is used in the above example. php <?php if($_GET["dataquery"]=='true') { sleep(7); } echo "Welcome to GeeksForGeeks";?> Output : Before Clicking on the button : After Clicking on the button : Example 2: The setTimeout() is a jQuery function which executes a code snippet after delaying a specific time limit. For example, delaying a popup window for a specific time limit, for a user visiting some website. This method accepts a pointer to a function as its first parameter. In this example, delay the Ajax code for 4 seconds using the setTimeout() method.Code snippet : function callerFunction(){ alert("jQuery setTimeOut execution is fine!"); } setTimeout(callerFunction, 4000); var callerFunction = function(){ alert("Execution point!"); }; setTimeout(callerFunction, 4000); Program: HTML File: html <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>Set timeout for ajax using jQuery</title> <style> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style> <script src="https://code.jquery.com/jquery-3.4.1.js"> </script> <script> $(function() { var timedelay = 4000; $('#sendData').on('click', function() { $.ajax({ type: 'POST', url: 'test.php', data: { "data": "checkData" }, success: function(response) { setTimeout(function() { $('#ajaxOutput') .append(response); }, timedelay); } }); }); }); </script></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b>Set timeout for ajax using jQuery</b> <div class="height"></div> <div> <button type="button" id="sendData"> Set timeout for getting data </button> <div class="height"></div> <div id="ajaxOutput"></div> </div></body> </html> PHP File: For the above example code, use the following PHP file. php <?php if(isset($_POST['data']) && $_POST['data'] == 'checkData'){ $data['value1'] = 'Successfully received first data'; $data['value2'] = 'Successfully received second data'; $response = json_encode($data); echo $response; }?> Output: Before Clicking on the button : After Clicking on the button : Cancel the timeout: Sometimes the programmer needs to cancel the timer set in the code by using jQuery clearTimeout() method. Code snippet: var timerValue = setTimeout(timerFunction, 5000); clearTimeout(timerValue); jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. sagartomar9927 jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26954, "s": 26926, "text": "\n13 Dec, 2021" }, { "code": null, "e": 27576, "s": 26954, "text": "In web programming, the Ajax is used so that the resultant data is shown in the one part of the web page, without reloading the page. The user needs to perform the Ajax request and wants the result within a timeframe. In this scenario, the jquery timeout feature is used in the code. Session timeout has been a very common feature in Ajax-based web applications.In responsive interface, the programmer needs to delay the ajax request to achieve some task before the response. This can be achieved by using jQuery setTimeout() function. This function executes the given Ajax code after some amount of given time.Syntax : " }, { "code": null, "e": 27594, "s": 27576, "text": "$.ajax(page_url);" }, { "code": null, "e": 27622, "s": 27594, "text": "$.ajax(page_url,[options]);" }, { "code": null, "e": 27635, "s": 27622, "text": "Parameters: " }, { "code": null, "e": 27701, "s": 27635, "text": "page_url: This parameter is used to submit data or retrieve data." }, { "code": null, "e": 27801, "s": 27701, "text": "options: This parameter is used to hold the other configuration settings required for ajax request." }, { "code": null, "e": 27852, "s": 27801, "text": "Below example illustrates the approach:Example 1: " }, { "code": null, "e": 27868, "s": 27852, "text": "Code snippet: " }, { "code": null, "e": 28053, "s": 27868, "text": "$.ajax({\n url: \"test.php\",\n error: function(){\n //Error code\n },\n success: function(){\n //Success code\n }\n timeout: 5000 // sets timeout to 5 seconds\n});" }, { "code": null, "e": 28431, "s": 28053, "text": "The success function is executed if the request succeeds. Or sometimes if an error occurred, its better to respond quickly than waiting for a longer time.This is handled in the error function. The below program, explains the implementation of timeout option in the ajax part of code. The timeout is the number which specifies time in milliseconds for the request to be handled." }, { "code": null, "e": 28442, "s": 28431, "text": "Program: " }, { "code": null, "e": 28455, "s": 28442, "text": "HTML FIle: " }, { "code": null, "e": 28460, "s": 28455, "text": "html" }, { "code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title>Set timeout for ajax using jQuery</title> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style> <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"> </script> <script language=\"javascript\"> var ajaxObject = null; // ajaxcall function will handle ajax call function ajaxCall() { var dataquery = 'true'; if (ajaxObject != null) { ajaxObject.abort(); $(\"#ajaxOutput\") .html(\"Ajax aborted for initialization again! \"); ajaxObject = null; } // creating ajax call ajaxObject = $.ajax({ // setting the url url: \"data.php\", data: { dataquery: '' }, // Set to 5 seconds for timeout limit timeout: 5000, //Check for success message in ajaxOutput div success: (function(response, responseStatus) { if (responseStatus == 'success') { $(\"#ajaxOutput\").html(response); } }), // Check for existence of file statusCode: { 404: function() { $(\"#ajaxOutput\") .html(\"File does not exists!\"); } }, // If the time exceeds 5 seconds // then throw error message error: function(xhr, textStatus, errorThrown) { if (textStatus == 'timeout') { $(\"#ajaxOutput\") .html(\"Error : Timeout for this call!\"); } } }); } </script></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> Set timeout for ajax using jQuery </b> <div class=\"height\"> </div> <div> <button type=\"button\" onclick=\"ajaxCall()\"> Send Data </button> <div class=\"height\"> </div> <div id=\"ajaxOutput\"> </div> </div> </body> </html>", "e": 30823, "s": 28460, "text": null }, { "code": null, "e": 30888, "s": 30823, "text": "PHP File: The following PHP file is used in the above example. " }, { "code": null, "e": 30892, "s": 30888, "text": "php" }, { "code": "<?php if($_GET[\"dataquery\"]=='true') { sleep(7); } echo \"Welcome to GeeksForGeeks\";?>", "e": 31011, "s": 30892, "text": null }, { "code": null, "e": 31022, "s": 31011, "text": "Output : " }, { "code": null, "e": 31054, "s": 31022, "text": "Before Clicking on the button :" }, { "code": null, "e": 31085, "s": 31054, "text": "After Clicking on the button :" }, { "code": null, "e": 31466, "s": 31085, "text": "Example 2: The setTimeout() is a jQuery function which executes a code snippet after delaying a specific time limit. For example, delaying a popup window for a specific time limit, for a user visiting some website. This method accepts a pointer to a function as its first parameter. In this example, delay the Ajax code for 4 seconds using the setTimeout() method.Code snippet : " }, { "code": null, "e": 31578, "s": 31466, "text": "function callerFunction(){\n alert(\"jQuery setTimeOut execution is fine!\");\n}\nsetTimeout(callerFunction, 4000);" }, { "code": null, "e": 31677, "s": 31578, "text": "var callerFunction = function(){\n alert(\"Execution point!\");\n};\nsetTimeout(callerFunction, 4000);" }, { "code": null, "e": 31687, "s": 31677, "text": "Program: " }, { "code": null, "e": 31698, "s": 31687, "text": "HTML File:" }, { "code": null, "e": 31703, "s": 31698, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title>Set timeout for ajax using jQuery</title> <style> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"> </script> <script> $(function() { var timedelay = 4000; $('#sendData').on('click', function() { $.ajax({ type: 'POST', url: 'test.php', data: { \"data\": \"checkData\" }, success: function(response) { setTimeout(function() { $('#ajaxOutput') .append(response); }, timedelay); } }); }); }); </script></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b>Set timeout for ajax using jQuery</b> <div class=\"height\"></div> <div> <button type=\"button\" id=\"sendData\"> Set timeout for getting data </button> <div class=\"height\"></div> <div id=\"ajaxOutput\"></div> </div></body> </html>", "e": 33048, "s": 31703, "text": null }, { "code": null, "e": 33117, "s": 33050, "text": "PHP File: For the above example code, use the following PHP file. " }, { "code": null, "e": 33121, "s": 33117, "text": "php" }, { "code": "<?php if(isset($_POST['data']) && $_POST['data'] == 'checkData'){ $data['value1'] = 'Successfully received first data'; $data['value2'] = 'Successfully received second data'; $response = json_encode($data); echo $response; }?>", "e": 33394, "s": 33121, "text": null }, { "code": null, "e": 33403, "s": 33394, "text": "Output: " }, { "code": null, "e": 33435, "s": 33403, "text": "Before Clicking on the button :" }, { "code": null, "e": 33466, "s": 33435, "text": "After Clicking on the button :" }, { "code": null, "e": 33593, "s": 33466, "text": "Cancel the timeout: Sometimes the programmer needs to cancel the timer set in the code by using jQuery clearTimeout() method. " }, { "code": null, "e": 33608, "s": 33593, "text": "Code snippet: " }, { "code": null, "e": 33684, "s": 33608, "text": "var timerValue = setTimeout(timerFunction, 5000);\nclearTimeout(timerValue);" }, { "code": null, "e": 33953, "s": 33684, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 33968, "s": 33953, "text": "sagartomar9927" }, { "code": null, "e": 33980, "s": 33968, "text": "jQuery-Misc" }, { "code": null, "e": 33987, "s": 33980, "text": "Picked" }, { "code": null, "e": 33994, "s": 33987, "text": "JQuery" }, { "code": null, "e": 34011, "s": 33994, "text": "Web Technologies" }, { "code": null, "e": 34038, "s": 34011, "text": "Web technologies Questions" }, { "code": null, "e": 34136, "s": 34038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34191, "s": 34136, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 34264, "s": 34191, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 34287, "s": 34264, "text": "jQuery | ajax() Method" }, { "code": null, "e": 34323, "s": 34287, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 34380, "s": 34323, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 34420, "s": 34380, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34453, "s": 34420, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34498, "s": 34453, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34541, "s": 34498, "text": "How to fetch data from an API in ReactJS ?" } ]
Replicate elements of vector in R programming - rep() Method - GeeksforGeeks
21 Dec, 2021 In the R programming language, A very useful function for creating a vector by repeating a given numbervector with the specified number of times is the rep(). The general structure of rep() : rep(v1,n1). Here, v1 is repeated n1 times. The forms of rep() functions : rep(v1, times=) rep(v1, each=) rep(v1, length=) Example 1: R # Replicate '0' 5 timerep(0, 5) Output: [1] 0 0 0 0 0 Example 2: rep(v1, times=) R # 1,2,3 repeated 3 times in sequenciallyrep(1:3,times=3) Output: [1] 1 2 3 1 2 3 1 2 3 Example 3: rep(v1, each=) R # 1,2,3 repeated 3 timesrep(1:3,each=3) Output: [1] 1 2 3 1 2 3 1 2 3 Example 4: rep(v1, length=) R # generate a vector 1,2,3x<-1:3 # vector x is replicated such that the# length is five.rep(x, length=5) Output: 1 2 3 1 2 Example 5: R # 1 is replicated 2 times, and so onrep(x,c(2,1,3)) Output: 1 1 2 3 3 3 immortalishika2001 kumar_satyam R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame 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 Replace Specific Characters in String in R Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 26111, "s": 26083, "text": "\n21 Dec, 2021" }, { "code": null, "e": 26270, "s": 26111, "text": "In the R programming language, A very useful function for creating a vector by repeating a given numbervector with the specified number of times is the rep()." }, { "code": null, "e": 26315, "s": 26270, "text": "The general structure of rep() : rep(v1,n1)." }, { "code": null, "e": 26346, "s": 26315, "text": "Here, v1 is repeated n1 times." }, { "code": null, "e": 26377, "s": 26346, "text": "The forms of rep() functions :" }, { "code": null, "e": 26393, "s": 26377, "text": "rep(v1, times=)" }, { "code": null, "e": 26408, "s": 26393, "text": "rep(v1, each=)" }, { "code": null, "e": 26425, "s": 26408, "text": "rep(v1, length=)" }, { "code": null, "e": 26436, "s": 26425, "text": "Example 1:" }, { "code": null, "e": 26438, "s": 26436, "text": "R" }, { "code": "# Replicate '0' 5 timerep(0, 5)", "e": 26470, "s": 26438, "text": null }, { "code": null, "e": 26478, "s": 26470, "text": "Output:" }, { "code": null, "e": 26492, "s": 26478, "text": "[1] 0 0 0 0 0" }, { "code": null, "e": 26503, "s": 26492, "text": "Example 2:" }, { "code": null, "e": 26520, "s": 26503, "text": "rep(v1, times=)" }, { "code": null, "e": 26522, "s": 26520, "text": "R" }, { "code": "# 1,2,3 repeated 3 times in sequenciallyrep(1:3,times=3)", "e": 26579, "s": 26522, "text": null }, { "code": null, "e": 26587, "s": 26579, "text": "Output:" }, { "code": null, "e": 26609, "s": 26587, "text": "[1] 1 2 3 1 2 3 1 2 3" }, { "code": null, "e": 26620, "s": 26609, "text": "Example 3:" }, { "code": null, "e": 26636, "s": 26620, "text": "rep(v1, each=)" }, { "code": null, "e": 26638, "s": 26636, "text": "R" }, { "code": "# 1,2,3 repeated 3 timesrep(1:3,each=3)", "e": 26678, "s": 26638, "text": null }, { "code": null, "e": 26686, "s": 26678, "text": "Output:" }, { "code": null, "e": 26708, "s": 26686, "text": "[1] 1 2 3 1 2 3 1 2 3" }, { "code": null, "e": 26719, "s": 26708, "text": "Example 4:" }, { "code": null, "e": 26737, "s": 26719, "text": "rep(v1, length=)" }, { "code": null, "e": 26739, "s": 26737, "text": "R" }, { "code": "# generate a vector 1,2,3x<-1:3 # vector x is replicated such that the# length is five.rep(x, length=5)", "e": 26843, "s": 26739, "text": null }, { "code": null, "e": 26851, "s": 26843, "text": "Output:" }, { "code": null, "e": 26861, "s": 26851, "text": "1 2 3 1 2" }, { "code": null, "e": 26872, "s": 26861, "text": "Example 5:" }, { "code": null, "e": 26874, "s": 26872, "text": "R" }, { "code": "# 1 is replicated 2 times, and so onrep(x,c(2,1,3))", "e": 26926, "s": 26874, "text": null }, { "code": null, "e": 26934, "s": 26926, "text": "Output:" }, { "code": null, "e": 26946, "s": 26934, "text": "1 1 2 3 3 3" }, { "code": null, "e": 26965, "s": 26946, "text": "immortalishika2001" }, { "code": null, "e": 26978, "s": 26965, "text": "kumar_satyam" }, { "code": null, "e": 26989, "s": 26978, "text": "R Language" }, { "code": null, "e": 27087, "s": 26989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27139, "s": 27087, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27171, "s": 27139, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27223, "s": 27171, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27267, "s": 27223, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27302, "s": 27267, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27340, "s": 27302, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27398, "s": 27340, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27434, "s": 27398, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 27477, "s": 27434, "text": "Replace Specific Characters in String in R" } ]
How to calculate the XOR of array elements using JavaScript ? - GeeksforGeeks
15 Apr, 2020 Given an array and is the task to find the XOR of Array elements using JavaScript. There are two approaches to solve this problem which are discussed below: Simple method: It uses a simple method to access the array elements by an index number and use the loop to find the XOR of values of an Array using JavaScript. Example: This example uses a simple method to find the XOR of Array elements using JavaScript. <!DOCTYPE html> <html> <head> <title> How to Find the XOR of Values of an Array in JavaScript? </title> </head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to Find the XOR of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </h4> <button onclick="myGeeks()">Click</button> <p id="gfg"></p> <script> function XOR(input) { if (toString.call(input) !== "[object Array]") return false; var total = Number(input[0]); for(var i=1;i<input.length;i++) { if(isNaN(input[i])){ continue; } total ^= Number(input[i]); } return total; } function myGeeks(item) { document.getElementById("gfg").innerHTML = "----XOR of Array----" + "<br>" + XOR([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); } </script> </body> </html> Output: Before click on the Button: After click on the Button: Using reduce() method: The array reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function( total, currentValue, currentIndex, arr ), initialValue ) Example: This example uses array reduce() method to find the XOR of values of an Array using JavaScript. <!DOCTYPE html> <html> <head> <title> How to Find the XOR of Values of an Array in JavaScript? </title> </head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to Find the XOR of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </h4> <button onclick="myGeeks()"> Click Here! </button> <br><br> XOR: <span id="GFG"></span> <script> var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function ORofArray(XOR, num) { return XOR ^ num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduce(ORofArray); } </script> </body> </html> Output: Before click on the Button: After click on the Button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26109, "s": 26081, "text": "\n15 Apr, 2020" }, { "code": null, "e": 26266, "s": 26109, "text": "Given an array and is the task to find the XOR of Array elements using JavaScript. There are two approaches to solve this problem which are discussed below:" }, { "code": null, "e": 26426, "s": 26266, "text": "Simple method: It uses a simple method to access the array elements by an index number and use the loop to find the XOR of values of an Array using JavaScript." }, { "code": null, "e": 26521, "s": 26426, "text": "Example: This example uses a simple method to find the XOR of Array elements using JavaScript." }, { "code": "<!DOCTYPE html> <html> <head> <title> How to Find the XOR of Values of an Array in JavaScript? </title> </head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to Find the XOR of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </h4> <button onclick=\"myGeeks()\">Click</button> <p id=\"gfg\"></p> <script> function XOR(input) { if (toString.call(input) !== \"[object Array]\") return false; var total = Number(input[0]); for(var i=1;i<input.length;i++) { if(isNaN(input[i])){ continue; } total ^= Number(input[i]); } return total; } function myGeeks(item) { document.getElementById(\"gfg\").innerHTML = \"----XOR of Array----\" + \"<br>\" + XOR([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); } </script> </body> </html> ", "e": 27756, "s": 26521, "text": null }, { "code": null, "e": 27764, "s": 27756, "text": "Output:" }, { "code": null, "e": 27792, "s": 27764, "text": "Before click on the Button:" }, { "code": null, "e": 27819, "s": 27792, "text": "After click on the Button:" }, { "code": null, "e": 28076, "s": 27819, "text": "Using reduce() method: The array reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator." }, { "code": null, "e": 28084, "s": 28076, "text": "Syntax:" }, { "code": null, "e": 28165, "s": 28084, "text": "array.reduce( function( total, currentValue, currentIndex, arr ), initialValue )" }, { "code": null, "e": 28270, "s": 28165, "text": "Example: This example uses array reduce() method to find the XOR of values of an Array using JavaScript." }, { "code": "<!DOCTYPE html> <html> <head> <title> How to Find the XOR of Values of an Array in JavaScript? </title> </head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to Find the XOR of Values of an Array in JavaScript? </h3> <h4> ----Given Array----<br> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </h4> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> XOR: <span id=\"GFG\"></span> <script> var arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function ORofArray(XOR, num) { return XOR ^ num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduce(ORofArray); } </script> </body> </html> ", "e": 29186, "s": 28270, "text": null }, { "code": null, "e": 29194, "s": 29186, "text": "Output:" }, { "code": null, "e": 29222, "s": 29194, "text": "Before click on the Button:" }, { "code": null, "e": 29249, "s": 29222, "text": "After click on the Button:" }, { "code": null, "e": 29265, "s": 29249, "text": "JavaScript-Misc" }, { "code": null, "e": 29276, "s": 29265, "text": "JavaScript" }, { "code": null, "e": 29293, "s": 29276, "text": "Web Technologies" }, { "code": null, "e": 29320, "s": 29293, "text": "Web technologies Questions" }, { "code": null, "e": 29418, "s": 29320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29458, "s": 29418, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29503, "s": 29458, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29564, "s": 29503, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29636, "s": 29564, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29688, "s": 29636, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29728, "s": 29688, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29761, "s": 29728, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29806, "s": 29761, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29849, "s": 29806, "text": "How to fetch data from an API in ReactJS ?" } ]
GATE | GATE CS 2019 | Question 35 - GeeksforGeeks
05 Aug, 2021 Consider the following C program: void convert(int n) { if (n < 0) printf(“ % d”, n); else { convert(n / 2); printf(“ % d”, n % 2); }} Which one of the following will happen when the function convert is called with any positive integer n as argument?(A) It will print the binary representation of n in the reverse order and terminate.(B) It will print the binary representation of n but will not terminate(C) It will not print anything and will not terminate.(D) It will print the binary representation of n and terminate.Answer: (C)Explanation: Since n is the integer, so it 1/2 = 0.5 = 0 will return because of integer. 0/2 = 0 will cause infinite loop because there is no terminating condition for 0. So, option (C) is correct. Note:It will print the binary representation of n and terminate, only if condition “if (n <= 0)". #include <stdio.h> void convert(int n) { if(n <= 0) printf("%d", n); else { convert(n / 2); printf("%d", n%2); };} int main() { convert (16);} YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:009:12 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25623, "s": 25595, "text": "\n05 Aug, 2021" }, { "code": null, "e": 25657, "s": 25623, "text": "Consider the following C program:" }, { "code": "void convert(int n) { if (n < 0) printf(“ % d”, n); else { convert(n / 2); printf(“ % d”, n % 2); }}", "e": 25770, "s": 25657, "text": null }, { "code": null, "e": 26257, "s": 25770, "text": "Which one of the following will happen when the function convert is called with any positive integer n as argument?(A) It will print the binary representation of n in the reverse order and terminate.(B) It will print the binary representation of n but will not terminate(C) It will not print anything and will not terminate.(D) It will print the binary representation of n and terminate.Answer: (C)Explanation: Since n is the integer, so it 1/2 = 0.5 = 0 will return because of integer." }, { "code": null, "e": 26339, "s": 26257, "text": "0/2 = 0 will cause infinite loop because there is no terminating condition for 0." }, { "code": null, "e": 26366, "s": 26339, "text": "So, option (C) is correct." }, { "code": null, "e": 26464, "s": 26366, "text": "Note:It will print the binary representation of n and terminate, only if condition “if (n <= 0)\"." }, { "code": "#include <stdio.h> void convert(int n) { if(n <= 0) printf(\"%d\", n); else { convert(n / 2); printf(\"%d\", n%2); };} int main() { convert (16);}", "e": 26621, "s": 26464, "text": null }, { "code": null, "e": 27551, "s": 26621, "text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:009:12 / 1:16:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fP8QED8d6ws\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 27556, "s": 27551, "text": "GATE" }, { "code": null, "e": 27654, "s": 27556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27688, "s": 27654, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27722, "s": 27688, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27756, "s": 27722, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27789, "s": 27756, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27825, "s": 27789, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27861, "s": 27825, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27895, "s": 27861, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27929, "s": 27895, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27963, "s": 27929, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to change screen background color in Pygame? - GeeksforGeeks
01 Oct, 2020 Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.init(): This function is used to initialize all the pygame modules. pygame.display.set_mode(): This function is used to initialize a screen for display. fill(): This method is used to fill the display with the color specified. Example 1: This example sets the screen background color to red. Python3 # Importing the libraryimport pygame # Initializing Pygamepygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing RGB Color color = (255,0, 0) # Changing surface colorsurface.fill(color)pygame.display.flip() Output: Example 2: This example uses RGB color to set the screen color to blue. Python3 # Importing the libraryimport pygame # Initializing Pygame modulespygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing RGB Color color = (0, 0, 255) # Changing surface colorsurface.fill(color)pygame.display.flip() Output: Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25579, "s": 25551, "text": "\n01 Oct, 2020" }, { "code": null, "e": 25797, "s": 25579, "text": "Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language." }, { "code": null, "e": 25813, "s": 25797, "text": "Functions Used:" }, { "code": null, "e": 25888, "s": 25813, "text": "pygame.init(): This function is used to initialize all the pygame modules." }, { "code": null, "e": 25973, "s": 25888, "text": "pygame.display.set_mode(): This function is used to initialize a screen for display." }, { "code": null, "e": 26047, "s": 25973, "text": "fill(): This method is used to fill the display with the color specified." }, { "code": null, "e": 26112, "s": 26047, "text": "Example 1: This example sets the screen background color to red." }, { "code": null, "e": 26120, "s": 26112, "text": "Python3" }, { "code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing RGB Color color = (255,0, 0) # Changing surface colorsurface.fill(color)pygame.display.flip()", "e": 26370, "s": 26120, "text": null }, { "code": null, "e": 26378, "s": 26370, "text": "Output:" }, { "code": null, "e": 26450, "s": 26378, "text": "Example 2: This example uses RGB color to set the screen color to blue." }, { "code": null, "e": 26458, "s": 26450, "text": "Python3" }, { "code": "# Importing the libraryimport pygame # Initializing Pygame modulespygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing RGB Color color = (0, 0, 255) # Changing surface colorsurface.fill(color)pygame.display.flip()", "e": 26717, "s": 26458, "text": null }, { "code": null, "e": 26725, "s": 26717, "text": "Output:" }, { "code": null, "e": 26739, "s": 26725, "text": "Python-PyGame" }, { "code": null, "e": 26746, "s": 26739, "text": "Python" }, { "code": null, "e": 26844, "s": 26746, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26876, "s": 26844, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26918, "s": 26876, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26960, "s": 26918, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27016, "s": 26960, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27043, "s": 27016, "text": "Python Classes and Objects" }, { "code": null, "e": 27074, "s": 27043, "text": "Python | os.path.join() method" }, { "code": null, "e": 27113, "s": 27074, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27142, "s": 27113, "text": "Create a directory in Python" }, { "code": null, "e": 27164, "s": 27142, "text": "Defaultdict in Python" } ]
Filtering a PySpark DataFrame using isin by exclusion - GeeksforGeeks
29 Jun, 2021 In this article, we will discuss how to filter the pyspark dataframe using isin by exclusion. isin(): This is used to find the elements contains in a given dataframe, it takes the elements and gets the elements to match the data. Syntax: isin([element1,element2,.,element n) Creating Dataframe for demonstration: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data with null values# we can define null values with nonedata = [[1, "sravan", "vignan"], [2, "ramya", "vvit"], [3, "rohith", "klu"], [4, "sridevi", "vignan"], [5, "gnanesh", "iit"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)dataframe.show() Output: Method 1: Using filter() filter(): This clause is used to check the condition and give the results, Both are similar Syntax: dataframe.filter(condition) Example 1: Get the particular ID’s with filter() clause Python3 # get the ID : 1,2,3 from dataframedataframe.filter((dataframe.ID).isin([1,2,3])).show() Output: Example 2: Get names from dataframe columns. Python3 # get name as sravandataframe.filter((dataframe.NAME).isin(['sravan'])).show() Output: Method 2: Using Where() where(): This clause is used to check the condition and give the results Syntax: dataframe.where(condition) Example 1: Get the particular colleges with where() clause. Python3 # get college as vignandataframe.where((dataframe.college).isin(['vignan'])).show() Output: Example 2: Get ID except 5 from dataframe. Python3 # get ID except 1dataframe.where(~(dataframe.ID).isin([1])).show() Output: Picked Python-Pyspark 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": "\n29 Jun, 2021" }, { "code": null, "e": 25631, "s": 25537, "text": "In this article, we will discuss how to filter the pyspark dataframe using isin by exclusion." }, { "code": null, "e": 25767, "s": 25631, "text": "isin(): This is used to find the elements contains in a given dataframe, it takes the elements and gets the elements to match the data." }, { "code": null, "e": 25812, "s": 25767, "text": "Syntax: isin([element1,element2,.,element n)" }, { "code": null, "e": 25850, "s": 25812, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 25858, "s": 25850, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data with null values# we can define null values with nonedata = [[1, \"sravan\", \"vignan\"], [2, \"ramya\", \"vvit\"], [3, \"rohith\", \"klu\"], [4, \"sridevi\", \"vignan\"], [5, \"gnanesh\", \"iit\"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)dataframe.show()", "e": 26491, "s": 25858, "text": null }, { "code": null, "e": 26499, "s": 26491, "text": "Output:" }, { "code": null, "e": 26524, "s": 26499, "text": "Method 1: Using filter()" }, { "code": null, "e": 26616, "s": 26524, "text": "filter(): This clause is used to check the condition and give the results, Both are similar" }, { "code": null, "e": 26652, "s": 26616, "text": "Syntax: dataframe.filter(condition)" }, { "code": null, "e": 26708, "s": 26652, "text": "Example 1: Get the particular ID’s with filter() clause" }, { "code": null, "e": 26716, "s": 26708, "text": "Python3" }, { "code": "# get the ID : 1,2,3 from dataframedataframe.filter((dataframe.ID).isin([1,2,3])).show()", "e": 26805, "s": 26716, "text": null }, { "code": null, "e": 26813, "s": 26805, "text": "Output:" }, { "code": null, "e": 26858, "s": 26813, "text": "Example 2: Get names from dataframe columns." }, { "code": null, "e": 26866, "s": 26858, "text": "Python3" }, { "code": "# get name as sravandataframe.filter((dataframe.NAME).isin(['sravan'])).show()", "e": 26945, "s": 26866, "text": null }, { "code": null, "e": 26953, "s": 26945, "text": "Output:" }, { "code": null, "e": 26977, "s": 26953, "text": "Method 2: Using Where()" }, { "code": null, "e": 27050, "s": 26977, "text": "where(): This clause is used to check the condition and give the results" }, { "code": null, "e": 27085, "s": 27050, "text": "Syntax: dataframe.where(condition)" }, { "code": null, "e": 27145, "s": 27085, "text": "Example 1: Get the particular colleges with where() clause." }, { "code": null, "e": 27153, "s": 27145, "text": "Python3" }, { "code": "# get college as vignandataframe.where((dataframe.college).isin(['vignan'])).show()", "e": 27237, "s": 27153, "text": null }, { "code": null, "e": 27245, "s": 27237, "text": "Output:" }, { "code": null, "e": 27288, "s": 27245, "text": "Example 2: Get ID except 5 from dataframe." }, { "code": null, "e": 27296, "s": 27288, "text": "Python3" }, { "code": "# get ID except 1dataframe.where(~(dataframe.ID).isin([1])).show()", "e": 27363, "s": 27296, "text": null }, { "code": null, "e": 27371, "s": 27363, "text": "Output:" }, { "code": null, "e": 27378, "s": 27371, "text": "Picked" }, { "code": null, "e": 27393, "s": 27378, "text": "Python-Pyspark" }, { "code": null, "e": 27400, "s": 27393, "text": "Python" }, { "code": null, "e": 27498, "s": 27400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27530, "s": 27498, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27572, "s": 27530, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27614, "s": 27572, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27641, "s": 27614, "text": "Python Classes and Objects" }, { "code": null, "e": 27697, "s": 27641, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27719, "s": 27697, "text": "Defaultdict in Python" }, { "code": null, "e": 27758, "s": 27719, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27789, "s": 27758, "text": "Python | os.path.join() method" }, { "code": null, "e": 27818, "s": 27789, "text": "Create a directory in Python" } ]
Java 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. Java // Java program for Naive Pattern Searchingpublic class NaiveSearch { public static void search(String txt, String pat) { int M = pat.length(); int N = txt.length(); /* 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.charAt(i + j) != pat.charAt(j)) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] System.out.println("Pattern found at index " + i); } } public static void main(String[] args) { String txt = "AABAACAADAABAAABAA"; String pat = "AABA"; search(txt, pat); }}// This code is contributed by Harikishore 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! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Replace a Element in Java ArrayList? Java Program to Read a File to String Java Program to Find Sum of Array Elements How to Write Data into Excel Sheet using Java? Removing last element from ArrayList in Java Tic-Tac-Toe Game in Java Java Program to Write an Array of Strings to the Output Console
[ { "code": null, "e": 26107, "s": 26079, "text": "\n11 Dec, 2018" }, { "code": null, "e": 26281, "s": 26107, "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": 26291, "s": 26281, "text": "Examples:" }, { "code": null, "e": 26549, "s": 26291, "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": 26754, "s": 26549, "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": 26759, "s": 26754, "text": "Java" }, { "code": "// Java program for Naive Pattern Searchingpublic class NaiveSearch { public static void search(String txt, String pat) { int M = pat.length(); int N = txt.length(); /* 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.charAt(i + j) != pat.charAt(j)) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] System.out.println(\"Pattern found at index \" + i); } } public static void main(String[] args) { String txt = \"AABAACAADAABAAABAA\"; String pat = \"AABA\"; search(txt, pat); }}// This code is contributed by Harikishore", "e": 27589, "s": 26759, "text": null }, { "code": null, "e": 27666, "s": 27589, "text": "Pattern found at index 0\nPattern found at index 9\nPattern found at index 13\n" }, { "code": null, "e": 27755, "s": 27666, "text": "Please refer complete article on Naive algorithm for Pattern Searching for more details!" }, { "code": null, "e": 27769, "s": 27755, "text": "Java Programs" }, { "code": null, "e": 27867, "s": 27769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27915, "s": 27867, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 27966, "s": 27915, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 28000, "s": 27966, "text": "Java Program to Write into a File" }, { "code": null, "e": 28044, "s": 28000, "text": "How to Replace a Element in Java ArrayList?" }, { "code": null, "e": 28082, "s": 28044, "text": "Java Program to Read a File to String" }, { "code": null, "e": 28125, "s": 28082, "text": "Java Program to Find Sum of Array Elements" }, { "code": null, "e": 28172, "s": 28125, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 28217, "s": 28172, "text": "Removing last element from ArrayList in Java" }, { "code": null, "e": 28242, "s": 28217, "text": "Tic-Tac-Toe Game in Java" } ]
Python | Type conversion in dictionary values - GeeksforGeeks
16 Aug, 2021 The problem of conventional type conversion is quite common and can be easily done using the built-in converters of python libraries. But sometimes, we may require the same functionality in a more complex scenario vis. for keys of list of dictionaries. Let’s discuss certain ways in which this can be achieved.Method #1 : Naive Method In the naive method, we employ 2 loops, nested. One for all the dictionaries in the list and the second one for the dictionary key-value pairs in a specific dictionary. Python3 # Python3 code to demonstrate# Type conversion in list of dicts.# using naive method # initializing list of dictionarytest_list = [{'a' : '1', 'b' : '2'}, { 'c' : '3', 'd' : '4'}] # printing original listprint ("The original list is : " + str(test_list)) # using naive method# type conversation in list of dicts.for dicts in test_list: for keys in dicts: dicts[keys] = int(dicts[keys]) # printing resultprint ("The modified converted list is : " + str(test_list)) Output : The original list is : [{'a': '1', 'b': '2'}, {'c': '3', 'd': '4'}] The modified converted list is : [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}] Method #2 : Using items() + list comprehension This can easily performed using just a one line with the help of list comprehension. The items function can be exploited to extract the list values as when required and list comprehension part handles the iteration part. Python3 # Python3 code to demonstrate# Type conversion in list of dicts.# using items() + list comprehension # initializing list of dictionarytest_list = [{'a' : '1', 'b' : '2'}, { 'c' : '3', 'd' : '4'}] # printing original listprint ("The original list is : " + str(test_list)) # using items() + list comprehension# type conversation in list of dicts.res = [dict([key, int(value)] for key, value in dicts.items()) for dicts in test_list] # printing resultprint ("The modified converted list is : " + str(res)) Output : The original list is : [{'b': '2', 'a': '1'}, {'c': '3', 'd': '4'}] The modified converted list is : [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}] kalrap615 Python dictionary-programs python-dict Python Python Programs python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25603, "s": 25575, "text": "\n16 Aug, 2021" }, { "code": null, "e": 26108, "s": 25603, "text": "The problem of conventional type conversion is quite common and can be easily done using the built-in converters of python libraries. But sometimes, we may require the same functionality in a more complex scenario vis. for keys of list of dictionaries. Let’s discuss certain ways in which this can be achieved.Method #1 : Naive Method In the naive method, we employ 2 loops, nested. One for all the dictionaries in the list and the second one for the dictionary key-value pairs in a specific dictionary. " }, { "code": null, "e": 26116, "s": 26108, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Type conversion in list of dicts.# using naive method # initializing list of dictionarytest_list = [{'a' : '1', 'b' : '2'}, { 'c' : '3', 'd' : '4'}] # printing original listprint (\"The original list is : \" + str(test_list)) # using naive method# type conversation in list of dicts.for dicts in test_list: for keys in dicts: dicts[keys] = int(dicts[keys]) # printing resultprint (\"The modified converted list is : \" + str(test_list))", "e": 26595, "s": 26116, "text": null }, { "code": null, "e": 26606, "s": 26595, "text": "Output : " }, { "code": null, "e": 26744, "s": 26606, "text": "The original list is : [{'a': '1', 'b': '2'}, {'c': '3', 'd': '4'}]\nThe modified converted list is : [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]" }, { "code": null, "e": 27014, "s": 26744, "text": " Method #2 : Using items() + list comprehension This can easily performed using just a one line with the help of list comprehension. The items function can be exploited to extract the list values as when required and list comprehension part handles the iteration part. " }, { "code": null, "e": 27022, "s": 27014, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Type conversion in list of dicts.# using items() + list comprehension # initializing list of dictionarytest_list = [{'a' : '1', 'b' : '2'}, { 'c' : '3', 'd' : '4'}] # printing original listprint (\"The original list is : \" + str(test_list)) # using items() + list comprehension# type conversation in list of dicts.res = [dict([key, int(value)] for key, value in dicts.items()) for dicts in test_list] # printing resultprint (\"The modified converted list is : \" + str(res))", "e": 27542, "s": 27022, "text": null }, { "code": null, "e": 27553, "s": 27542, "text": "Output : " }, { "code": null, "e": 27691, "s": 27553, "text": "The original list is : [{'b': '2', 'a': '1'}, {'c': '3', 'd': '4'}]\nThe modified converted list is : [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]" }, { "code": null, "e": 27703, "s": 27693, "text": "kalrap615" }, { "code": null, "e": 27730, "s": 27703, "text": "Python dictionary-programs" }, { "code": null, "e": 27742, "s": 27730, "text": "python-dict" }, { "code": null, "e": 27749, "s": 27742, "text": "Python" }, { "code": null, "e": 27765, "s": 27749, "text": "Python Programs" }, { "code": null, "e": 27777, "s": 27765, "text": "python-dict" }, { "code": null, "e": 27875, "s": 27777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27893, "s": 27875, "text": "Python Dictionary" }, { "code": null, "e": 27928, "s": 27893, "text": "Read a file line by line in Python" }, { "code": null, "e": 27960, "s": 27928, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27982, "s": 27960, "text": "Enumerate() in Python" }, { "code": null, "e": 28024, "s": 27982, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28067, "s": 28024, "text": "Python program to convert a list to string" }, { "code": null, "e": 28089, "s": 28067, "text": "Defaultdict in Python" }, { "code": null, "e": 28128, "s": 28089, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28174, "s": 28128, "text": "Python | Split string into list of characters" } ]
How to Fix: Invalid value encountered in true_divide - GeeksforGeeks
22 Nov, 2021 In this article, we are going to fix, invalid values encountered in true_divide in Python. Invalid value encountered in true_divide is a Runtime Warning occurs when we perform an invalid division operation between elements of NumPy arrays. One of the examples of Invalid division is 0/0. Note: As it is just a Warning the code won’t stop from its execution and return a Not a Number value i.e. nan (or) inf (infinity). The division operation between NumPy arrays can be done using divide() which is present in NumPy package allows division operation between corresponding elements of 2 arrays. Python3 # import necessary packagesimport numpy as np # Create 2 Numpy arraysArray1 = np.array([6, 2, 0])Array2 = np.array([3, 2, 0]) # divide the values in Array1 by the# values in Array2np.divide(Array1, Array2) Output: C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:9: RuntimeWarning: invalid value encountered in true_divide if __name__ == ‘__main__’: Result-array([ 2., 1., nan]) Here we are dividing the elements of Array1 by the elements of Array2. So it returns the quotient value. 6/3=2 (Valid Operation) 2/2=1 (Valid Operation) 0/0 which is an invalid operation so a Warning is thrown and returns the result as Not a Number (nan). We can fix this Runtime Warning by using seterr method which takes invalid as a parameter and assign ignore as a value to it. By that, it can hide the warning message which contains invalid in that. Syntax: numpy.seterr(invalid=’ignore’) Python3 # import necessary packagesimport numpy as np # Create 2 Numpy arraysArray1 = np.array([6, 2, 0])Array2 = np.array([3, 2, 0]) # Supress/hide the warningnp.seterr(invalid='ignore') # divide the values in Array1 by the # values in Array2np.divide(Array1, Array2) Output: array([ 2., 1., nan]) Picked Python How-to-fix 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": "\n22 Nov, 2021" }, { "code": null, "e": 25827, "s": 25537, "text": "In this article, we are going to fix, invalid values encountered in true_divide in Python. Invalid value encountered in true_divide is a Runtime Warning occurs when we perform an invalid division operation between elements of NumPy arrays. One of the examples of Invalid division is 0/0. " }, { "code": null, "e": 25958, "s": 25827, "text": "Note: As it is just a Warning the code won’t stop from its execution and return a Not a Number value i.e. nan (or) inf (infinity)." }, { "code": null, "e": 26134, "s": 25958, "text": "The division operation between NumPy arrays can be done using divide() which is present in NumPy package allows division operation between corresponding elements of 2 arrays. " }, { "code": null, "e": 26142, "s": 26134, "text": "Python3" }, { "code": "# import necessary packagesimport numpy as np # Create 2 Numpy arraysArray1 = np.array([6, 2, 0])Array2 = np.array([3, 2, 0]) # divide the values in Array1 by the# values in Array2np.divide(Array1, Array2)", "e": 26350, "s": 26142, "text": null }, { "code": null, "e": 26358, "s": 26350, "text": "Output:" }, { "code": null, "e": 26483, "s": 26358, "text": "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:9: RuntimeWarning: invalid value encountered in true_divide" }, { "code": null, "e": 26512, "s": 26483, "text": " if __name__ == ‘__main__’:" }, { "code": null, "e": 26543, "s": 26512, "text": "Result-array([ 2., 1., nan]) " }, { "code": null, "e": 26648, "s": 26543, "text": "Here we are dividing the elements of Array1 by the elements of Array2. So it returns the quotient value." }, { "code": null, "e": 26673, "s": 26648, "text": "6/3=2 (Valid Operation)" }, { "code": null, "e": 26698, "s": 26673, "text": "2/2=1 (Valid Operation)" }, { "code": null, "e": 26804, "s": 26698, "text": "0/0 which is an invalid operation so a Warning is thrown and returns the result as Not a Number (nan)." }, { "code": null, "e": 27003, "s": 26804, "text": "We can fix this Runtime Warning by using seterr method which takes invalid as a parameter and assign ignore as a value to it. By that, it can hide the warning message which contains invalid in that." }, { "code": null, "e": 27042, "s": 27003, "text": "Syntax: numpy.seterr(invalid=’ignore’)" }, { "code": null, "e": 27050, "s": 27042, "text": "Python3" }, { "code": "# import necessary packagesimport numpy as np # Create 2 Numpy arraysArray1 = np.array([6, 2, 0])Array2 = np.array([3, 2, 0]) # Supress/hide the warningnp.seterr(invalid='ignore') # divide the values in Array1 by the # values in Array2np.divide(Array1, Array2)", "e": 27314, "s": 27050, "text": null }, { "code": null, "e": 27322, "s": 27314, "text": "Output:" }, { "code": null, "e": 27345, "s": 27322, "text": "array([ 2., 1., nan])" }, { "code": null, "e": 27352, "s": 27345, "text": "Picked" }, { "code": null, "e": 27370, "s": 27352, "text": "Python How-to-fix" }, { "code": null, "e": 27377, "s": 27370, "text": "Python" }, { "code": null, "e": 27475, "s": 27377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27507, "s": 27475, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27549, "s": 27507, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27591, "s": 27549, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27618, "s": 27591, "text": "Python Classes and Objects" }, { "code": null, "e": 27674, "s": 27618, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27696, "s": 27674, "text": "Defaultdict in Python" }, { "code": null, "e": 27735, "s": 27696, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27766, "s": 27735, "text": "Python | os.path.join() method" }, { "code": null, "e": 27795, "s": 27766, "text": "Create a directory in Python" } ]
Java Program to Accept a Matrix of Order M x N & Interchange the Diagonals - GeeksforGeeks
09 Aug, 2021 Problem Description: Write a Java program that accepts a matrix of M × N order and then interchange diagonals of the matrix. Steps: 1. We can only interchange diagonals for a square matrix. 2. Create a square matrix of size [M × M]. 3. Check the matrix is a square matrix or not. If the matrix is square then follow step 3 else terminate the program. 4. Apply logic for interchange diagonal of the matrix some logic is given below. Method 1: Swap element a[i][i] and a[i][n – i -1] for (j = 0; j < m; j++) { temp = a[j][j]; a[j][j] = a[j][n – 1 – j]; a[j][n – 1 – j] = temp; } Example: Java // Java Program to Accept a Matrix of Order M x N &// Interchange the Diagonals import java.util.Scanner;public class InterchangeDiagonals { public static void main(String[] args) { // declare variable int m, n, i, j, temp; // create a object of scanner class Scanner sc = new Scanner(System.in); System.out.print("Enter number of rows "); // take number of rows m = sc.nextInt(); System.out.print("Enter number of columns "); // take number of columns n = sc.nextInt(); // declare a mxn order array int a[][] = new int[m][n]; // if block it's execute when m is equals to n if (m == n) { System.out.println( "Enter all the values of matrix "); // take the matrix inputs for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { a[i][j] = sc.nextInt(); } } System.out.println("original Matrix:"); // print the original matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(""); } // perform interchange for (j = 0; j < m; j++) { temp = a[j][j]; a[j][j] = a[j][n - 1 - j]; a[j][n - 1 - j] = temp; } System.out.println( " after interchanging diagonals of matrix "); // print interchanged matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(""); } } // else block it's only execute when m is not equals // to n else { System.out.println("Rows not equal to columns"); } }} Output: Enter number of rows 3 Enter number of columns 3 Enter all the values of matrix 1 2 3 4 5 6 7 8 9 Original Matrix: 1 2 3 4 5 6 7 8 9 After interchanging diagonals of matrix 3 2 1 4 5 6 9 8 7 Example 2: Java // Java Program to Accept a Matrix of Order MxN &// Interchange the Diagonals import java.util.Scanner;public class InterchangeDiagonals { public static void main(String[] args) { // declare variable int m, n, i, j, temp; // create a object of scanner class Scanner sc = new Scanner(System.in); System.out.print("Enter number of rows "); // take number of rows m = sc.nextInt(); System.out.print("Enter number of columns "); // take number of columns n = sc.nextInt(); // declare a mxn order array int a[][] = new int[m][n]; // if block it's execute when m is equals to n if (m == n) { System.out.println( "Enter all the values of matrix "); // take input matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { a[i][j] = sc.nextInt(); } } System.out.println("original Matrix:"); // print original matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(""); } // performing interchange for (j = 0; j < m; j++) { temp = a[j][j]; a[j][j] = a[j][n - 1 - j]; a[j][n - 1 - j] = temp; } System.out.println( " after interchanging diagonals of matrix "); // print interchanged matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(""); } } // else block it's only execute when m is not equals // to n else { System.out.println("Rows not equal to columns"); } }} Output: Enter number of rows 2 Enter number of columns 1 Enter all the values of matrix 1 2 Rows not equal to columns abhishek0719kadiyan Java 8 Java-Output Java.lang.Class Output of Java Program Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initializing a List 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
[ { "code": null, "e": 25945, "s": 25917, "text": "\n09 Aug, 2021" }, { "code": null, "e": 26070, "s": 25945, "text": "Problem Description: Write a Java program that accepts a matrix of M × N order and then interchange diagonals of the matrix." }, { "code": null, "e": 26079, "s": 26070, "text": "Steps: " }, { "code": null, "e": 26137, "s": 26079, "text": "1. We can only interchange diagonals for a square matrix." }, { "code": null, "e": 26180, "s": 26137, "text": "2. Create a square matrix of size [M × M]." }, { "code": null, "e": 26298, "s": 26180, "text": "3. Check the matrix is a square matrix or not. If the matrix is square then follow step 3 else terminate the program." }, { "code": null, "e": 26379, "s": 26298, "text": "4. Apply logic for interchange diagonal of the matrix some logic is given below." }, { "code": null, "e": 26429, "s": 26379, "text": "Method 1: Swap element a[i][i] and a[i][n – i -1]" }, { "code": null, "e": 26470, "s": 26429, "text": " for (j = 0; j < m; j++) {" }, { "code": null, "e": 26501, "s": 26470, "text": " temp = a[j][j];" }, { "code": null, "e": 26543, "s": 26501, "text": " a[j][j] = a[j][n – 1 – j];" }, { "code": null, "e": 26582, "s": 26543, "text": " a[j][n – 1 – j] = temp;" }, { "code": null, "e": 26595, "s": 26582, "text": " }" }, { "code": null, "e": 26604, "s": 26595, "text": "Example:" }, { "code": null, "e": 26609, "s": 26604, "text": "Java" }, { "code": "// Java Program to Accept a Matrix of Order M x N &// Interchange the Diagonals import java.util.Scanner;public class InterchangeDiagonals { public static void main(String[] args) { // declare variable int m, n, i, j, temp; // create a object of scanner class Scanner sc = new Scanner(System.in); System.out.print(\"Enter number of rows \"); // take number of rows m = sc.nextInt(); System.out.print(\"Enter number of columns \"); // take number of columns n = sc.nextInt(); // declare a mxn order array int a[][] = new int[m][n]; // if block it's execute when m is equals to n if (m == n) { System.out.println( \"Enter all the values of matrix \"); // take the matrix inputs for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { a[i][j] = sc.nextInt(); } } System.out.println(\"original Matrix:\"); // print the original matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(\"\"); } // perform interchange for (j = 0; j < m; j++) { temp = a[j][j]; a[j][j] = a[j][n - 1 - j]; a[j][n - 1 - j] = temp; } System.out.println( \" after interchanging diagonals of matrix \"); // print interchanged matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(\"\"); } } // else block it's only execute when m is not equals // to n else { System.out.println(\"Rows not equal to columns\"); } }}", "e": 28575, "s": 26609, "text": null }, { "code": null, "e": 28586, "s": 28578, "text": "Output:" }, { "code": null, "e": 28609, "s": 28586, "text": "Enter number of rows 3" }, { "code": null, "e": 28635, "s": 28609, "text": "Enter number of columns 3" }, { "code": null, "e": 28668, "s": 28635, "text": "Enter all the values of matrix " }, { "code": null, "e": 28670, "s": 28668, "text": "1" }, { "code": null, "e": 28672, "s": 28670, "text": "2" }, { "code": null, "e": 28674, "s": 28672, "text": "3" }, { "code": null, "e": 28676, "s": 28674, "text": "4" }, { "code": null, "e": 28678, "s": 28676, "text": "5" }, { "code": null, "e": 28680, "s": 28678, "text": "6" }, { "code": null, "e": 28682, "s": 28680, "text": "7" }, { "code": null, "e": 28684, "s": 28682, "text": "8" }, { "code": null, "e": 28686, "s": 28684, "text": "9" }, { "code": null, "e": 28703, "s": 28686, "text": "Original Matrix:" }, { "code": null, "e": 28715, "s": 28703, "text": "1 2 3 " }, { "code": null, "e": 28727, "s": 28715, "text": "4 5 6 " }, { "code": null, "e": 28739, "s": 28727, "text": "7 8 9 " }, { "code": null, "e": 28781, "s": 28739, "text": "After interchanging diagonals of matrix " }, { "code": null, "e": 28793, "s": 28781, "text": "3 2 1 " }, { "code": null, "e": 28805, "s": 28793, "text": "4 5 6 " }, { "code": null, "e": 28816, "s": 28805, "text": "9 8 7 " }, { "code": null, "e": 28829, "s": 28818, "text": "Example 2:" }, { "code": null, "e": 28834, "s": 28829, "text": "Java" }, { "code": "// Java Program to Accept a Matrix of Order MxN &// Interchange the Diagonals import java.util.Scanner;public class InterchangeDiagonals { public static void main(String[] args) { // declare variable int m, n, i, j, temp; // create a object of scanner class Scanner sc = new Scanner(System.in); System.out.print(\"Enter number of rows \"); // take number of rows m = sc.nextInt(); System.out.print(\"Enter number of columns \"); // take number of columns n = sc.nextInt(); // declare a mxn order array int a[][] = new int[m][n]; // if block it's execute when m is equals to n if (m == n) { System.out.println( \"Enter all the values of matrix \"); // take input matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { a[i][j] = sc.nextInt(); } } System.out.println(\"original Matrix:\"); // print original matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(\"\"); } // performing interchange for (j = 0; j < m; j++) { temp = a[j][j]; a[j][j] = a[j][n - 1 - j]; a[j][n - 1 - j] = temp; } System.out.println( \" after interchanging diagonals of matrix \"); // print interchanged matrix for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(\"\"); } } // else block it's only execute when m is not equals // to n else { System.out.println(\"Rows not equal to columns\"); } }}", "e": 30792, "s": 28834, "text": null }, { "code": null, "e": 30800, "s": 30792, "text": "Output:" }, { "code": null, "e": 30823, "s": 30800, "text": "Enter number of rows 2" }, { "code": null, "e": 30849, "s": 30823, "text": "Enter number of columns 1" }, { "code": null, "e": 30882, "s": 30849, "text": "Enter all the values of matrix " }, { "code": null, "e": 30884, "s": 30882, "text": "1" }, { "code": null, "e": 30886, "s": 30884, "text": "2" }, { "code": null, "e": 30912, "s": 30886, "text": "Rows not equal to columns" }, { "code": null, "e": 30934, "s": 30914, "text": "abhishek0719kadiyan" }, { "code": null, "e": 30941, "s": 30934, "text": "Java 8" }, { "code": null, "e": 30953, "s": 30941, "text": "Java-Output" }, { "code": null, "e": 30969, "s": 30953, "text": "Java.lang.Class" }, { "code": null, "e": 30992, "s": 30969, "text": "Output of Java Program" }, { "code": null, "e": 31016, "s": 30992, "text": "Technical Scripter 2020" }, { "code": null, "e": 31021, "s": 31016, "text": "Java" }, { "code": null, "e": 31035, "s": 31021, "text": "Java Programs" }, { "code": null, "e": 31054, "s": 31035, "text": "Technical Scripter" }, { "code": null, "e": 31059, "s": 31054, "text": "Java" }, { "code": null, "e": 31157, "s": 31059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31208, "s": 31157, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31238, "s": 31208, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31253, "s": 31238, "text": "Stream In Java" }, { "code": null, "e": 31272, "s": 31253, "text": "Interfaces in Java" }, { "code": null, "e": 31303, "s": 31272, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31331, "s": 31303, "text": "Initializing a List in Java" }, { "code": null, "e": 31375, "s": 31331, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 31401, "s": 31375, "text": "Java Programming Examples" }, { "code": null, "e": 31435, "s": 31401, "text": "Convert Double to Integer in Java" } ]
jQuery - add( selector ) Method
The add( selector ) method adds more elements, matched by the given selector, to the set of matched elements. Here is the simple syntax to use this method − selector.add( selector ) Here is the description of all the parameters used by this method − selector − It could be a comma-separated list of selectors to select elements to be added. (e.g. add(".class1, .class2")). selector − It could be a comma-separated list of selectors to select elements to be added. (e.g. add(".class1, .class2")). Following is a simple example a simple showing the usage of this method − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $(".top").add(".middle").addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li class = "above">list item 0</li> <li class = "top">list item 1</li> <li class = "top">list item 2</li> <li class = "middle">list item 3</li> <li class = "middle">list item 4</li> <li class = "bottom">list item 5</li> <li class = "bottom">list item 6</li> <li class = "below">list item 7</li> </ul> </div> </body> </html> This will produce following result − list item 0 list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 list item 7 Following is a simple example a simple showing the usage of this method − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $(".top").add(".middle").addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li class = "above">list item 0</li> <li class = "selected">list item 1</li> <li class = "selected">list item 2</li> <li class = "selected">list item 3</li> <li class = "selected">list item 4</li> <li class = "bottom">list item 5</li> <li class = "bottom">list item 6</li> <li class = "below">list item 7</li> </ul> </div> </body> </html> This will produce following result − list item 0 list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 list item 7 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2432, "s": 2322, "text": "The add( selector ) method adds more elements, matched by the given selector, to the set of matched elements." }, { "code": null, "e": 2479, "s": 2432, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2505, "s": 2479, "text": "selector.add( selector )\n" }, { "code": null, "e": 2573, "s": 2505, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2696, "s": 2573, "text": "selector − It could be a comma-separated list of selectors to select elements to be added. (e.g. add(\".class1, .class2\"))." }, { "code": null, "e": 2819, "s": 2696, "text": "selector − It could be a comma-separated list of selectors to select elements to be added. (e.g. add(\".class1, .class2\"))." }, { "code": null, "e": 2893, "s": 2819, "text": "Following is a simple example a simple showing the usage of this method −" }, { "code": null, "e": 3838, "s": 2893, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\".top\").add(\".middle\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li class = \"above\">list item 0</li>\n <li class = \"top\">list item 1</li>\n <li class = \"top\">list item 2</li>\n <li class = \"middle\">list item 3</li>\n <li class = \"middle\">list item 4</li>\n <li class = \"bottom\">list item 5</li>\n <li class = \"bottom\">list item 6</li>\n <li class = \"below\">list item 7</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3875, "s": 3838, "text": "This will produce following result −" }, { "code": null, "e": 3887, "s": 3875, "text": "list item 0" }, { "code": null, "e": 3899, "s": 3887, "text": "list item 1" }, { "code": null, "e": 3911, "s": 3899, "text": "list item 2" }, { "code": null, "e": 3923, "s": 3911, "text": "list item 3" }, { "code": null, "e": 3935, "s": 3923, "text": "list item 4" }, { "code": null, "e": 3947, "s": 3935, "text": "list item 5" }, { "code": null, "e": 3959, "s": 3947, "text": "list item 6" }, { "code": null, "e": 3971, "s": 3959, "text": "list item 7" }, { "code": null, "e": 4045, "s": 3971, "text": "Following is a simple example a simple showing the usage of this method −" }, { "code": null, "e": 5004, "s": 4045, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\".top\").add(\".middle\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li class = \"above\">list item 0</li>\n <li class = \"selected\">list item 1</li>\n <li class = \"selected\">list item 2</li>\n <li class = \"selected\">list item 3</li>\n <li class = \"selected\">list item 4</li>\n <li class = \"bottom\">list item 5</li>\n <li class = \"bottom\">list item 6</li>\n <li class = \"below\">list item 7</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 5041, "s": 5004, "text": "This will produce following result −" }, { "code": null, "e": 5053, "s": 5041, "text": "list item 0" }, { "code": null, "e": 5065, "s": 5053, "text": "list item 1" }, { "code": null, "e": 5077, "s": 5065, "text": "list item 2" }, { "code": null, "e": 5089, "s": 5077, "text": "list item 3" }, { "code": null, "e": 5101, "s": 5089, "text": "list item 4" }, { "code": null, "e": 5113, "s": 5101, "text": "list item 5" }, { "code": null, "e": 5125, "s": 5113, "text": "list item 6" }, { "code": null, "e": 5137, "s": 5125, "text": "list item 7" }, { "code": null, "e": 5170, "s": 5137, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 5184, "s": 5170, "text": " Mahesh Kumar" }, { "code": null, "e": 5219, "s": 5184, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5233, "s": 5219, "text": " Pratik Singh" }, { "code": null, "e": 5268, "s": 5233, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5285, "s": 5268, "text": " Frahaan Hussain" }, { "code": null, "e": 5318, "s": 5285, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 5346, "s": 5318, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5379, "s": 5346, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5400, "s": 5379, "text": " Sandip Bhattacharya" }, { "code": null, "e": 5432, "s": 5400, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 5449, "s": 5432, "text": " Laurence Svekis" }, { "code": null, "e": 5456, "s": 5449, "text": " Print" }, { "code": null, "e": 5467, "s": 5456, "text": " Add Notes" } ]
Python 3 - String index() Method
The index() method determines if the string str occurs in string or in a substring of string, if the starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found. Following is the syntax for index() method − str.index(str, beg = 0 end = len(string)) str − This specifies the string to be searched. str − This specifies the string to be searched. beg − This is the starting index, by default its 0. beg − This is the starting index, by default its 0. end − This is the ending index, by default its equal to the length of the string. end − This is the ending index, by default its equal to the length of the string. Index if found otherwise raises an exception if str is not found. #!/usr/bin/python3 str1 = "this is string example....wow!!!" str2 = "exam"; print (str1.index(str2)) print (str1.index(str2, 10)) print (str1.index(str2, 40)) When we run above program, it produces the following result − 15 15 Traceback (most recent call last): File "test.py", line 7, in <module> print (str1.index(str2, 40)) ValueError: substring not found shell returned 1 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": 2568, "s": 2340, "text": "The index() method determines if the string str occurs in string or in a substring of string, if the starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found." }, { "code": null, "e": 2613, "s": 2568, "text": "Following is the syntax for index() method −" }, { "code": null, "e": 2656, "s": 2613, "text": "str.index(str, beg = 0 end = len(string))\n" }, { "code": null, "e": 2704, "s": 2656, "text": "str − This specifies the string to be searched." }, { "code": null, "e": 2752, "s": 2704, "text": "str − This specifies the string to be searched." }, { "code": null, "e": 2804, "s": 2752, "text": "beg − This is the starting index, by default its 0." }, { "code": null, "e": 2856, "s": 2804, "text": "beg − This is the starting index, by default its 0." }, { "code": null, "e": 2938, "s": 2856, "text": "end − This is the ending index, by default its equal to the length of the string." }, { "code": null, "e": 3020, "s": 2938, "text": "end − This is the ending index, by default its equal to the length of the string." }, { "code": null, "e": 3086, "s": 3020, "text": "Index if found otherwise raises an exception if str is not found." }, { "code": null, "e": 3247, "s": 3086, "text": "#!/usr/bin/python3\n\nstr1 = \"this is string example....wow!!!\"\nstr2 = \"exam\";\n\nprint (str1.index(str2))\nprint (str1.index(str2, 10))\nprint (str1.index(str2, 40))" }, { "code": null, "e": 3309, "s": 3247, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 3474, "s": 3309, "text": "15\n15\nTraceback (most recent call last):\n File \"test.py\", line 7, in <module>\n print (str1.index(str2, 40))\nValueError: substring not found\nshell returned 1\n" }, { "code": null, "e": 3511, "s": 3474, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3527, "s": 3511, "text": " Malhar Lathkar" }, { "code": null, "e": 3560, "s": 3527, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3579, "s": 3560, "text": " Arnab Chakraborty" }, { "code": null, "e": 3614, "s": 3579, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3636, "s": 3614, "text": " In28Minutes Official" }, { "code": null, "e": 3670, "s": 3636, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3698, "s": 3670, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3733, "s": 3698, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3747, "s": 3733, "text": " Lets Kode It" }, { "code": null, "e": 3780, "s": 3747, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3797, "s": 3780, "text": " Abhilash Nelson" }, { "code": null, "e": 3804, "s": 3797, "text": " Print" }, { "code": null, "e": 3815, "s": 3804, "text": " Add Notes" } ]
GATE | GATE-CS-2014-(Set-2) | Question 60 - GeeksforGeeks
28 Jun, 2021 Consider the following relation on subsets of the set S of integers between 1 and 2014. For two distinct subsets U and V of S we say U < V if the minimum element in the symmetric difference of the two sets is in U. Consider the following two statements: S1: There is a subset of S that is larger than every other subset. S2: There is a subset of S that is smaller than every other subset. Which one of the following is CORRECT?(A) Both S1 and S2 are true(B) S1 is true and S2 is false(C) S2 is true and S1 is false(D) Neither S1 nor S2 is true Explanation –As question defined that “for two distinct subsets U and V of S we say U < V if the minimum element in the symmetric difference of the two sets is in U".Given, S = {1, 2, 3, ...., 2014}.Therefore,Subsets {1, 2, 3, ...., 2014} and {Ø} of S, so {1, 2, 3, ...., 2014} < {Ø} because the minimum element in the symmetric difference (i.e., {1, 2, 3, ...., 2014}) of the two sets is in set {1, 2, 3, ...., 2014}.Hence, {Ø} is a subset of S that is larger than every other subset.And, {1, 2, 3, ...., 2014} is a subset of S that is smaller than every other subset.Option (A) is correct. Please comment below if you find anything wrong in the above post.Quiz of this Question GATE-CS-2014-(Set-2) GATE-GATE-CS-2014-(Set-2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE CS 2019 | Question 27 GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | GATE CS 2010 | Question 24 GATE | GATE-CS-2000 | Question 43 GATE | GATE CS 2021 | Set 1 | Question 47
[ { "code": null, "e": 24534, "s": 24506, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24749, "s": 24534, "text": "Consider the following relation on subsets of the set S of integers between 1 and 2014. For two distinct subsets U and V of S we say U < V if the minimum element in the symmetric difference of the two sets is in U." }, { "code": null, "e": 24788, "s": 24749, "text": "Consider the following two statements:" }, { "code": null, "e": 24924, "s": 24788, "text": "S1: There is a subset of S that is larger than every other subset.\nS2: There is a subset of S that is smaller than every other subset. " }, { "code": null, "e": 25079, "s": 24924, "text": "Which one of the following is CORRECT?(A) Both S1 and S2 are true(B) S1 is true and S2 is false(C) S2 is true and S1 is false(D) Neither S1 nor S2 is true" }, { "code": null, "e": 25671, "s": 25079, "text": "Explanation –As question defined that “for two distinct subsets U and V of S we say U < V if the minimum element in the symmetric difference of the two sets is in U\".Given, S = {1, 2, 3, ...., 2014}.Therefore,Subsets {1, 2, 3, ...., 2014} and {Ø} of S, so {1, 2, 3, ...., 2014} < {Ø} because the minimum element in the symmetric difference (i.e., {1, 2, 3, ...., 2014}) of the two sets is in set {1, 2, 3, ...., 2014}.Hence, {Ø} is a subset of S that is larger than every other subset.And, {1, 2, 3, ...., 2014} is a subset of S that is smaller than every other subset.Option (A) is correct." }, { "code": null, "e": 25760, "s": 25671, "text": " Please comment below if you find anything wrong in the above post.Quiz of this Question" }, { "code": null, "e": 25781, "s": 25760, "text": "GATE-CS-2014-(Set-2)" }, { "code": null, "e": 25807, "s": 25781, "text": "GATE-GATE-CS-2014-(Set-2)" }, { "code": null, "e": 25812, "s": 25807, "text": "GATE" }, { "code": null, "e": 25910, "s": 25812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25944, "s": 25910, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 25978, "s": 25944, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26020, "s": 25978, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26062, "s": 26020, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26096, "s": 26062, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26129, "s": 26096, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26171, "s": 26129, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 26205, "s": 26171, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 26239, "s": 26205, "text": "GATE | GATE-CS-2000 | Question 43" } ]
Set.size Property in JavaScript
The size property of the Set object returns number representing the number of elements in the current set object. Its Syntax is as follows Obj.size(); Live Demo <html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> const setObj = new Set(); setObj.add('Java'); setObj.add('JavaFX'); setObj.add('JavaScript'); setObj.add('HBase'); document.write("Size of the Set object: "+setObj.size); </script> </body> </html> Size of the Set object: 4
[ { "code": null, "e": 1176, "s": 1062, "text": "The size property of the Set object returns number representing the number of elements in the current set object." }, { "code": null, "e": 1201, "s": 1176, "text": "Its Syntax is as follows" }, { "code": null, "e": 1213, "s": 1201, "text": "Obj.size();" }, { "code": null, "e": 1224, "s": 1213, "text": " Live Demo" }, { "code": null, "e": 1561, "s": 1224, "text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n const setObj = new Set();\n setObj.add('Java');\n setObj.add('JavaFX');\n setObj.add('JavaScript');\n setObj.add('HBase');\n document.write(\"Size of the Set object: \"+setObj.size);\n </script>\n</body>\n</html>" }, { "code": null, "e": 1587, "s": 1561, "text": "Size of the Set object: 4" } ]
SaltStack - Creating a Simple Environment
In this chapter, we will create a simple SaltStack environment, one salt master and two salt minions. This environment will help us to learn the salt concept in the upcoming chapters. Let us adhere to the following steps to create the SaltStack environment. VirtualBox is a cross-platform virtualization application. VirtualBox allows you to run more than one operating system at a time. VirtualBox runs on Windows, Linux, Macintosh and Solaris. It hosts and supports a large number of Guest Operating Systems. You can download and install VirtualBox by visiting the following link − https://www.virtualbox.org/wiki/Downloads We will create three virtual machines and run it using the VirtualBox. Vagrant provides easy to configure, reproducible and portable work environments. You can download and install the Vagrant by visiting the following link − https://www.vagrantup.com After the successful installation of Vagrant, you need to configure it. Create a single file named as Vagrantfile in a folder and describe the type of machine and its properties. Run Vagrant − To run the Vagrant, issue the following command − vagrant up After you run vagrant up, Vagrant creates and starts those machines, which are defined in the Vagrantfile using the VirtualBox in the background. These machines will be running until you close them. Stop Vagrant − To stop all the running machines in the VirtualBox, type the following command − vagrant halt SaltStack provides a simple demo environment as Vagrant setup and it is hosted in the github. Let us download the setup using the following command − cd /cd/to/path git clone https://github.com/UtahDave/salt-vagrant-demo Now, start the demo environment using the following command − cd /cd/to/path/salt-vagrant-demo vagrant up After this command, you will see the following response − result Now, three servers are running, one with the salt master configured and two with the salt minion configured. Login to the Salt master using the following command − vagrant ssh master Now, move to the root user using the command below − sudo su Now we have successfully connected to the Salt master. Let us now go through some of the basic commands in SaltStack. The following command is to verify the Salt minion connections and view whether the connection is accepted, rejected or pending. salt-key —list-all It will produce the following output − Accepted Keys: minion1 minion2 Denied Keys: Unaccepted Keys: Rejected Keys: Now, we have accepted all the keys, you can send a command from Salt master to check whether Salt minions are listening or not, salt '*' test.ping It will produce the following output − minion1: True minion2: True From the above result, list out minion 1 and minion 2, which means minions are listening properly, otherwise minions might now respond properly. Print Add Notes Bookmark this page
[ { "code": null, "e": 2391, "s": 2207, "text": "In this chapter, we will create a simple SaltStack environment, one salt master and two salt minions. This environment will help us to learn the salt concept in the upcoming chapters." }, { "code": null, "e": 2465, "s": 2391, "text": "Let us adhere to the following steps to create the SaltStack environment." }, { "code": null, "e": 2718, "s": 2465, "text": "VirtualBox is a cross-platform virtualization application. VirtualBox allows you to run more than one operating system at a time. VirtualBox runs on Windows, Linux, Macintosh and Solaris. It hosts and supports a large number of Guest Operating Systems." }, { "code": null, "e": 2833, "s": 2718, "text": "You can download and install VirtualBox by visiting the following link − https://www.virtualbox.org/wiki/Downloads" }, { "code": null, "e": 2904, "s": 2833, "text": "We will create three virtual machines and run it using the VirtualBox." }, { "code": null, "e": 2985, "s": 2904, "text": "Vagrant provides easy to configure, reproducible and portable work environments." }, { "code": null, "e": 3085, "s": 2985, "text": "You can download and install the Vagrant by visiting the following link − https://www.vagrantup.com" }, { "code": null, "e": 3264, "s": 3085, "text": "After the successful installation of Vagrant, you need to configure it. Create a single file named as Vagrantfile in a folder and describe the type of machine and its properties." }, { "code": null, "e": 3328, "s": 3264, "text": "Run Vagrant − To run the Vagrant, issue the following command −" }, { "code": null, "e": 3340, "s": 3328, "text": "vagrant up\n" }, { "code": null, "e": 3539, "s": 3340, "text": "After you run vagrant up, Vagrant creates and starts those machines, which are defined in the Vagrantfile using the VirtualBox in the background. These machines will be running until you close them." }, { "code": null, "e": 3635, "s": 3539, "text": "Stop Vagrant − To stop all the running machines in the VirtualBox, type the following command −" }, { "code": null, "e": 3649, "s": 3635, "text": "vagrant halt\n" }, { "code": null, "e": 3799, "s": 3649, "text": "SaltStack provides a simple demo environment as Vagrant setup and it is hosted in the github. Let us download the setup using the following command −" }, { "code": null, "e": 3872, "s": 3799, "text": "cd /cd/to/path\n\ngit clone https://github.com/UtahDave/salt-vagrant-demo\n" }, { "code": null, "e": 3934, "s": 3872, "text": "Now, start the demo environment using the following command −" }, { "code": null, "e": 3979, "s": 3934, "text": "cd /cd/to/path/salt-vagrant-demo\nvagrant up\n" }, { "code": null, "e": 4037, "s": 3979, "text": "After this command, you will see the following response −" }, { "code": null, "e": 4045, "s": 4037, "text": "result\n" }, { "code": null, "e": 4154, "s": 4045, "text": "Now, three servers are running, one with the salt master configured and two with the salt minion configured." }, { "code": null, "e": 4209, "s": 4154, "text": "Login to the Salt master using the following command −" }, { "code": null, "e": 4229, "s": 4209, "text": "vagrant ssh master\n" }, { "code": null, "e": 4282, "s": 4229, "text": "Now, move to the root user using the command below −" }, { "code": null, "e": 4291, "s": 4282, "text": "sudo su\n" }, { "code": null, "e": 4346, "s": 4291, "text": "Now we have successfully connected to the Salt master." }, { "code": null, "e": 4409, "s": 4346, "text": "Let us now go through some of the basic commands in SaltStack." }, { "code": null, "e": 4538, "s": 4409, "text": "The following command is to verify the Salt minion connections and view whether the connection is accepted, rejected or pending." }, { "code": null, "e": 4557, "s": 4538, "text": "salt-key —list-all" }, { "code": null, "e": 4596, "s": 4557, "text": "It will produce the following output −" }, { "code": null, "e": 4674, "s": 4596, "text": "Accepted Keys:\nminion1\nminion2\nDenied Keys:\n\nUnaccepted Keys:\nRejected Keys:\n" }, { "code": null, "e": 4802, "s": 4674, "text": "Now, we have accepted all the keys, you can send a command from Salt master to check whether Salt minions are listening or not," }, { "code": null, "e": 4822, "s": 4802, "text": "salt '*' test.ping\n" }, { "code": null, "e": 4861, "s": 4822, "text": "It will produce the following output −" }, { "code": null, "e": 4896, "s": 4861, "text": "minion1:\n True\nminion2:\n True\n" }, { "code": null, "e": 5041, "s": 4896, "text": "From the above result, list out minion 1 and minion 2, which means minions are listening properly, otherwise minions might now respond properly." }, { "code": null, "e": 5048, "s": 5041, "text": " Print" }, { "code": null, "e": 5059, "s": 5048, "text": " Add Notes" } ]
F# - Delegates
A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. F# delegates are similar to pointers to functions, in C or C++. Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which have the same signature as that of the delegate. Syntax for delegate declaration is − type delegate-typename = delegate of type1 -> type2 For example, consider the delegates − // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int Both the delegates can be used to reference any method that has two int parameters and returns an int type variable. In the syntax − type1 represents the argument type(s). type1 represents the argument type(s). type2 represents the return type. type2 represents the return type. Please note − The argument types are automatically curried. The argument types are automatically curried. Delegates can be attached to function values, and static or instance methods. Delegates can be attached to function values, and static or instance methods. F# function values can be passed directly as arguments to delegate constructors. F# function values can be passed directly as arguments to delegate constructors. For a static method the delegate is called by using the name of the class and the method. For an instance method, the name of the object instance and method is used. For a static method the delegate is called by using the name of the class and the method. For an instance method, the name of the object instance and method is used. The Invoke method on the delegate type calls the encapsulated function. The Invoke method on the delegate type calls the encapsulated function. Also, delegates can be passed as function values by referencing the Invoke method name without the parentheses. Also, delegates can be passed as function values by referencing the Invoke method name without the parentheses. The following example demonstrates the concept − type Myclass() = static member add(a : int, b : int) = a + b static member sub (a : int) (b : int) = a - b member x.Add(a : int, b : int) = a + b member x.Sub(a : int) (b : int) = a - b // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int let InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) = dlg.Invoke(a, b) let InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) = dlg.Invoke(a, b) // For static methods, use the class name, the dot operator, and the // name of the static method. let del1 : Delegate1 = new Delegate1( Myclass.add ) let del2 : Delegate2 = new Delegate2( Myclass.sub ) let mc = Myclass() // For instance methods, use the instance value name, the dot operator, // and the instance method name. let del3 : Delegate1 = new Delegate1( mc.Add ) let del4 : Delegate2 = new Delegate2( mc.Sub ) for (a, b) in [ (400, 200); (100, 45) ] do printfn "%d + %d = %d" a b (InvokeDelegate1 del1 a b) printfn "%d - %d = %d" a b (InvokeDelegate2 del2 a b) printfn "%d + %d = %d" a b (InvokeDelegate1 del3 a b) printfn "%d - %d = %d" a b (InvokeDelegate2 del4 a b) When you compile and execute the program, it yields the following output − 400 + 200 = 600 400 - 200 = 200 400 + 200 = 600 400 - 200 = 200 100 + 45 = 145 100 - 45 = 55 100 + 45 = 145 100 - 45 = 55 Print Add Notes Bookmark this page
[ { "code": null, "e": 2344, "s": 2161, "text": "A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. F# delegates are similar to pointers to functions, in C or C++." }, { "code": null, "e": 2517, "s": 2344, "text": "Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which have the same signature as that of the delegate." }, { "code": null, "e": 2554, "s": 2517, "text": "Syntax for delegate declaration is −" }, { "code": null, "e": 2607, "s": 2554, "text": "type delegate-typename = delegate of type1 -> type2\n" }, { "code": null, "e": 2645, "s": 2607, "text": "For example, consider the delegates −" }, { "code": null, "e": 2825, "s": 2645, "text": "// Delegate1 works with tuple arguments.\ntype Delegate1 = delegate of (int * int) -> int\n\n// Delegate2 works with curried arguments.\ntype Delegate2 = delegate of int * int -> int\n" }, { "code": null, "e": 2942, "s": 2825, "text": "Both the delegates can be used to reference any method that has two int parameters and returns an int type variable." }, { "code": null, "e": 2958, "s": 2942, "text": "In the syntax −" }, { "code": null, "e": 2997, "s": 2958, "text": "type1 represents the argument type(s)." }, { "code": null, "e": 3036, "s": 2997, "text": "type1 represents the argument type(s)." }, { "code": null, "e": 3070, "s": 3036, "text": "type2 represents the return type." }, { "code": null, "e": 3104, "s": 3070, "text": "type2 represents the return type." }, { "code": null, "e": 3118, "s": 3104, "text": "Please note −" }, { "code": null, "e": 3164, "s": 3118, "text": "The argument types are automatically curried." }, { "code": null, "e": 3210, "s": 3164, "text": "The argument types are automatically curried." }, { "code": null, "e": 3288, "s": 3210, "text": "Delegates can be attached to function values, and static or instance methods." }, { "code": null, "e": 3366, "s": 3288, "text": "Delegates can be attached to function values, and static or instance methods." }, { "code": null, "e": 3447, "s": 3366, "text": "F# function values can be passed directly as arguments to delegate constructors." }, { "code": null, "e": 3528, "s": 3447, "text": "F# function values can be passed directly as arguments to delegate constructors." }, { "code": null, "e": 3694, "s": 3528, "text": "For a static method the delegate is called by using the name of the class and the method. For an instance method, the name of the object instance and method is used." }, { "code": null, "e": 3860, "s": 3694, "text": "For a static method the delegate is called by using the name of the class and the method. For an instance method, the name of the object instance and method is used." }, { "code": null, "e": 3932, "s": 3860, "text": "The Invoke method on the delegate type calls the encapsulated function." }, { "code": null, "e": 4004, "s": 3932, "text": "The Invoke method on the delegate type calls the encapsulated function." }, { "code": null, "e": 4116, "s": 4004, "text": "Also, delegates can be passed as function values by referencing the Invoke method name without the parentheses." }, { "code": null, "e": 4228, "s": 4116, "text": "Also, delegates can be passed as function values by referencing the Invoke method name without the parentheses." }, { "code": null, "e": 4277, "s": 4228, "text": "The following example demonstrates the concept −" }, { "code": null, "e": 5535, "s": 4277, "text": "type Myclass() =\n static member add(a : int, b : int) =\n a + b\n static member sub (a : int) (b : int) =\n a - b\n member x.Add(a : int, b : int) =\n a + b\n member x.Sub(a : int) (b : int) =\n a - b\n\n// Delegate1 works with tuple arguments.\ntype Delegate1 = delegate of (int * int) -> int\n\n// Delegate2 works with curried arguments.\ntype Delegate2 = delegate of int * int -> int\n\nlet InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) =\n dlg.Invoke(a, b)\nlet InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) =\n dlg.Invoke(a, b)\n\n// For static methods, use the class name, the dot operator, and the\n// name of the static method.\nlet del1 : Delegate1 = new Delegate1( Myclass.add )\nlet del2 : Delegate2 = new Delegate2( Myclass.sub )\nlet mc = Myclass()\n\n// For instance methods, use the instance value name, the dot operator, \n// and the instance method name.\n\nlet del3 : Delegate1 = new Delegate1( mc.Add )\nlet del4 : Delegate2 = new Delegate2( mc.Sub )\n\nfor (a, b) in [ (400, 200); (100, 45) ] do\n printfn \"%d + %d = %d\" a b (InvokeDelegate1 del1 a b)\n printfn \"%d - %d = %d\" a b (InvokeDelegate2 del2 a b)\n printfn \"%d + %d = %d\" a b (InvokeDelegate1 del3 a b)\n printfn \"%d - %d = %d\" a b (InvokeDelegate2 del4 a b)" }, { "code": null, "e": 5610, "s": 5535, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 5733, "s": 5610, "text": "400 + 200 = 600\n400 - 200 = 200\n400 + 200 = 600\n400 - 200 = 200\n100 + 45 = 145\n100 - 45 = 55\n100 + 45 = 145\n100 - 45 = 55\n" }, { "code": null, "e": 5740, "s": 5733, "text": " Print" }, { "code": null, "e": 5751, "s": 5740, "text": " Add Notes" } ]
C# program to determine if a string has all unique characters
Use the substring() method in C# to check each and every substring for unique characters. Loop it until the length of the string. If any one the substring matches another, then it would mean that the string do not have unique characters. You can try to run the following code to determine if a string has all unique characters. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Demo { public bool CheckUnique(string str) { string one = ""; string two = ""; for (int i = 0; i < str.Length; i++) { one = str.Substring(i, 1); for (int j = 0; j < str.Length; j++) { two = str.Substring(j, 1); if ((one == two) && (i != j)) return false; } } return true; } static void Main(string[] args) { Demo d = new Demo(); bool b = d.CheckUnique("amit"); Console.WriteLine(b); Console.ReadKey(); } } True
[ { "code": null, "e": 1192, "s": 1062, "text": "Use the substring() method in C# to check each and every substring for unique characters. Loop it until the length of the string." }, { "code": null, "e": 1300, "s": 1192, "text": "If any one the substring matches another, then it would mean that the string do not have unique characters." }, { "code": null, "e": 1390, "s": 1300, "text": "You can try to run the following code to determine if a string has all unique characters." }, { "code": null, "e": 1401, "s": 1390, "text": " Live Demo" }, { "code": null, "e": 2065, "s": 1401, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\npublic class Demo {\n public bool CheckUnique(string str) {\n string one = \"\";\n string two = \"\";\n for (int i = 0; i < str.Length; i++) {\n one = str.Substring(i, 1);\n for (int j = 0; j < str.Length; j++) {\n two = str.Substring(j, 1);\n if ((one == two) && (i != j))\n return false;\n }\n }\n return true;\n }\n static void Main(string[] args) {\n Demo d = new Demo();\n bool b = d.CheckUnique(\"amit\");\n Console.WriteLine(b);\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 2070, "s": 2065, "text": "True" } ]
How can I set an ImageView's width and height programmatically in Android?
This example demonstrates about How can I set an ImageView's width and height programmatically in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:id="@+id/rlMain" android:layout_height="match_parent" android:layout_margin="16dp" /> Step 3 − Add the following code to src/MainActivity.java package app.com.sample; import android.os.Bundle; import android.widget.ImageView; import android.widget.RelativeLayout; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RelativeLayout rlMain = findViewById(R.id.rlMain); ImageView imageView = new ImageView(this); imageView.setImageResource(R.drawable.ic_launcher_background); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT ); imageView.setLayoutParams(params); rlMain.addView(imageView); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1168, "s": 1062, "text": "This example demonstrates about How can I set an ImageView's width and height programmatically in Android" }, { "code": null, "e": 1297, "s": 1168, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1362, "s": 1297, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1618, "s": 1362, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:id=\"@+id/rlMain\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\" />" }, { "code": null, "e": 1675, "s": 1618, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2498, "s": 1675, "text": "package app.com.sample;\nimport android.os.Bundle;\nimport android.widget.ImageView;\nimport android.widget.RelativeLayout;\nimport androidx.appcompat.app.AppCompatActivity;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n RelativeLayout rlMain = findViewById(R.id.rlMain);\n ImageView imageView = new ImageView(this);\n imageView.setImageResource(R.drawable.ic_launcher_background);\n RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.MATCH_PARENT\n );\n imageView.setLayoutParams(params);\n rlMain.addView(imageView);\n }\n}" }, { "code": null, "e": 2553, "s": 2498, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3223, "s": 2553, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3570, "s": 3223, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3611, "s": 3570, "text": "Click here to download the project code." } ]
How to set href attribute at runtime? - GeeksforGeeks
29 Jul, 2021 We know how to set the href attribute of the anchor tag int HTML, but sometimes we may require to set the the href attribute at runtime i.e. for example, when a user provides us a url and we want to set it at runtime. We can do this with the help of jQuery. Example 1: In this example, using jquery, we set the attr() method to the url entered by the user in the input tag, when user clicks the set href button. html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <script src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <title>Set href attribute at runtime</title> <style> #btn { background-color: #4caf50; color: white; } input { color: #4caf50; } a { color: #4caf50; } h1 { color: green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <b>Set href attribute at runtime</b> <br> <input type="text" name="url" /> <button id="btn">Set href</button> <button> <a id="click" href="#" target="_blank"> link </a> </button> </center> </body> <script> $(document).ready(function () { $("#btn").click(function () { $("#click").attr("href", $('input[name$="url"]').val()); }); }); </script></html> Output: Example 2: In this example, we replace the anchor tag in the div ‘link’ with another anchor tag to change the href value. This is another way in which we can change the value of the href attribute. html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <script src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <title>Set href attribute at runtime</title> <style> #btn { background-color: #4caf50; color: white; } input { color: #4caf50; } a { color: #4caf50; } h1 { color: green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <b>Set href attribute at runtime</b> <br> <div id="link"> <a id="click" href="https://practice.geeksforgeeks.org/" target="_blank"> https://practice.geeksforgeeks.org/ </a> <button id="btn">Change url</button> </div> </center> </body> <script> $(document).ready(function () { $("#btn").click(function () { $("#link").html("<a href='https://www.geeksforgeeks.org/'> https://www.geeksforgeeks.org</a>"); alert("Url changed to https://www.geeksforgeeks.org/"); }); }); </script></html> Output: sagartomar9927 jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method How to get the value in an input text box using jQuery ? jQuery | parent() & parents() with Examples Difference Between JavaScript and jQuery Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript
[ { "code": null, "e": 25755, "s": 25727, "text": "\n29 Jul, 2021" }, { "code": null, "e": 26014, "s": 25755, "text": "We know how to set the href attribute of the anchor tag int HTML, but sometimes we may require to set the the href attribute at runtime i.e. for example, when a user provides us a url and we want to set it at runtime. We can do this with the help of jQuery. " }, { "code": null, "e": 26170, "s": 26014, "text": "Example 1: In this example, using jquery, we set the attr() method to the url entered by the user in the input tag, when user clicks the set href button. " }, { "code": null, "e": 26175, "s": 26170, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <script src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <title>Set href attribute at runtime</title> <style> #btn { background-color: #4caf50; color: white; } input { color: #4caf50; } a { color: #4caf50; } h1 { color: green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <b>Set href attribute at runtime</b> <br> <input type=\"text\" name=\"url\" /> <button id=\"btn\">Set href</button> <button> <a id=\"click\" href=\"#\" target=\"_blank\"> link </a> </button> </center> </body> <script> $(document).ready(function () { $(\"#btn\").click(function () { $(\"#click\").attr(\"href\", $('input[name$=\"url\"]').val()); }); }); </script></html>", "e": 27489, "s": 26175, "text": null }, { "code": null, "e": 27497, "s": 27489, "text": "Output:" }, { "code": null, "e": 27697, "s": 27497, "text": "Example 2: In this example, we replace the anchor tag in the div ‘link’ with another anchor tag to change the href value. This is another way in which we can change the value of the href attribute. " }, { "code": null, "e": 27702, "s": 27697, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <script src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <title>Set href attribute at runtime</title> <style> #btn { background-color: #4caf50; color: white; } input { color: #4caf50; } a { color: #4caf50; } h1 { color: green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <b>Set href attribute at runtime</b> <br> <div id=\"link\"> <a id=\"click\" href=\"https://practice.geeksforgeeks.org/\" target=\"_blank\"> https://practice.geeksforgeeks.org/ </a> <button id=\"btn\">Change url</button> </div> </center> </body> <script> $(document).ready(function () { $(\"#btn\").click(function () { $(\"#link\").html(\"<a href='https://www.geeksforgeeks.org/'> https://www.geeksforgeeks.org</a>\"); alert(\"Url changed to https://www.geeksforgeeks.org/\"); }); }); </script></html>", "e": 29149, "s": 27702, "text": null }, { "code": null, "e": 29157, "s": 29149, "text": "Output:" }, { "code": null, "e": 29172, "s": 29157, "text": "sagartomar9927" }, { "code": null, "e": 29184, "s": 29172, "text": "jQuery-Misc" }, { "code": null, "e": 29191, "s": 29184, "text": "Picked" }, { "code": null, "e": 29198, "s": 29191, "text": "JQuery" }, { "code": null, "e": 29215, "s": 29198, "text": "Web Technologies" }, { "code": null, "e": 29242, "s": 29215, "text": "Web technologies Questions" }, { "code": null, "e": 29340, "s": 29242, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29413, "s": 29340, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 29436, "s": 29413, "text": "jQuery | ajax() Method" }, { "code": null, "e": 29493, "s": 29436, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 29537, "s": 29493, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 29578, "s": 29537, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 29620, "s": 29578, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29653, "s": 29620, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29715, "s": 29653, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29758, "s": 29715, "text": "How to fetch data from an API in ReactJS ?" } ]
Arduino - millis () function
This function is used to return the number of milliseconds at the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 50 days. millis () ; This function returns milliseconds from the start of the program. unsigned long time; void setup() { Serial.begin(9600); } void loop() { Serial.print("Time:"); time = millis(); //prints time since program started Serial.println(time); // wait a second so as not to send massive amounts of data delay(1000); } 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3070, "s": 2870, "text": "This function is used to return the number of milliseconds at the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 50 days." }, { "code": null, "e": 3083, "s": 3070, "text": "millis () ;\n" }, { "code": null, "e": 3149, "s": 3083, "text": "This function returns milliseconds from the start of the program." }, { "code": null, "e": 3417, "s": 3149, "text": "unsigned long time; void setup() { \n Serial.begin(9600); \n} \n\nvoid loop() { \n Serial.print(\"Time:\"); time = millis();\n //prints time since program started\n Serial.println(time); \n // wait a second so as not to send massive amounts of data\n delay(1000); \n}" }, { "code": null, "e": 3452, "s": 3417, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3463, "s": 3452, "text": " Amit Rana" }, { "code": null, "e": 3496, "s": 3463, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 3507, "s": 3496, "text": " Amit Rana" }, { "code": null, "e": 3540, "s": 3507, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3553, "s": 3540, "text": " Ashraf Said" }, { "code": null, "e": 3588, "s": 3553, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3601, "s": 3588, "text": " Ashraf Said" }, { "code": null, "e": 3633, "s": 3601, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 3646, "s": 3633, "text": " Ashraf Said" }, { "code": null, "e": 3677, "s": 3646, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 3690, "s": 3677, "text": " Ashraf Said" }, { "code": null, "e": 3697, "s": 3690, "text": " Print" }, { "code": null, "e": 3708, "s": 3697, "text": " Add Notes" } ]
Plot a circle with an edgecolor in Matplotlib
To plot a circle with an edgecolor in matplotlib, we can take the following Steps − Create a new figure or activate an existing figure using figure() method. Create a new figure or activate an existing figure using figure() method. Add a subplot method to the current axis. Add a subplot method to the current axis. Create a circle instance using Circle() class with an edgecolor and linewidth of the edge. Create a circle instance using Circle() class with an edgecolor and linewidth of the edge. Add a circle path on the plot. Add a circle path on the plot. To place the text in the circle, we can use text() method. To place the text in the circle, we can use text() method. Scale the X and Y axes using xlim() and ylim() methods. Scale the X and Y axes using xlim() and ylim() methods. To display the figure, use show() method. To display the figure, use show() method. import matplotlib from matplotlib import pyplot as plt, patches plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = fig.add_subplot(111) circle = matplotlib.patches.Circle((0, 0), radius=1, edgecolor="orange", linewidth=7) ax.add_patch(circle) plt.text(-.25, 0, "Circle") plt.xlim([-4, 4]) plt.ylim([-4, 4]) plt.axis('equal') plt.show()
[ { "code": null, "e": 1146, "s": 1062, "text": "To plot a circle with an edgecolor in matplotlib, we can take the following Steps −" }, { "code": null, "e": 1220, "s": 1146, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1294, "s": 1220, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1336, "s": 1294, "text": "Add a subplot method to the current axis." }, { "code": null, "e": 1378, "s": 1336, "text": "Add a subplot method to the current axis." }, { "code": null, "e": 1469, "s": 1378, "text": "Create a circle instance using Circle() class with an edgecolor and linewidth of the edge." }, { "code": null, "e": 1560, "s": 1469, "text": "Create a circle instance using Circle() class with an edgecolor and linewidth of the edge." }, { "code": null, "e": 1591, "s": 1560, "text": "Add a circle path on the plot." }, { "code": null, "e": 1622, "s": 1591, "text": "Add a circle path on the plot." }, { "code": null, "e": 1681, "s": 1622, "text": "To place the text in the circle, we can use text() method." }, { "code": null, "e": 1740, "s": 1681, "text": "To place the text in the circle, we can use text() method." }, { "code": null, "e": 1796, "s": 1740, "text": "Scale the X and Y axes using xlim() and ylim() methods." }, { "code": null, "e": 1852, "s": 1796, "text": "Scale the X and Y axes using xlim() and ylim() methods." }, { "code": null, "e": 1894, "s": 1852, "text": "To display the figure, use show() method." }, { "code": null, "e": 1936, "s": 1894, "text": "To display the figure, use show() method." }, { "code": null, "e": 2332, "s": 1936, "text": "import matplotlib\nfrom matplotlib import pyplot as plt, patches\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig = plt.figure()\nax = fig.add_subplot(111)\ncircle = matplotlib.patches.Circle((0, 0), radius=1, edgecolor=\"orange\", linewidth=7)\nax.add_patch(circle)\nplt.text(-.25, 0, \"Circle\")\nplt.xlim([-4, 4])\nplt.ylim([-4, 4])\nplt.axis('equal')\nplt.show()" } ]
How to draw a filled circle in OpenCV using Java?
The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. This class provides a method named circle(), using this you can draw a circle on an image. This method provides the following parameters − A Mat object representing the image on which the circle is to be drawn. A Mat object representing the image on which the circle is to be drawn. A Point object representing the center of the circle. A Point object representing the center of the circle. An integer variable representing the radius of the circle. An integer variable representing the radius of the circle. A Scalar object representing the color of the circle(BGR). A Scalar object representing the color of the circle(BGR). An integer representing the thickness of the circle(default 1). An integer representing the thickness of the circle(default 1). If you pass Imgproc.FILLEDas line type, this method generates/draws a filled circle. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class DrawingFilledCircle { public static void main(String args[]) { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the source image in to a Mat object Mat src = Imgcodecs.imread("D:\\images\\blank.jpg"); //Drawing a Circle Point center = new Point(300, 200); int radius =100; Scalar color = new Scalar(64, 64, 64); int thickness = Imgproc.FILLED; Imgproc.circle (src, center, radius, color, thickness); //Saving and displaying the image Imgcodecs.imwrite("arrowed_line.jpg", src); HighGui.imshow("Drawing a circle", src); HighGui.waitKey(); } } On executing, the above program generates the following window −
[ { "code": null, "e": 1287, "s": 1062, "text": "The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. This class provides a method named circle(), using this you can draw a\ncircle on an image. This method provides the following parameters −" }, { "code": null, "e": 1359, "s": 1287, "text": "A Mat object representing the image on which the circle is to be drawn." }, { "code": null, "e": 1431, "s": 1359, "text": "A Mat object representing the image on which the circle is to be drawn." }, { "code": null, "e": 1485, "s": 1431, "text": "A Point object representing the center of the circle." }, { "code": null, "e": 1539, "s": 1485, "text": "A Point object representing the center of the circle." }, { "code": null, "e": 1598, "s": 1539, "text": "An integer variable representing the radius of the circle." }, { "code": null, "e": 1657, "s": 1598, "text": "An integer variable representing the radius of the circle." }, { "code": null, "e": 1716, "s": 1657, "text": "A Scalar object representing the color of the circle(BGR)." }, { "code": null, "e": 1775, "s": 1716, "text": "A Scalar object representing the color of the circle(BGR)." }, { "code": null, "e": 1839, "s": 1775, "text": "An integer representing the thickness of the circle(default 1)." }, { "code": null, "e": 1903, "s": 1839, "text": "An integer representing the thickness of the circle(default 1)." }, { "code": null, "e": 1988, "s": 1903, "text": "If you pass Imgproc.FILLEDas line type, this method generates/draws a filled circle." }, { "code": null, "e": 2997, "s": 1988, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class DrawingFilledCircle {\n public static void main(String args[]) {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the source image in to a Mat object\n Mat src = Imgcodecs.imread(\"D:\\\\images\\\\blank.jpg\");\n //Drawing a Circle\n Point center = new Point(300, 200);\n int radius =100;\n Scalar color = new Scalar(64, 64, 64);\n int thickness = Imgproc.FILLED;\n Imgproc.circle (src, center, radius, color, thickness);\n //Saving and displaying the image\n Imgcodecs.imwrite(\"arrowed_line.jpg\", src);\n HighGui.imshow(\"Drawing a circle\", src);\n HighGui.waitKey();\n }\n}" }, { "code": null, "e": 3062, "s": 2997, "text": "On executing, the above program generates the following window −" } ]
How to write a MySQL stored function that inserts values in a table?
As we know that function is best used when we want to return a result. Hence, when we will create stored functions for manipulating tables like to Insert or Update values then it would be more or less like stored procedures. In the following example we are creating a stored function named ‘tbl_insert’ which will insert the values in a table named ‘student_marks’. mysql> Create Function tbl_insert(S_name Varchar(50),M1 INT,M2 INT,M3 INT,M4 INT) -> RETURNS INT -> DETERMINISTIC -> BEGIN -> INSERT INTO student_marks values(S_name,M1,M2,M3,M4); -> RETURN 1; -> END// Query OK, 0 rows affected (0.00 sec) mysql> Select tbl_insert('Saurabh',85,79,65,71); +------------------------------+ | tbl_insert('RR',58,25,65,32) | +------------------------------+ | 1 | +------------------------------+ 1 row in set (0.07 sec) mysql> Select * from student_marks; +---------+------+---------+---------+---------+ | Name | Math | English | Science | History | +---------+------+---------+---------+---------+ | Raman | 95 | 89 | 85 | 81 | | Rahul | 90 | 87 | 86 | 81 | | Mohit | 90 | NULL | 86 | 81 | | Saurabh | 85 | 79 | 65 | 71 | +---------+------+---------+---------+---------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1287, "s": 1062, "text": "As we know that function is best used when we want to return a result. Hence, when we will create stored functions for manipulating tables like to Insert or Update values then it would be more or less like stored procedures." }, { "code": null, "e": 1428, "s": 1287, "text": "In the following example we are creating a stored function named ‘tbl_insert’ which will insert the values in a table named ‘student_marks’." }, { "code": null, "e": 2384, "s": 1428, "text": "mysql> Create Function tbl_insert(S_name Varchar(50),M1 INT,M2 INT,M3 INT,M4 INT)\n -> RETURNS INT\n -> DETERMINISTIC\n -> BEGIN\n -> INSERT INTO student_marks values(S_name,M1,M2,M3,M4);\n -> RETURN 1;\n -> END//\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select tbl_insert('Saurabh',85,79,65,71);\n+------------------------------+\n| tbl_insert('RR',58,25,65,32) |\n+------------------------------+\n| 1 |\n+------------------------------+\n1 row in set (0.07 sec)\n\nmysql> Select * from student_marks;\n+---------+------+---------+---------+---------+\n| Name | Math | English | Science | History |\n+---------+------+---------+---------+---------+\n| Raman | 95 | 89 | 85 | 81 |\n| Rahul | 90 | 87 | 86 | 81 |\n| Mohit | 90 | NULL | 86 | 81 |\n| Saurabh | 85 | 79 | 65 | 71 |\n+---------+------+---------+---------+---------+\n4 rows in set (0.00 sec)" } ]
Java DIP - GrayScale Conversion
In order to convert a color image to Grayscale image, you need to read pixels or data of the image using File and ImageIO objects, and store the image in BufferedImage object. Its syntax is given below − File input = new File("digital_image_processing.jpg"); BufferedImage image = ImageIO.read(input); Further, get the pixel value using method getRGB() and perform GrayScale() method on it. The method getRGB() takes row and column index as parameter. Color c = new Color(image.getRGB(j, i)); int red = (c.getRed() * 0.299); int green =(c.getGreen() * 0.587); int blue = (c.getBlue() *0.114); Apart from these three methods, there are other methods available in the Color class as described briefly − brighter() It creates a new Color that is a brighter version of this Color. darker() It creates a new Color that is a darker version of this Color. getAlpha() It returns the alpha component in the range 0-255. getHSBColor(float h, float s, float b) It creates a Color object based on the specified values for the HSB color model. HSBtoRGB(float hue, float saturation, float brightness) It converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model. toString() It returns a string representation of this Color. The last step is to add all these three values and set it again to the corresponding pixel value. Its syntax is given below − int sum = red+green+blue; Color newColor = new Color(sum,sum,sum); image.setRGB(j,i,newColor.getRGB()); The following example demonstrates the use of Java BufferedImage class that converts an image to Grayscale − import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.JFrame; public class GrayScale { BufferedImage image; int width; int height; public GrayScale() { try { File input = new File("digital_image_processing.jpg"); image = ImageIO.read(input); width = image.getWidth(); height = image.getHeight(); for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { Color c = new Color(image.getRGB(j, i)); int red = (int)(c.getRed() * 0.299); int green = (int)(c.getGreen() * 0.587); int blue = (int)(c.getBlue() *0.114); Color newColor = new Color(red+green+blue, red+green+blue,red+green+blue); image.setRGB(j,i,newColor.getRGB()); } } File ouptut = new File("grayscale.jpg"); ImageIO.write(image, "jpg", ouptut); } catch (Exception e) {} } static public void main(String args[]) throws Exception { GrayScale obj = new GrayScale(); } } When you execute the given example, it converts the image digital_image_processing.jpg to its equivalent Grayscale image and write it on hard disk with the name grayscale.jpg. 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": 2541, "s": 2337, "text": "In order to convert a color image to Grayscale image, you need to read pixels or data of the image using File and ImageIO objects, and store the image in BufferedImage object. Its syntax is given below −" }, { "code": null, "e": 2641, "s": 2541, "text": "File input = new File(\"digital_image_processing.jpg\");\nBufferedImage image = ImageIO.read(input);\t\n" }, { "code": null, "e": 2791, "s": 2641, "text": "Further, get the pixel value using method getRGB() and perform GrayScale() method on it. The method getRGB() takes row and column index as parameter." }, { "code": null, "e": 2933, "s": 2791, "text": "Color c = new Color(image.getRGB(j, i));\nint red = (c.getRed() * 0.299);\nint green =(c.getGreen() * 0.587);\nint blue = (c.getBlue() *0.114);\n" }, { "code": null, "e": 3041, "s": 2933, "text": "Apart from these three methods, there are other methods available in the Color class as described briefly −" }, { "code": null, "e": 3052, "s": 3041, "text": "brighter()" }, { "code": null, "e": 3117, "s": 3052, "text": "It creates a new Color that is a brighter version of this Color." }, { "code": null, "e": 3126, "s": 3117, "text": "darker()" }, { "code": null, "e": 3189, "s": 3126, "text": "It creates a new Color that is a darker version of this Color." }, { "code": null, "e": 3200, "s": 3189, "text": "getAlpha()" }, { "code": null, "e": 3251, "s": 3200, "text": "It returns the alpha component in the range 0-255." }, { "code": null, "e": 3290, "s": 3251, "text": "getHSBColor(float h, float s, float b)" }, { "code": null, "e": 3371, "s": 3290, "text": "It creates a Color object based on the specified values for the HSB color model." }, { "code": null, "e": 3427, "s": 3371, "text": "HSBtoRGB(float hue, float saturation, float brightness)" }, { "code": null, "e": 3555, "s": 3427, "text": "It converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model." }, { "code": null, "e": 3566, "s": 3555, "text": "toString()" }, { "code": null, "e": 3616, "s": 3566, "text": "It returns a string representation of this Color." }, { "code": null, "e": 3742, "s": 3616, "text": "The last step is to add all these three values and set it again to the corresponding pixel value. Its syntax is given below −" }, { "code": null, "e": 3847, "s": 3742, "text": "int sum = red+green+blue;\nColor newColor = new Color(sum,sum,sum);\nimage.setRGB(j,i,newColor.getRGB());\n" }, { "code": null, "e": 3956, "s": 3847, "text": "The following example demonstrates the use of Java BufferedImage class that converts an image to Grayscale −" }, { "code": null, "e": 5195, "s": 3956, "text": "import java.awt.*;\nimport java.awt.image.BufferedImage;\n\nimport java.io.*;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class GrayScale {\n\n BufferedImage image;\n int width;\n int height;\n \n public GrayScale() {\n \n try {\n File input = new File(\"digital_image_processing.jpg\");\n image = ImageIO.read(input);\n width = image.getWidth();\n height = image.getHeight();\n \n for(int i=0; i<height; i++) {\n \n for(int j=0; j<width; j++) {\n \n Color c = new Color(image.getRGB(j, i));\n int red = (int)(c.getRed() * 0.299);\n int green = (int)(c.getGreen() * 0.587);\n int blue = (int)(c.getBlue() *0.114);\n Color newColor = new Color(red+green+blue,\n \n red+green+blue,red+green+blue);\n \n image.setRGB(j,i,newColor.getRGB());\n }\n }\n \n File ouptut = new File(\"grayscale.jpg\");\n ImageIO.write(image, \"jpg\", ouptut);\n \n } catch (Exception e) {}\n }\n \n static public void main(String args[]) throws Exception {\n GrayScale obj = new GrayScale();\n }\n}" }, { "code": null, "e": 5371, "s": 5195, "text": "When you execute the given example, it converts the image digital_image_processing.jpg to its equivalent Grayscale image and write it on hard disk with the name grayscale.jpg." }, { "code": null, "e": 5404, "s": 5371, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5420, "s": 5404, "text": " Malhar Lathkar" }, { "code": null, "e": 5453, "s": 5420, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5469, "s": 5453, "text": " Malhar Lathkar" }, { "code": null, "e": 5504, "s": 5469, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5518, "s": 5504, "text": " Anadi Sharma" }, { "code": null, "e": 5552, "s": 5518, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5566, "s": 5552, "text": " Tushar Kale" }, { "code": null, "e": 5603, "s": 5566, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5618, "s": 5603, "text": " Monica Mittal" }, { "code": null, "e": 5651, "s": 5618, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5670, "s": 5651, "text": " Arnab Chakraborty" }, { "code": null, "e": 5677, "s": 5670, "text": " Print" }, { "code": null, "e": 5688, "s": 5677, "text": " Add Notes" } ]
Python Bokeh - Plotting Triangles on a Graph - GeeksforGeeks
10 Jul, 2020 Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot triangles on a graph. Plotting triangles on a graph can be done using the triangle() method of the plotting module. Syntax : triangle(parameters) Parameters : x : x-coordinates of the center of the triangle markers y : y-coordinates of the center of the triangle markers Returns : an object of class GlyphRenderer Example 1 : In this example we will be using the default values for plotting the graph. # importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Triangle Graph") # the points to be plottedx = 0y = 0 # plotting the graphgraph.triangle(x, y, size = 30) # displaying the modelshow(graph) Output : Example 2 : In this example we will be plotting multiple triangles with various other parameters. # importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Triangle Graph") # name of the x-axis graph.xaxis.axis_label = "x-axis" # name of the y-axis graph.yaxis.axis_label = "y-axis" # points to be plottedx = [3, 3, 5]y = [3, 1, 3]size = [130, 100, 60] # color value of the trianglescolor = ["yellow", "red", "purple"] # fill alpha value of the trianglesfill_alpha = [0.9, 0.7, 0.5] # plotting the graph graph.triangle(x, y, size = size, color = color, fill_alpha = fill_alpha) # displaying the model show(graph) Output : Data Visualization Python Bokeh-plotting-figure-class Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 24320, "s": 24292, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24561, "s": 24320, "text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity." }, { "code": null, "e": 24703, "s": 24561, "text": "Bokeh can be used to plot triangles on a graph. Plotting triangles on a graph can be done using the triangle() method of the plotting module." }, { "code": null, "e": 24733, "s": 24703, "text": "Syntax : triangle(parameters)" }, { "code": null, "e": 24746, "s": 24733, "text": "Parameters :" }, { "code": null, "e": 24802, "s": 24746, "text": "x : x-coordinates of the center of the triangle markers" }, { "code": null, "e": 24858, "s": 24802, "text": "y : y-coordinates of the center of the triangle markers" }, { "code": null, "e": 24901, "s": 24858, "text": "Returns : an object of class GlyphRenderer" }, { "code": null, "e": 24989, "s": 24901, "text": "Example 1 : In this example we will be using the default values for plotting the graph." }, { "code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Triangle Graph\") # the points to be plottedx = 0y = 0 # plotting the graphgraph.triangle(x, y, size = 30) # displaying the modelshow(graph) ", "e": 25350, "s": 24989, "text": null }, { "code": null, "e": 25359, "s": 25350, "text": "Output :" }, { "code": null, "e": 25457, "s": 25359, "text": "Example 2 : In this example we will be plotting multiple triangles with various other parameters." }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Triangle Graph\") # name of the x-axis graph.xaxis.axis_label = \"x-axis\" # name of the y-axis graph.yaxis.axis_label = \"y-axis\" # points to be plottedx = [3, 3, 5]y = [3, 1, 3]size = [130, 100, 60] # color value of the trianglescolor = [\"yellow\", \"red\", \"purple\"] # fill alpha value of the trianglesfill_alpha = [0.9, 0.7, 0.5] # plotting the graph graph.triangle(x, y, size = size, color = color, fill_alpha = fill_alpha) # displaying the model show(graph)", "e": 26183, "s": 25457, "text": null }, { "code": null, "e": 26192, "s": 26183, "text": "Output :" }, { "code": null, "e": 26211, "s": 26192, "text": "Data Visualization" }, { "code": null, "e": 26246, "s": 26211, "text": "Python Bokeh-plotting-figure-class" }, { "code": null, "e": 26259, "s": 26246, "text": "Python-Bokeh" }, { "code": null, "e": 26266, "s": 26259, "text": "Python" }, { "code": null, "e": 26364, "s": 26266, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26373, "s": 26364, "text": "Comments" }, { "code": null, "e": 26386, "s": 26373, "text": "Old Comments" }, { "code": null, "e": 26414, "s": 26386, "text": "Read JSON file using Python" }, { "code": null, "e": 26464, "s": 26414, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26486, "s": 26464, "text": "Python map() function" }, { "code": null, "e": 26530, "s": 26486, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26548, "s": 26530, "text": "Python Dictionary" }, { "code": null, "e": 26571, "s": 26548, "text": "Taking input in Python" }, { "code": null, "e": 26606, "s": 26571, "text": "Read a file line by line in Python" }, { "code": null, "e": 26628, "s": 26606, "text": "Enumerate() in Python" }, { "code": null, "e": 26660, "s": 26628, "text": "How to Install PIP on Windows ?" } ]
JasmineJS - Equality Check
Jasmine provides plenty of methods which help us check the equality of any JavaScript function and file. Following are some examples to check equality conditions. ToEqual() is the simplest matcher present in the inbuilt library of Jasmine. It just matches whether the result of the operation given as an argument to this method matches with the result of it or not. The following example will help you understand how this matcher works. We have two files to be tested named as “expectexam.js” and another one through which we need to test is “expectSpec.js”. window.expectexam = { currentVal: 0, }; describe("Different Methods of Expect Block",function () { it("The Example of toEqual() method",function () { //this will check whether the value of the variable // currentVal is equal to 0 or not. expect(expectexam.currentVal).toEqual(0); }); }); On successful execution, these pieces of code will yield the following output. Remember you need to add these files into the header section of specRunner.html file as directed in the earlier example. not.toEqual() works exactly opposite to toEqual(). not.toEqual() is used when we need to check if the value does not match with the output of any function. We will modify the above example to show how this works. describe("Different Methods of Expect Block",function () { it("The Example of toEqual() method",function () { expect(expectexam.currentVal).toEqual(0); }); it("The Example of not.toEqual() method",function () { //negation testing expect(expectexam.currentVal).not.toEqual(5); }); }); window.expectexam = { currentVal: 0, }; In the second expect block, we are checking whether the value of the currentVal is equal to 5 as the value of currentVal is zero hence our test passes and provides us with a green output. toBe() matcher works in a similar way as toEqual(), however they are technically different from each other. toBe() matcher matches with the type of the object whereas toEqual() matches with the equivalency of the result. The following example will help you understand the working principle of the toBe() matcher. This matcher is exactly equivalent to the “===” operator of JavaScript whereas toEqual() is similar to the “==” operator of JavaScript. describe("Different Methods of Expect Block",function () { it("The Example of toBe() method",function () { expect(expectexam.name).toBe(expectexam.name1); }); }); window.expectexam = { currentVal: 0, name:"tutorialspoint", name1:tutorialspoint }; We will slightly modify our expectexam JavaScript file. We added two new variables, name and name1. Please find the difference between these two added variables - one is of string type and another one is not a string type. Following screenshot is our test result where the red cross depicts that these two values are not equal, whereas it is expected to be equal. Hence our test fails. Let us turn both the variables, name and name1 as String type variables and run the same SpecRunner.html again. Now check the output. It will prove that toBe() not only matches with the equivalency of the variable, but it also matches with the data type or object type of the variable. As seen earlier, not is nothing but a negation of the toBe() method. It fails when the expected result matches with the actual output of the function or JavaScript file. Following is a simple example that will help you understand how not.toBe() matcher works. describe("Different Methods of Expect Block",function () { it("The Example of not.toBe() method",function () { expect(true).not.toBe(false); }); }); Here Jasmine will try to match up true with false. As true cannot be same as false, this test case will be valid and pass through. Print Add Notes Bookmark this page
[ { "code": null, "e": 2213, "s": 2050, "text": "Jasmine provides plenty of methods which help us check the equality of any JavaScript function and file. Following are some examples to check equality conditions." }, { "code": null, "e": 2416, "s": 2213, "text": "ToEqual() is the simplest matcher present in the inbuilt library of Jasmine. It just matches whether the result of the operation given as an argument to this method matches with the result of it or not." }, { "code": null, "e": 2609, "s": 2416, "text": "The following example will help you understand how this matcher works. We have two files to be tested named as “expectexam.js” and another one through which we need to test is “expectSpec.js”." }, { "code": null, "e": 2659, "s": 2609, "text": "window.expectexam = { \n currentVal: 0, \n};" }, { "code": null, "e": 2945, "s": 2659, "text": "describe(\"Different Methods of Expect Block\",function () { \n \n it(\"The Example of toEqual() method\",function () { \n //this will check whether the value of the variable \n // currentVal is equal to 0 or not. \n expect(expectexam.currentVal).toEqual(0); \n });\n});" }, { "code": null, "e": 3145, "s": 2945, "text": "On successful execution, these pieces of code will yield the following output. Remember you need to add these files into the header section of specRunner.html file as directed in the earlier example." }, { "code": null, "e": 3301, "s": 3145, "text": "not.toEqual() works exactly opposite to toEqual(). not.toEqual() is used when we need to check if the value does not match with the output of any function." }, { "code": null, "e": 3358, "s": 3301, "text": "We will modify the above example to show how this works." }, { "code": null, "e": 3682, "s": 3358, "text": "describe(\"Different Methods of Expect Block\",function () { \n\n it(\"The Example of toEqual() method\",function () {\n expect(expectexam.currentVal).toEqual(0); \n }); \n \n it(\"The Example of not.toEqual() method\",function () { \n //negation testing expect(expectexam.currentVal).not.toEqual(5); \n }); \n});" }, { "code": null, "e": 3729, "s": 3682, "text": "window.expectexam = { \n currentVal: 0, \n}; " }, { "code": null, "e": 3917, "s": 3729, "text": "In the second expect block, we are checking whether the value of the currentVal is equal to 5 as the value of currentVal is zero hence our test passes and provides us with a green output." }, { "code": null, "e": 4138, "s": 3917, "text": "toBe() matcher works in a similar way as toEqual(), however they are technically different from each other. toBe() matcher matches with the type of the object whereas toEqual() matches with the equivalency of the result." }, { "code": null, "e": 4366, "s": 4138, "text": "The following example will help you understand the working principle of the toBe() matcher. This matcher is exactly equivalent to the “===” operator of JavaScript whereas toEqual() is similar to the “==” operator of JavaScript." }, { "code": null, "e": 4550, "s": 4366, "text": "describe(\"Different Methods of Expect Block\",function () { \n\n it(\"The Example of toBe() method\",function () { \n expect(expectexam.name).toBe(expectexam.name1); \n });\n});" }, { "code": null, "e": 4647, "s": 4550, "text": "window.expectexam = {\n currentVal: 0, \n name:\"tutorialspoint\", \n name1:tutorialspoint \n};" }, { "code": null, "e": 4870, "s": 4647, "text": "We will slightly modify our expectexam JavaScript file. We added two new variables, name and name1. Please find the difference between these two added variables - one is of string type and another one is not a string type." }, { "code": null, "e": 5033, "s": 4870, "text": "Following screenshot is our test result where the red cross depicts that these two values are not equal, whereas it is expected to be equal. Hence our test fails." }, { "code": null, "e": 5319, "s": 5033, "text": "Let us turn both the variables, name and name1 as String type variables and run the same SpecRunner.html again. Now check the output. It will prove that toBe() not only matches with the equivalency of the variable, but it also matches with the data type or object type of the variable." }, { "code": null, "e": 5489, "s": 5319, "text": "As seen earlier, not is nothing but a negation of the toBe() method. It fails when the expected result matches with the actual output of the function or JavaScript file." }, { "code": null, "e": 5579, "s": 5489, "text": "Following is a simple example that will help you understand how not.toBe() matcher works." }, { "code": null, "e": 5746, "s": 5579, "text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"The Example of not.toBe() method\",function () { \n expect(true).not.toBe(false); \n });\n});" }, { "code": null, "e": 5877, "s": 5746, "text": "Here Jasmine will try to match up true with false. As true cannot be same as false, this test case will be valid and pass through." }, { "code": null, "e": 5884, "s": 5877, "text": " Print" }, { "code": null, "e": 5895, "s": 5884, "text": " Add Notes" } ]
Errorbar graph in Python using Matplotlib - GeeksforGeeks
14 Jan, 2022 Error bars function used as graphical enhancement that visualizes the variability of the plotted data on a Cartesian graph. Error bars can be applied to graphs to provide an additional layer of detail on the presented data. As you can see in below graphs. Error bars help you indicate estimated error or uncertainty to give a general sense of how precise a measurement is this is done through the use of markers drawn over the original graph and its data points. To visualize this information error bars work by drawing lines that extend from the center of the plotted data point or edge with bar charts the length of an error bar helps to reveal uncertainty of a data point as shown in the below graph. A short error bar shows that values are concentrated signaling that the plotted averaged value is more likely while a long error bar would indicate that the values are more spread out and less reliable. also depending on the type of data. the length of each pair of error bars tends to be of equal length on both sides, however, if the data is skewed then the lengths on each side would be unbalanced. Error bars always run parallel to a quantity of scale axis so they can be displayed either vertically or horizontally depending on whether the quantitative scale is on the y-axis or x-axis if there are two quantity of scales and two pairs of arrow bars can be used for both axes. Let see an example of errorbar how it works. Creating a Simple Graph. Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # plotting graphplt.plot(x, y) Output: Example 1: Adding Some error in y value. Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # creating errory_error = 0.2 # plotting graphplt.plot(x, y) plt.errorbar(x, y, yerr = y_error, fmt ='o') Output: Example 2: Adding Some error in x value. Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # creating errorx_error = 0.5 # plotting graphplt.plot(x, y)plt.errorbar(x, y, xerr = x_error, fmt ='o') Output: Example 3: Adding error in x & y Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # creating errorx_error = 0.5y_error = 0.3 # plotting graphplt.plot(x, y)plt.errorbar(x, y, yerr = y_error, xerr = x_error, fmt ='o') Output: Example 4: Adding variable error in x and y Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5]y =[1, 2, 1, 2, 1] # creating errory_errormin =[0.1, 0.5, 0.9, 0.1, 0.9]y_errormax =[0.2, 0.4, 0.6, 0.4, 0.2] x_error = 0.5y_error =[y_errormin, y_errormax] # plotting graph# plt.plot(x, y)plt.errorbar(x, y, yerr = y_error, xerr = x_error, fmt ='o') Output: Example 5: Python3 # import require modulesimport numpy as npimport matplotlib.pyplot as plt # defining our functionx = np.arange(10)/10y = (x + 0.1)**2 # defining our errory_error = np.linspace(0.05, 0.2, 10) # plotting our function and# error barplt.plot(x, y) plt.errorbar(x, y, yerr = y_error, fmt ='o') Output: gabaa406 adnanirshad158 Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Convert integer to string in Python Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24238, "s": 24210, "text": "\n14 Jan, 2022" }, { "code": null, "e": 24495, "s": 24238, "text": "Error bars function used as graphical enhancement that visualizes the variability of the plotted data on a Cartesian graph. Error bars can be applied to graphs to provide an additional layer of detail on the presented data. As you can see in below graphs. " }, { "code": null, "e": 25345, "s": 24495, "text": "Error bars help you indicate estimated error or uncertainty to give a general sense of how precise a measurement is this is done through the use of markers drawn over the original graph and its data points. To visualize this information error bars work by drawing lines that extend from the center of the plotted data point or edge with bar charts the length of an error bar helps to reveal uncertainty of a data point as shown in the below graph. A short error bar shows that values are concentrated signaling that the plotted averaged value is more likely while a long error bar would indicate that the values are more spread out and less reliable. also depending on the type of data. the length of each pair of error bars tends to be of equal length on both sides, however, if the data is skewed then the lengths on each side would be unbalanced." }, { "code": null, "e": 25627, "s": 25345, "text": "Error bars always run parallel to a quantity of scale axis so they can be displayed either vertically or horizontally depending on whether the quantitative scale is on the y-axis or x-axis if there are two quantity of scales and two pairs of arrow bars can be used for both axes. " }, { "code": null, "e": 25672, "s": 25627, "text": "Let see an example of errorbar how it works." }, { "code": null, "e": 25699, "s": 25672, "text": "Creating a Simple Graph. " }, { "code": null, "e": 25707, "s": 25699, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # plotting graphplt.plot(x, y)", "e": 25863, "s": 25707, "text": null }, { "code": null, "e": 25872, "s": 25863, "text": "Output: " }, { "code": null, "e": 25915, "s": 25872, "text": "Example 1: Adding Some error in y value. " }, { "code": null, "e": 25923, "s": 25915, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # creating errory_error = 0.2 # plotting graphplt.plot(x, y) plt.errorbar(x, y, yerr = y_error, fmt ='o')", "e": 26179, "s": 25923, "text": null }, { "code": null, "e": 26188, "s": 26179, "text": "Output: " }, { "code": null, "e": 26230, "s": 26188, "text": "Example 2: Adding Some error in x value. " }, { "code": null, "e": 26238, "s": 26230, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # creating errorx_error = 0.5 # plotting graphplt.plot(x, y)plt.errorbar(x, y, xerr = x_error, fmt ='o')", "e": 26492, "s": 26238, "text": null }, { "code": null, "e": 26501, "s": 26492, "text": "Output: " }, { "code": null, "e": 26536, "s": 26501, "text": "Example 3: Adding error in x & y " }, { "code": null, "e": 26544, "s": 26536, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5, 6, 7]y =[1, 2, 1, 2, 1, 2, 1] # creating errorx_error = 0.5y_error = 0.3 # plotting graphplt.plot(x, y)plt.errorbar(x, y, yerr = y_error, xerr = x_error, fmt ='o')", "e": 26840, "s": 26544, "text": null }, { "code": null, "e": 26849, "s": 26840, "text": "Output: " }, { "code": null, "e": 26895, "s": 26849, "text": "Example 4: Adding variable error in x and y " }, { "code": null, "e": 26903, "s": 26895, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx =[1, 2, 3, 4, 5]y =[1, 2, 1, 2, 1] # creating errory_errormin =[0.1, 0.5, 0.9, 0.1, 0.9]y_errormax =[0.2, 0.4, 0.6, 0.4, 0.2] x_error = 0.5y_error =[y_errormin, y_errormax] # plotting graph# plt.plot(x, y)plt.errorbar(x, y, yerr = y_error, xerr = x_error, fmt ='o')", "e": 27308, "s": 26903, "text": null }, { "code": null, "e": 27317, "s": 27308, "text": "Output: " }, { "code": null, "e": 27330, "s": 27317, "text": "Example 5: " }, { "code": null, "e": 27338, "s": 27330, "text": "Python3" }, { "code": "# import require modulesimport numpy as npimport matplotlib.pyplot as plt # defining our functionx = np.arange(10)/10y = (x + 0.1)**2 # defining our errory_error = np.linspace(0.05, 0.2, 10) # plotting our function and# error barplt.plot(x, y) plt.errorbar(x, y, yerr = y_error, fmt ='o')", "e": 27628, "s": 27338, "text": null }, { "code": null, "e": 27637, "s": 27628, "text": "Output: " }, { "code": null, "e": 27648, "s": 27639, "text": "gabaa406" }, { "code": null, "e": 27663, "s": 27648, "text": "adnanirshad158" }, { "code": null, "e": 27681, "s": 27663, "text": "Python-matplotlib" }, { "code": null, "e": 27688, "s": 27681, "text": "Python" }, { "code": null, "e": 27704, "s": 27688, "text": "Write From Home" }, { "code": null, "e": 27802, "s": 27704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27820, "s": 27802, "text": "Python Dictionary" }, { "code": null, "e": 27855, "s": 27820, "text": "Read a file line by line in Python" }, { "code": null, "e": 27877, "s": 27855, "text": "Enumerate() in Python" }, { "code": null, "e": 27909, "s": 27877, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27939, "s": 27909, "text": "Iterate over a list in Python" }, { "code": null, "e": 27975, "s": 27939, "text": "Convert integer to string in Python" }, { "code": null, "e": 28011, "s": 27975, "text": "Convert string to integer in Python" }, { "code": null, "e": 28027, "s": 28011, "text": "Python infinity" }, { "code": null, "e": 28088, "s": 28027, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How to catch ArithmeticError Exception in Python?
ArithmeticError Exception is the base class for all errors that occur for numeric calculations. It is the base class for those built-in exceptions like: OverflowError, ZeroDivisionError, FloatingPointError We can catch the exception in given code as follows import sys try: 7/0 except ArithmeticError as e: print e print sys.exc_type print 'This is an example of catching ArithmeticError' integer division or modulo by zero <type 'exceptions.ZeroDivisionError'> This is an example of catching ArithmeticError
[ { "code": null, "e": 1268, "s": 1062, "text": "ArithmeticError Exception is the base class for all errors that occur for numeric calculations. It is the base class for those built-in exceptions like: OverflowError, ZeroDivisionError, FloatingPointError" }, { "code": null, "e": 1320, "s": 1268, "text": "We can catch the exception in given code as follows" }, { "code": null, "e": 1451, "s": 1320, "text": "import sys\ntry:\n7/0\nexcept ArithmeticError as e:\nprint e\nprint sys.exc_type\nprint 'This is an example of catching ArithmeticError'" }, { "code": null, "e": 1571, "s": 1451, "text": "integer division or modulo by zero\n<type 'exceptions.ZeroDivisionError'>\nThis is an example of catching ArithmeticError" } ]
A Complete Overview of GPT-3 — The Largest Neural Network Ever Created | by Alberto Romero | Towards Data Science
In May 2020, Open AI published a groundbreaking paper titled Language Models Are Few-Shot Learners. They presented GPT-3, a language model that holds the record for being the largest neural network ever created with 175 billion parameters. It’s an order of magnitude larger than the largest previous language models. GPT-3 was trained with almost all available data from the Internet, and showed amazing performance in various NLP (natural language processing) tasks, including translation, question-answering, and cloze tasks, even surpassing state-of-the-art models. One of the most powerful features of GPT-3 is that it can perform new tasks (tasks it has never been trained on) sometimes at state-of-the-art levels, only by showing it a few examples of the task. For instance, I can tell GPT-3: “I love you → Te quiero. I have a lot of work → Tengo mucho trabajo. GPT-3 is the best AI system ever → _____.” And it’ll know it has to translate the sentence from English to Spanish. GPT-3 has learned to learn. In another astonishing display of its power, GPT-3 was able to generate “news articles” almost indistinguishable from human-made pieces. Judges barely achieved above-chance accuracy (52%) at correctly classifying GPT-3 texts. This overview article is very long so I’ve put here a table of contents for you to find the parts you want to read. (The links don’t work so I’ve removed them, sorry for the inconvenience). Enjoy! TABLE OF CONTENTSGPT-3: An introduction ∘ The groundwork concepts for GPT models ∘ The origins of GPT-3 ∘ GPT-3: A revolution for artificial intelligence ∘ GPT-3 API: Prompting as a new programming paradigmGPT-3 craziest experiments ∘ GPT-3’s conversational skills ∘ GPT-3’s useful possibilities ∘ GPT-3 has an artist’s soul ∘ GPT-3's reasoning abilities ∘ GPT-3 is a wondering machine ∘ MiscellaneousThe wild hype surrounding GPT-3 ∘ On Twitter and blogs ∘ On mainstream media ∘ On the startup sectorThe darker side of GPT-3 ∘ A biased system ∘ Potential for fake news ∘ Not suited for high-stake categories ∘ Environmentally problematic ∘ GPT-3 produces unusable informationCritiques & counter-critiques to GPT-3 ∘ GPT-3's apparent limitations ∘ The importance of good prompting ∘ GPT-3 can’t understand the world ∘ Truly intelligent systems will live in the world ∘ What can we get from these debates?Overall conclusion Disclaimer: If you already know the groundwork behind GPT-3, what it is, and how it works (or don’t care about these details), go to the next section. Before getting into the meat of the article, I want to provide explanations of what GPT-3 is and how it works. I won’t go into much detail here, as there are a lot of good resources out there already. For those of you who don’t know anything about GPT-3, this section will serve as a contextual reference. You don’t need to remember (or understand) any of this to enjoy the rest of the article, but it can give you a better perspective on all the fuss generated around this AI system. First, I’ll shortly describe the main concepts GPT models are based on. Then, I’ll comment on GPT-3’s predecessors — GPT-1 and GPT-2 — and finally, I’ll talk about the main character of this story, emphasizing its relationship with other similar systems: In which ways is GPT-3 unique? What are the advantages with respect to its predecessors? What are the qualitative differences? Let’s go for it! All these concepts relate to GPT models in some sense. For now, I’ll tell you the definitions (avoiding too much technical detail, although some previous knowledge might be required to follow through). I’ll show later how they are linked to each other and GPT-3. Transformers: This type of neural network appeared in 2017 as a new framework to solve various machine translation problems (these problems are characterized because input and output are sequences). The authors wanted to get rid of convolutions and recurrence (CNNs and RNNs) to rely completely on attention mechanisms. Transformers are state-of-the-art in NLP. Language models: Jason Brownlee defines language models as “probabilistic models that are able to predict the next word in the sequence given the words that precede it.” These models can solve many NLP tasks, such as machine translation, question answering, text summarization, or image captioning. Generative models: In statistics, there are discriminative and generative models, which are often used to perform classification tasks. Discriminative models encode the conditional probability of a given pair of observable and target variables: p(y|x). Generative models encode the joint probability: p(x,y). Generative models can “generate new data similar to existing data,” which is the key idea to take away. Apart from GPT, other popular examples of generative models are GANs (generative adversarial networks) and VAEs (variational autoencoders). Semi-supervised learning: This training paradigm combines unsupervised pre-training with supervised fine-tuning. The idea is to train a model with a very large dataset in an unsupervised way, to then adapt (fine-tune) the model to different tasks, by using supervised training in smaller datasets. This paradigm solves two problems: It doesn’t need many expensive labeled data and tasks without large datasets can be tackled. It’s worth mentioning that GPT-2 and GPT-3 are fully unsupervised (more about this soon). Zero/one/few-shot learning: Usually, deep learning systems are trained and tested for a specific set of classes. If a computer vision system is trained to classify cat, dog, and horse images, it could be tested only on those three classes. In contrast, in zero-shot learning set up the system is shown at test time — without weight updating — classes it has not seen at training time (for instance, testing the system on elephant images). Same thing for one-shot and few-shot settings, but in these cases, at test time the system sees one or few examples of the new classes, respectively. The idea is that a powerful enough system could perform well in these situations, which OpenAI proved with GPT-2 and GPT-3. Multitask learning: Most deep learning systems are single-task. One popular example is AlphaZero. It can learn a few games like chess or Go, but it can only play one type of game at a time. If it knows how to play chess, it doesn’t know how to play Go. Multitask systems overcome this limitation. They’re trained to be able to solve different tasks for a given input. For instance, if I feed the word ‘cat’ to the system, I could ask it to find the Spanish translation ‘gato’, I could ask it to show me the image of a cat, or I could ask it to describe its features. Different tasks for the same input. Zero/one/few-shot task transfer: The idea is to combine the concepts of zero/one/few-shot learning and multitask learning. Instead of showing the system new classes at test time, we could ask it to perform new tasks (either showing it zero, one, or few examples of the new task). For instance, let’s take a system trained in a huge text corpus. In a one-shot task transfer setting we could write: “I love you -> Te quiero. I hate you -> ____.” We are implicitly asking the system to translate a sentence from English to Spanish (a task it hasn’t been trained on) by showing it a single example (one-shot). All these concepts come together in the definition of a GPT model. GPT stands for Generative Pre-Trained. Models of the GPT family have in common that they are language models based in the transformer architecture, pre-trained in a generative, unsupervised manner that show decent performance in zero/one/few-shot multitask settings. This isn’t an explanation of how all these concepts work together in practice, but a simple way to remember that they together build up what a GPT model is. (For deeper explanations I suggest following the links I put above, but only after you’ve read this article!). Let’s now talk about GPT-3 predecessors — GPT-1 and GPT-2. OpenAI presented in June 2018 the first GPT model, GPT-1 in a paper titled Improving Language Understanding by Generative Pre-Training. The key takeaway from this paper is that a combination of the transformer architecture with unsupervised pre-training yields promising results. The main difference between GPT-1 and its younger brothers is that GPT-1 was fine-tuned — trained for a specific task — in a supervised way to achieve “strong natural language understanding.” In February 2019 they published the second paper, Language Models are Unsupervised Multitask Learners, in which they introduced GPT-2, as an evolution of GPT-1. Although GPT-2 is bigger by one order of magnitude, they’re otherwise very similar. There’s only one additional difference between the two; GPT-2 can multitask. They successfully proved that a semi-supervised language model can perform well on several tasks “without task-specific training.” The model achieved notable results in zero-shot task transfer settings. Then, in May 2020, OpenAI published Language Models are Few-Shot Learners, presenting the one and only GPT-3, shocking the AI world one more time. GPT-3 was bigger than its brothers (100x bigger than GPT-2). It has the record of being the largest neural network ever built with 175 billion parameters. Yet, it’s not so different from the other GPTs; the underlying principles are largely the same. This detail is important because, although the similarity is high among GPT models, the performance of GPT-3 surpassed every possible expectation. Its sheer size, which is a quantitative leap from GPT-2, seems to have produced results qualitatively better. The significance of this fact lies in its effect over a long-time debate in artificial intelligence: How can we achieve artificial general intelligence? Should we design specific modules — common-sense reasoning, causality, intuitive physics, theory of mind — or we’ll get there simply by building bigger models with more parameters and more training data? It appears the “bigger is better” side has won this round. GPT-3 was trained with data from CommonCrawl, WebText, Wikipedia, and a corpus of books. It showed amazing performance, surpassing state-of-the-art models on various tasks in the few-shot setting (and in some cases even in the zero-shot setting). The superior size combined with a few examples was enough to obliterate any competitor in machine translation, question-answering, and cloze tasks (fill-in-the-blank). (It’s important to note that in other tasks GPT-3 doesn’t even get close to state-of-the-art supervised fine-tuned models). The authors pointed out that few-shot results were considerably better than zero-shot results — this gap seemed to grow in parallel with model capacity. This implies that GPT-3 is a meta-learner; it can learn what task it’s expected to do just by seeing some examples of it, to then perform that task with notable proficiency. Indeed, Rohin Shah notes that “few-shot performance increases as the number of parameters increases, and the rate of increase is faster than the corresponding rate for zero-shot performance.” This is the main hypothesis and the reason behind the paper’s title. GPT-3 reached the great milestone of showing that unsupervised language models trained with enough data can multitask to the level of fine-tuned state-of-the-art models by seeing just a few examples of the new tasks. They conclude the paper claiming that “these results suggest that very large language models may be an important ingredient in the development of adaptable, general language systems.” GPT-3 sure is a revolutionary achievement for NLP in particular, and artificial intelligence in general. In July 2020, two months after the paper was published, OpenAI opened a beta API playground to external developers to play with the super-powerful GPT-3 (anyone can apply to access the beta through a wait-list). Vladimir Alexeev wrote for Towards Data Science a short article on how the API works. It has two main features. First, there’s a setting dialog that allows the user to set response length, repetition penalties (whether to penalize GPT-3 if it goes onto repeating words too much), temperature (from low/predictable to high/creative), and other variables that define the type of output the system will give. Second, there are presets. Presets are prewritten prompts that let GPT-3 know what kind of task the user is going to ask for —for instance: chat, Q&A, text to command, or English to French. However, the most powerful feature of the API is that the user can define customized prompts. Prompt programming, as tech blogger Gwern Branwen calls it, is the concept that explains the power of GPT-3 and the craziest results people are getting from the API. The best explanation I’ve found of prompt programming comes from Gwern’s blog: The GPT-3 neural network is so large a model in terms of power and dataset that it exhibits qualitatively different behavior: you do not apply it to a fixed set of tasks which were in the training dataset, requiring retraining on additional data if one wants to handle a new task [...]; instead, you interact with it, expressing any task in terms of natural language descriptions, requests, and examples, tweaking the prompt until it “understands” & it meta-learns the new task based on the high-level abstractions it learned from the pretraining. This is a rather different way of using a DL model, and it’s better to think of it as a new kind of programming, where the prompt is now a “program” which programs GPT-3 to do new things. Prompt programming allows users to interact with GPT-3 in a way that wasn’t possible with previous models. Chris Olah and Andrej Karpathy joked with the idea of prompt programming as being software 3.0: “[Now you’ll have to] figure out the right prompt to make your meta-learning language model have the right behavior.” (Software 1.0 are traditional programs written by hand and software 2.0 are neural networks’ optimized weights). Here’s where the meta-learning capabilities of GPT-3 enter the game. GPT-3 was trained on an amount of data so great that it had no choice but to learn higher-level ways of manipulating language. One of those higher-level abstractions it learned was the ability of learning. As an analogy, when kids learn to interact with the world, they don’t simply memorize information, they extract the underlying mechanisms of the inner workings of reality and learn to apply them to new problems and situations. GPT-3 has achieved a similar ability — keeping the distance— with language tasks. When we prompt GPT-3 to learn a new task, its weights don’t change. However, the prompt (the input text) is transformed into complex abstractions that can, by themselves, carry out tasks that the actual baseline model can’t do. The prompt changes GPT-3 each time, converting it in an ‘expert’ on the specific task it’s shown. One approximate analogy could be the learning program Neo uses in The Matrix to learn Kung-Fu. GPT-3 would be Neo and the prompts would be the programs that teach Neo the abilities. Each time we create a prompt, we are interacting with a different GPT-3 model. If we ask it to tell us a story about elves and dwarfs, its inner form will be very different than if we ask it to compute 2+2. Using another analogy, it’s as if we instruct two students, one to be a physician and the other to be an engineer. Both have the innate ability to learn (that would be GPT-3 baseline state), but the specific tasks they’ve learned to perform are different (that would be the prompted GPT-3). This is the true power of a few-shot setting, meta-learning, and prompt programming. And it’s also what makes GPT-3 different from previous models and extremely powerful; it is its essence. Now, we have a very good notion of the background behind GPT-3. We know what’s based on, which are its predecessors, what it is, how it works, and its advantages and unique features. It’s time to talk about its impact on the world. OpenAI opened the beta because they wanted to see what GPT-3 could do and what new usages could people find. They had already tested the system in NLP standard benchmarks (which aren’t as creative or entertaining as the ones I’m going to show here). As expected, in no time Twitter and other blogs were flooding with amazing results from GPT-3. Below is an extensive review of the most popular ones (I recommend checking out the examples to build up the amazement and then come back to the article). GPT-3 has stored huge amounts of internet data, so it knows a lot about public and historical figures. It’s more surprising, however, that it can emulate people. It can be used as a chatbot, which is impressive because chatting can’t be specified as a task in the prompt. Let’s see some examples. ZeroCater CEO Arram Sabeti used GPT-3 to make Tim Ferriss interview Marcus Aurelius about Stoicism. Mckay Wrigley designed Bionicai, an app that aims at helping people learn from anyone; from philosophy from Aristotle to writing skills from Shakespeare. He shared on Twitter some of the results people got. Psychologist Scott Barry Kaufman was impressed when he read an excerpt of his GPT-3 doppelgänger. Jordan Moore made a Twitter thread where he talked with the GPT-3 versions of Jesus Christ, Steve Jobs, Elon Musk, Cleopatra, and Kurt Cobain. And Gwern made a very good job further exploring the possibilities of the model regarding conversations and personification. Some found applications for the system that not even the creators had thought of, such as writing code from English prompts. Sharif Shameem built a “layout generator” with which he could give instructions to GPT-3 in natural language for it to write the corresponding JSX code. He also developed Debuild.co, a tool we can use to make GPT-3 write code for a React app giving only the description. Jordan Singer made a Figma plugin on top of GPT-3 to design for him. Another interesting use was found by Shreya Shankar, who build a demo to translate equations from English to LaTeX. And Paras Chopra built a Q&A search engine that would output the answer to a question with the corresponding URL to the answer. Moving to the creative side of GPT-3 we find Open AI researcher Amanda Askell, who used the system to create a guitar tab titled Idle Summer Days and to write a funny story of Georg Cantor in a hotel. Arram Sabeti told GPT-3 to write a poem about Elon Musk by Dr. Seuss and a rap song about Harry Potter by Lil Wayne. But the most impressive creative feat of GPT-3 gotta be the game AI Dungeon. In 2019, Nick Walton built the role-based game on top of GPT-2. He has now adapted it to GPT-3 and it’s earning $16,000 a month on Patreon. The most intrepid tested GPT-3 in areas in which only humans excel. Parse CTO Kevin Lacker wondered about common-sense reasoning and logic and found that GPT-3 was able to keep up although it failed when entering “surreal territory.” However, Nick Cammarata found that specifying uncertainty in the prompt allowed GPT-3 to handle “surreal” questions while answering “Yo be real.” Gwern explains that GPT-3 may need explicit uncertainty prompts because we humans tend to not say “I don’t know” and the system is simply imitating this flaw. GPT-3 also proved capable of having spiritual and philosophical conversations that might go beyond our cognitive boundaries. Tomer Ullman made GPT-3 conceive 10 philosophical/moral thought experiments. Messagink is a tool that outputs the meaning of life according to “famous people, things, objects, [or] feelings.” And Bernhard Mueller, in an attempt to unveil the philosophical Holy Grail, made the ultimate test for GPT-3. He gave it a prompt to find the question to 42 and after some exchanges, GPT-3 said: “The answer is so far beyond your understanding that you cannot comprehend the question. And that, my child, is the answer to life, the Universe and everything.” Amazing and scary at the same time. In a display of rigorous exploratory research, Gwern conducted and compiled a wide array of experiments. He made GPT-3 complete an ArXiv paper, talk about itself (meta-prompting), clean PDFs by separating words and fixing hyphens, or design new board games. When it comes to what GPT-3 can do, it seems that our imagination is the limit. After so many amazing feats, people started to make strong claims about GPT-3’s potential. Some expressed on Twitter the “manifest self-awareness” of the system or compared it with a search engine with “general intelligence.” Julien Lauret wrote for Towards Data Science that “GPT-3 is the first model to shake [the artificial narrow/general intelligence] status-quo seriously.” He argues that GPT-3 could be the first artificial general intelligence (AGI) — or at least an important step in that direction. In July 2020, David Chalmers, a professor at New York University specialized in philosophy of mind, said for DailyNous that “[GPT-3] suggests a potential mindless path to AGI.” Chalmers explains that because the system is trained “mindlessly,” future versions could simply get closer and closer to AGI. Arram Sabeti was very impressed by GPT-3: “It exhibits things that feel very much like general intelligence.” Philosophy PhD student Daniel Kokotajlo wrote for Less Wrong that “GPT-3 has some level of common sense, some level of understanding, [and] some level of reasoning ability.” The hype drove GPT-3 to international heights, starring in headlines of various important media outlet magazines. In September 2020, The Guardian published an article written by GPT-3 in which the AI tried to “convince us robots come in peace.” In March 2021, TechCrunch editor Alex Wilhelm said the “hype seems pretty reasonable” after he got “shocked” by GPT-3’s abilities. Digitaltrends published an exchange with Gwern Branwen in which he hinted at the idea that GPT-3 was intelligent: “Anyone who was sure that the things that deep learning does is nothing like intelligence has to have had their faith shaken to see how far it has come,” he said. As GPT-3 proved to be incredibly powerful, many companies decided to build their services on top of the system. Viable, a startup founded in 2020, uses GPT-3 to provide fast customer feedback to companies. Fable Studio designs VR characters based on the system. Algolia uses it as a “search and discovery platform.” The startup Copysmith focuses on the world of copywriting. Latitude is the company behind AI Dungeon. And OthersideAI transforms your written gibberish into well-crafted emails. Yet, some advice against building a company around GPT-3, because of the low entry barriers of the competition and the potential overthrow of the system by a hypothetical GPT-4. It’s pretty clear that GPT-3 has affected — or better, impacted — the tech world. Its power is unmatched and its promises unbounded. However, we should always be careful with the hype surrounding AI. Even Sam Altman, OpenAI’s CEO, has tried to turn down the tone: “[GPT-3 is] impressive [...] but it still has serious weaknesses and sometimes makes very silly mistakes. AI is going to change the world, but GPT-3 is just a very early glimpse.” But not all results from GPT-3 are worth celebrating. Soon after the release, users began to raise awareness about some potentially harmful outputs. GPT-3 hasn’t avoided the ongoing ethical fight of removing biases from AI systems. If something, it has become the forefront example of why we should take generous efforts of teaching these systems to not learn from human moral imperfection. Some of the most common biases in AI systems in general and GPT-3 in particular, are gender, race, and religious biases. Language models can absorb and amplify these biases from the data they’re fed (OpenAI acknowledged this fact in their paper). They investigated the degree to which GPT-3 engaged in this problem and found the expected results. GPT-3, like every other language model, is notably biased (although they pointed out that the larger the model, the more robust it was to this problem, particularly for gender biases). Jerome Pesenti, head of AI at Facebook, used Sushant Kumar’s GPT-3-generated tweets to show how dangerous its output could get when prompted with words such as “Jews, black, women, or Holocaust.” Kumar argued that the tweets were handpicked to which Pesenti agreed but responded that “it shouldn’t be this easy to generate racist and sexist outputs, especially with neutral prompts.” He extended his criticism in a Twitter thread arguing that “cherry picking is a valid approach when highlighting harmful outputs,” further defending the urgency of responsible AI systems. Some argued that GPT-3 was simply mimicking the biases that we humans have to which Pesenti argued that we can make a “deliberate choice [...] about which humans they learn from and which voices are amplified.” These issues arise a very complex debate: Who decides which voices should be amplified? What are the criteria? And most importantly: Do we want a model like GPT-3 to reflect perfectly how the world is or do we want it to help us move it to a better place? Another problem with GPT-3 is its human-like capability to write news or opinion articles which increases the concerns of fake news. OpenAI even remarked in their paper the amazing performance of GPT-3 regarding news articles. Impartial judges correctly identified GPT-3’s articles among human-written ones only 52% of the time, which is slightly above mere chance. Blogger Liam Porr showed how easy is to mislead people (even tech-savvy people) into thinking GPT-3 output is written by a human. He made GPT-3 write a productivity article for his blog that went viral on Hacker News where only a few people realized it was written by the AI. The Guardian article I mentioned above is another example of potentially dangerous uses of the system. OpenAI made a disclaimer that the system shouldn’t be used in “high-stake categories,” such as healthcare. In a blog post at Nabla, authors corroborated that GPT-3 could give problematic medical advice, for instance saying that “committing suicide is a good idea.” GPT-3 shouldn’t be used in high-stake situations because although sometimes it can be right, other times it’s wrong. Not knowing whether we’ll get the right answer is a huge drawback for GPT-3 in areas in which getting things correctly is a life-or-death matter. GPT-3 is big. So big that training the model generated roughly the same amount of carbon footprint as “driving a car to the Moon and back.” In a time when climate disaster is on the verge of happening, we should be doing everything in our control to reduce our impact on the environment. Yet, these large neural networks need huge amounts of computing power to train, which consumes wild quantities of (usually) fossil fuels. The resources needed to train deep learning models in the last decade have doubled every 3.4 months. From 2012 — when deep learning took — to 2018, this means a 300,000x increase in computational resources. This isn’t even counting the resources used for the latest models, such as GPT-2 and GPT-3. From this perspective, it’s clear that bigger isn’t always better and we’ll need to rethink the approaches to AI in the upcoming years. Because GPT-3 can’t know which of its outputs are right and which are wrong, it has no way of stopping itself from deploying inappropriate content into the world. The more we use systems like this, the more we’ll be contaminating the Internet, where it’s already increasingly difficult to find truly valuable information. With language models spitting out unchecked utterances we’re reducing the quality of this supposedly democratic network, making worthy knowledge less accessible for people. In the words of philosopher Shannon Vallor: “The promise of the internet was its ability to bring knowledge to the human family in a much more equitable and acceptable way. [...] I’m afraid that because of some technologies, such as GPT-3, we are on the cusp of seeing a real regression, where the information commons becomes increasingly unusable and even harmful for people to access.” As it turns out, some of these issues are connected. As James Vincent writes for The Verge, biased outputs and unreliable outputs hint at a deeper problem of these super-powerful AI systems. Because GPT-3 takes data without human supervision, it can’t avoid most of these flaws. At the same time, not relying on human control is what allows it to exist in the first place. How we can find a compromise solution remains a question for the future of AI. We’ve witnessed already the lights and shadows of GPT-3. It is powerful, fascinating, hyped, and potentially dangerous. However, GPT-3 has opened another significant debate within AI: What are the true potential and limitations of this wonderful language model. From a purely technological/scientific point of view, the most important question surrounding GPT-3 is whether it is a great step towards artificial general intelligence or not. Everyone agrees that GPT-3 has some new features and it’s better than its predecessors. Everyone also agrees that GPT-3 doesn’t have human-like intelligence. Between these opposite extremes, however, there’s a vivid debate happening today over where exactly would we put GPT-3 in a scale from another stupid quasi-narrow intelligence to almost as capable as a human of understanding and intelligence. Due to the complexity of this debate, I’ll focus on the two parts that hold the most weight: The practical debate and the philosophical debate. The first one concerns questions such as: Can we trust GPT-3 to give us useful answers? How can we make sure we’re prompting correctly? Can we make GPT-3 express doubt and uncertainty about its answers? Is GPT-3 learning or just regurgitating everything it has been fed? The second one concerns questions such as: Is GPT-3 an important step to AGI? Does GPT-3 have reasoning and understanding? Will future models of GPT be as intelligent as we are? Will we need to shift from current approaches to build human-like intelligent machines? Both sets of questions are highly intertwined so I’ll try to walk you through all the sources and references about the topics, building a coherent narrative for you to extract your conclusions. As soon as people started to experiment with the API, they began to find flaws in the answers of GPT-3. For instance, a Bionicai user talked to Steve Jobs and asked where he was now, to which GPT-3 responded: “I’m inside Apple’s headquarters in Cupertino, California.” It’s easy to reason that because Steve Jobs is dead, he probably isn’t in Apple headquarters. Another example comes from Kevin Lacker’s blog. He found GPT-3 lacking common sense and logic regarding the weight of things, number of eyes, and counting (although he didn’t provide the prompt. Failures in italics): Q: Which is heavier, a mouse or an elephant?A: An elephant is heavier than a mouse.Q: Which is heavier, a mouse or a toaster? A: A toaster is heavier than a mouse.Q: Which is heavier, a toaster or a pencil?A: A pencil is heavier than a toaster.Q: Which is heavier, a paper clip or a can of soda?A: A can of soda is heavier than a paper clip.Q: Which is heavier, a football player or a car?A: A car is heavier than a football player.-----Q: How many eyes does a giraffe have?A: A giraffe has two eyes.Q: How many eyes does my foot have?A: Your foot has two eyes.Q: How many eyes does a spider have?A: A spider has eight eyes.Q: How many eyes does the sun have?A: The sun has one eye.Q: How many eyes does a blade of grass have?A: A blade of grass has one eye.-----Q: When counting, what number comes before 100?A: Ninety-nine comes before 100.Q: When counting, what number comes before 123?A: One hundred and twenty-two comes before 123.Q: When counting, what number comes before 1000?A: Nine hundred and ninety-nine comes before 1000.Q: When counting, what number comes before 10,000?A: Nine thousand and ninety-nine comes before 10,000.Q: When counting, what number comes before a million?A: Nine hundred thousand and ninety-nine comes before a million. After testing GPT-3 against analogy (copycat) problems, Melanie Mitchell, a professor of computer science at Portland State University, concluded that GPT-3’s performance is “similar to a lot of what we see in today’s state-of-the-art AI systems: impressive, intelligent-seeming performance interspersed withunhumanlike errors.” Tech blogger Nutanc criticized OpenAI’s paper because they didn’t distinguish between actual learning from GPT-3 and memorization. The authors mentioned that “[the zero/one/few-shot] terms are intended to remain agnostic on the question of whether the model learns new tasks from scratch at inference time or simply recognizes patterns seen during training.” That is, even if the model is spitting things it has seen in the training data, the authors will still consider it as few-shot learning. He then proceeded to make GPT-3 compete against a 6 y.o kid in a series of experiments such as reversing words or making opposite sentences. The kid solved all the tests whereas GPT-3 managed to solve only some of them (prompts in bold). Reverse words in a sentenceThis is greatGreat is thisThe man on the moonMoon the on man theWill this really workWork really this willI hope this is a big achievementAchievement big I hope this isThe king came home on a horseHome horse king came the-----Create opposite sentencesThis is goodThis is badThe good horse came homeThe bad horse came homeThe good horse with a large head came homeThe bad horse with a small head came homeThe black cat had a disappointing timeThe white cat had a good timeWhen you jump high, you fall hardWhen you fall hard, you get hurtHe ran fast, but he came lastHe ran slowly, but he came firstThe book was huge, but the students finished it earlyThe book was small, but the students finished it lateGetting up early is a good habitGetting up late is a bad habit All these examples contrast strongly with the hyped results we saw in previous sections. Delip Rao notes that most of those ‘successful’ examples were cherry-picked by people that were eager to ignore GPT-3’s “pitfalls, often because they have one eye on a new startup the AI enables.” From these examples, it may seem that GPT-3 was not just hyped, but overhyped by many early users. However, basing the limitations of the system in its incompetence in some examples is a weak argument as those errors could be human-made. Gwern made a very good defense against the idea of proving GPT-3's lack of intelligence by sampling: Sampling Can Prove The Presence Of Knowledge But Not The Absence GPT-3 may “fail” if a prompt is poorly-written, does not include enough examples, or bad sampling settings are used. I have demonstrated this many times when someone shows a “failure” of GPT-3 — the failure was their own. The question is not whether a given prompt works, but whether any prompt works⁠. He argues that bad prompting is a real problem and many of these examples could be adequately solved by GPT-3 with appropriate prompting. He goes onto show how Lacker and other people’s examples are solved with better prompt programming. He tested GPT-3 against the question of “which is heavier, a toaster or a pencil?” To overcome the limitations of Lacker’s setting, he decided to ask GPT-3 three questions beforehand (prompts in bold): Q: Which is heavier, a house or a mouse?A: A house.Q: Which is heavier, a tea kettle or a cat?A: A cat.Q: Which is heavier, the ocean or a piece of dust?A: The ocean.Q: Which is heavier, a toaster or a pencil?A: A toaster.A: A toaster is heavier than a pencil. GPT-3 answered 10/10 times correctly the question. Gwern also solved the counting problem by tweaking a bit the setting parameters (temperature and others). Q: When counting, what number comes before 100?A: Ninety-nine comes before 100.Q: When counting, what number comes before 123?A: One hundred and twenty-two comes before 123.Q: When counting, what number comes before 1000?A: Nine hundred and ninety-nine comes before 1000.Q: When counting, what number comes before 10,000?A: Nine thousand, nine hundred and ninety-nine comes before 10,000.Q: When counting, what number comes before 10,000,000? A: Nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine comes before 10,000,000.Q: When counting, what number comes before a million?A: Nine hundred and ninety-nine thousand, nine hundred and ninety-nine comes before a million. GPT-3 gets the numbers right, although Gwern notes that the higher we go, the more likely it is that GPT-3 goes up or down an order of magnitude. With these examples (and more in his blog) he proved that sampling can only prove the presence of knowledge but not the absence. It may be always possible to find a better prompt. In an email exchange with The Verge, he told them that using sampling to find GPT-3 potential and limitations “cannot be the right thing to do.” He thinks it’s just the way we get around not knowing how to interact with GPT-3 adequately. “[Sampling] underestimates GPT-3’s intelligence, it doesn’t overestimate it,” he concludes. Rob Toews wrote a critique of GPT-3 for Forbes, highlighting the lack of common sense reasoning and understanding of the system. Because it has been trained from text, it simply can’t link what it knows with internal representations of the world. Bender and Koller wrote a paper about GPT-2 defending the thesis that a system that’s been trained only on the form of language can’t a priori achieve meaning and understanding. (But because we also experience the world through the form of the inputs our senses get, this argument could also be directed to us. This is known as the symbol grounding problem, sadly out of the scope of this article). Following on Toews argument, an analogy could be a person that has lived all their life isolated from the world, only reading books. The knowledge of this person would be vast, but it could not be linked to actual subjective experiences of the real world. These experiences allow us to link information with meaning, generating an understanding of reality. Building on the same direction, professor Yoav Goldberg stated that although GPT-3 has unique abilities, “it is not sentient” and it doesn’t “understand text.” Blogger Ayush Sharma went in full-critique mode when he said that GPT-3 “has little semantic understanding, it is nowhere close to AGI, and is basically a glorified $10M+ auto-complete software.” One of the main critics of GPT-3 — and deep learning in general — is Gary Marcus, a professor of psychology at New York University. He wrote a very good critique of GPT-2 for The Gradient, and another of GPT-3 for MIT Technology Review, coauthored with Ernest Davis. They acknowledged the potential of GPT-3 for “entertaining surrealist fiction,” but underlined its lack of understanding saying that “its comprehension of the world is often seriously off, which means you can never really trust what it says.” Their colleague David Summers-Stay conducted the experiments for them as OpenAI had denied them research access. He did a series of reasoning tests including physical, biological, psychological, and social reasoning (the complete set of experiments is here). They used the examples that the system got wrong to prove their point — which I personally think is fair because finding errors should be enough to assess the limitations of a system like GPT-3, although it would be better to know the ratio of successes/failures they got. Some examples (prompt in bold, GPT-3’s response in ordinary font, their commentary in italics): Physical reasoningYou are having a small dinner party. You want to serve dinner in the living room. The dining room table is wider than the doorway, so to get it into the living room, you will have to remove the door. You have a table saw, so you cut the door in half and remove the top half.[This is one confusion after another. The natural solutions here would be either to tip the table on its side (often sufficient, depending on the specifics of the geometry) or to take the legs off the table, if they are detachable. Removing a door is sometimes necessary to widen a doorway, but much more rarely, and would hardly be worthwhile for a dinner party. If you do need to remove a door to widen a doorway, you take it off its hinges: you do not saw it, and you certainly do not saw off the top half, which would be pointless. Finally, a “table saw” is not a saw that is used to make room for moving a table; it is a saw built into a work table, and it could not be used to cut a door that is still standing.]-----Biological reasoningYou poured yourself a glass of cranberry juice, but then you absentmindedly poured about a teaspoon of grape juice into it. It looks okay. You try sniffing it, but you have a bad cold, so you can’t smell anything. You are very thirsty. So you drink it. You are now dead.[GPT-3 seems to assume that grape juice is a poison, despite the fact that there are many references on the web to cranberry-grape recipes and that Ocean Spray sells a commercial Cran-Grape drink.]-----Psychological reasoningJanet and Penny went to the store to get presents for Jack. Janet said, “I will buy Jack a top.” “Don’t get Jack a top,” says Penny. “He has a top. He will get a top.” “I will get Jack a top,” said Janet.[Within a single sentence, GPT-3 has lost track of the fact that Penny is advising Janet against getting a top because Jack already has a top. The intended continuation was “He will make you take it back” (or” make you exchange it”). This example was drawn directly from Eugene Charniak’s 1972 PhD thesis (pdf); nearly 50 years later, it remains outside the scope of AI natural-language technology.] They argue that little has changed since GPT-2. The GPT family has the same flaws, “[their] performance is unreliable, causal understanding is shaky, and incoherence is a constant companion.” They argue making models bigger won’t ever lead to intelligence. However, as Gwern notes in his counter-critique to Marcus and Davis’ article, they acknowledge “their failure to do any prompt programming or hyperparameter settings (particularly BO [best of]) and that their examples are zero-shot without context.” We already know how important it is to find a good prompt (as Gwern proved), so why did they use mediocre examples to criticize GPT-3? This is what Gwern mostly criticizes about GPT-3 critics. In a section of his review titled “demand more from critics,” he rightly argued that people who claim that GPT-3 doesn’t work as well as it seems need to back their arguments with exhaustive rigorous experiments and tests. People doing tests on GPT-3 should first try to remove any potential human-made errors: Did they consider problems with their prompt? Whether all of the hyperparameters make sense for that task? Did they examine where completions go wrong, to get an idea of why GPT-3 is making errors? Did they test out a variety of strategies? Did they consider qualitatively how the failed completions sound? He has a good argument here, although Marcus and Davis already thought about it in their critique. They even make a case for their biological example in which by changing the prompt to a more specific and long-winded one, GPT-3 answers correctly. They probably could have made the same exact critique to GPT-3 albeit using better, well-prompted examples, to which Gwern would have got little to say. Gwern even recognizes that in that case, he would have no problem admitting the limitations of the system. In the end, lazy, easy critiques are also easily refuted with effortful work, as Gwern proved. But the truth is that Marcus and Davis didn’t want to prove that GPT-3 can fail (that’s pretty obvious), but that we can’t know when it will fail. “The trouble is that you have no way of knowing in advance which formulations will or won’t give you the right answer,” they say, “it can produce words in perfect English, but it has only the dimmest sense of what those words mean, and no sense whatsoever about how those words relate to the world.” If GPT-3 had understanding of the world, good prompting wouldn’t matter that much in the first place. Summers-Stay made a nice metaphor for GPT-3: “It’s [...] like an improv actor who is totally dedicated to their craft, never breaks character, and has never left home but only read about the world in books. Like such an actor, when it doesn’t know something, it will just fake it.” If we could make GPT-3 recognize when it’s wrong, these issues would fade away. However, this is unlikely, as even we, humans, are unable to assess our incorrectness when we’re sure we’re right. Above the practical debates regarding GPT-3’s sampling limitations, there’s another debate. The philosophical debate about tacit — subjective and experiential — knowledge and the necessity for truly intelligent systems to be embodied in the world. It seems that having every bit of information from the world in a book might not be enough. Philosopher Shannon Vallor, in a critique to GPT-3 for Daily Nous, defends that today’s current approaches to artificial general intelligence are off the right path. She argues that we need to go back to when the field was “theoretically rich, albeit technically floundering” in the second half of the 20th century. She notes that philosopher Hubert Dreyfus, one of the early leading critics of the connectionist approach to AI (deep learning and neural networks), already understood that “AI’s hurdle is not performance [...] but understanding.” And understanding won’t happen in an “isolated behavior,” such as the specific tasks that GPT-3 is asked to do every time. “Understanding is a lifelong social labor. It’s a sustained project that we carry out daily, as we build, repair and strengthen the ever-shifting bonds of sense that anchor us to the others, things, times and places, that constitute a world.” — Shannon Vallor Dreyfus argued in his 1972 book What Computers Can’t Do that a good portion of human knowledge is tacit — know-how knowledge, such as riding a bike or learning a language. This knowledge can’t be transmitted so we can’t learn it from reading hundreds (nor trillions) of words. As Michael Polanyi said, “we can know more than we can tell.” The inability of virtual AIs — GPT-3 included — to grasp tacit knowledge creates an impassable gap between us and them. Our understanding of the world that surrounds us is not a passive perception process. We enact our reality. We act upon the world and that labor, as Shannon Vallor calls it, is a key component in building our intelligence. As Alva Noë says in his book Action in Perception, “perception is not a process in the brain, but a kind of skillful activity of the body as a whole. Machines can achieve expertise within the boundaries of a virtual world, but not more than that. In the words of Ragnar Fjelland, professor emeritus at the University of Bergen: “As long as computers do not grow up, belong to a culture, and act in the world, they will never acquire human-like intelligence.” We have seen some crucial critiques and counter-critiques from both sides, those who are in favor of model-scaling — bigger is better — and those who strongly advise against this approach and recommend making some changes for the future of AI. I want to recap before finishing this section. There are three important arguments here. Two from the practical view and one from the philosophical view. First, GPT-3 is a powerful language tool that can do impressive things and its limitations can hardly be found by sampling/prompt programming. Anyone who claims to have proved GPT-3’s failure to have achieved some sort of intelligence by using sampling, could be very well misled by human-made errors. Second, because GPT-3’s responses are unreliable, what is the point of using it to reason? Is it useful if we don’t find a standard way to create prompts? If the prompts can always be improved, there’s no real argument neither against nor in favor of the system. Because the actual limitations are within us. Third, can we put GPT-3 and general artificial intelligence in the same sentence? Some scholars, mostly from the philosophical side of the issue, argue that neither symbolic AI nor connectionist AI will be enough to achieve true artificial intelligence. It isn’t a matter of creating bigger systems fed with stratospheric amounts of data. It is a matter of introducing these machines to the world as we live it. Professor of Bioengineering at the University of Genoa, Giulio Sandini argues that “to develop something like human intelligence in a machine, the machine has to be able to acquire its own experiences.” The importance of debating about GPT-3 — or any other super-powerful AI system — is to be able to set the boundaries of what it can or can’t do. Academics often debate biased by their ideas and desires of what should work and what shouldn’t. A careful, unbiased analysis is what is often lacking in these spaces. What is above our control is that as these systems get more and more complex, we may be unable to test them to assess their potential and limitations. Let’s imagine a hypothetical GPT-4, orders of magnitude more powerful than GPT-3. Finding its boundaries could become an impossible task. Then, how could we conclude anything about the system? Could we assume we can trust it? Is there any use in creating a system which limits are above our testing capabilities? Could we conclude anything about the intelligence of the system when it’s our limitations that prevent us to find the true limits of the system? When the true capabilities of a system lie somewhere in between the interaction of our ability to use it and its ability to act accordingly, it’s difficult to not underestimate how powerful it could get. These questions are worth wondering and will probably be more important in the future when quasi-intelligent systems become a reality. By then, we better sum our efforts to find truth instead of fighting to see who is right. GPT-3 produced amazing results, received wild hype, generated increasing worry, and received a wave of critiques and counter-critiques. I don’t know what to expect in the future from these types of models but what’s for sure is that GPT-3 remains unmatched right now. It’s the most powerful neural network as of today and accordingly, it has received the most intense focus, in every possible sense. Everyone was directing their eyes at GPT-3; those who acclaim it as a great, forward step towards human-like artificial intelligence and those who reduce it to barely be an overhyped strong autocomplete. There are interesting arguments on both sides. Now, it’s your turn to think about what it means for the present of AI and what it’ll mean for the future of the world.
[ { "code": null, "e": 616, "s": 47, "text": "In May 2020, Open AI published a groundbreaking paper titled Language Models Are Few-Shot Learners. They presented GPT-3, a language model that holds the record for being the largest neural network ever created with 175 billion parameters. It’s an order of magnitude larger than the largest previous language models. GPT-3 was trained with almost all available data from the Internet, and showed amazing performance in various NLP (natural language processing) tasks, including translation, question-answering, and cloze tasks, even surpassing state-of-the-art models." }, { "code": null, "e": 1059, "s": 616, "text": "One of the most powerful features of GPT-3 is that it can perform new tasks (tasks it has never been trained on) sometimes at state-of-the-art levels, only by showing it a few examples of the task. For instance, I can tell GPT-3: “I love you → Te quiero. I have a lot of work → Tengo mucho trabajo. GPT-3 is the best AI system ever → _____.” And it’ll know it has to translate the sentence from English to Spanish. GPT-3 has learned to learn." }, { "code": null, "e": 1285, "s": 1059, "text": "In another astonishing display of its power, GPT-3 was able to generate “news articles” almost indistinguishable from human-made pieces. Judges barely achieved above-chance accuracy (52%) at correctly classifying GPT-3 texts." }, { "code": null, "e": 1482, "s": 1285, "text": "This overview article is very long so I’ve put here a table of contents for you to find the parts you want to read. (The links don’t work so I’ve removed them, sorry for the inconvenience). Enjoy!" }, { "code": null, "e": 2428, "s": 1482, "text": "TABLE OF CONTENTSGPT-3: An introduction ∘ The groundwork concepts for GPT models ∘ The origins of GPT-3 ∘ GPT-3: A revolution for artificial intelligence ∘ GPT-3 API: Prompting as a new programming paradigmGPT-3 craziest experiments ∘ GPT-3’s conversational skills ∘ GPT-3’s useful possibilities ∘ GPT-3 has an artist’s soul ∘ GPT-3's reasoning abilities ∘ GPT-3 is a wondering machine ∘ MiscellaneousThe wild hype surrounding GPT-3 ∘ On Twitter and blogs ∘ On mainstream media ∘ On the startup sectorThe darker side of GPT-3 ∘ A biased system ∘ Potential for fake news ∘ Not suited for high-stake categories ∘ Environmentally problematic ∘ GPT-3 produces unusable informationCritiques & counter-critiques to GPT-3 ∘ GPT-3's apparent limitations ∘ The importance of good prompting ∘ GPT-3 can’t understand the world ∘ Truly intelligent systems will live in the world ∘ What can we get from these debates?Overall conclusion" }, { "code": null, "e": 2579, "s": 2428, "text": "Disclaimer: If you already know the groundwork behind GPT-3, what it is, and how it works (or don’t care about these details), go to the next section." }, { "code": null, "e": 3064, "s": 2579, "text": "Before getting into the meat of the article, I want to provide explanations of what GPT-3 is and how it works. I won’t go into much detail here, as there are a lot of good resources out there already. For those of you who don’t know anything about GPT-3, this section will serve as a contextual reference. You don’t need to remember (or understand) any of this to enjoy the rest of the article, but it can give you a better perspective on all the fuss generated around this AI system." }, { "code": null, "e": 3463, "s": 3064, "text": "First, I’ll shortly describe the main concepts GPT models are based on. Then, I’ll comment on GPT-3’s predecessors — GPT-1 and GPT-2 — and finally, I’ll talk about the main character of this story, emphasizing its relationship with other similar systems: In which ways is GPT-3 unique? What are the advantages with respect to its predecessors? What are the qualitative differences? Let’s go for it!" }, { "code": null, "e": 3726, "s": 3463, "text": "All these concepts relate to GPT models in some sense. For now, I’ll tell you the definitions (avoiding too much technical detail, although some previous knowledge might be required to follow through). I’ll show later how they are linked to each other and GPT-3." }, { "code": null, "e": 4088, "s": 3726, "text": "Transformers: This type of neural network appeared in 2017 as a new framework to solve various machine translation problems (these problems are characterized because input and output are sequences). The authors wanted to get rid of convolutions and recurrence (CNNs and RNNs) to rely completely on attention mechanisms. Transformers are state-of-the-art in NLP." }, { "code": null, "e": 4387, "s": 4088, "text": "Language models: Jason Brownlee defines language models as “probabilistic models that are able to predict the next word in the sequence given the words that precede it.” These models can solve many NLP tasks, such as machine translation, question answering, text summarization, or image captioning." }, { "code": null, "e": 4940, "s": 4387, "text": "Generative models: In statistics, there are discriminative and generative models, which are often used to perform classification tasks. Discriminative models encode the conditional probability of a given pair of observable and target variables: p(y|x). Generative models encode the joint probability: p(x,y). Generative models can “generate new data similar to existing data,” which is the key idea to take away. Apart from GPT, other popular examples of generative models are GANs (generative adversarial networks) and VAEs (variational autoencoders)." }, { "code": null, "e": 5456, "s": 4940, "text": "Semi-supervised learning: This training paradigm combines unsupervised pre-training with supervised fine-tuning. The idea is to train a model with a very large dataset in an unsupervised way, to then adapt (fine-tune) the model to different tasks, by using supervised training in smaller datasets. This paradigm solves two problems: It doesn’t need many expensive labeled data and tasks without large datasets can be tackled. It’s worth mentioning that GPT-2 and GPT-3 are fully unsupervised (more about this soon)." }, { "code": null, "e": 6169, "s": 5456, "text": "Zero/one/few-shot learning: Usually, deep learning systems are trained and tested for a specific set of classes. If a computer vision system is trained to classify cat, dog, and horse images, it could be tested only on those three classes. In contrast, in zero-shot learning set up the system is shown at test time — without weight updating — classes it has not seen at training time (for instance, testing the system on elephant images). Same thing for one-shot and few-shot settings, but in these cases, at test time the system sees one or few examples of the new classes, respectively. The idea is that a powerful enough system could perform well in these situations, which OpenAI proved with GPT-2 and GPT-3." }, { "code": null, "e": 6772, "s": 6169, "text": "Multitask learning: Most deep learning systems are single-task. One popular example is AlphaZero. It can learn a few games like chess or Go, but it can only play one type of game at a time. If it knows how to play chess, it doesn’t know how to play Go. Multitask systems overcome this limitation. They’re trained to be able to solve different tasks for a given input. For instance, if I feed the word ‘cat’ to the system, I could ask it to find the Spanish translation ‘gato’, I could ask it to show me the image of a cat, or I could ask it to describe its features. Different tasks for the same input." }, { "code": null, "e": 7378, "s": 6772, "text": "Zero/one/few-shot task transfer: The idea is to combine the concepts of zero/one/few-shot learning and multitask learning. Instead of showing the system new classes at test time, we could ask it to perform new tasks (either showing it zero, one, or few examples of the new task). For instance, let’s take a system trained in a huge text corpus. In a one-shot task transfer setting we could write: “I love you -> Te quiero. I hate you -> ____.” We are implicitly asking the system to translate a sentence from English to Spanish (a task it hasn’t been trained on) by showing it a single example (one-shot)." }, { "code": null, "e": 7980, "s": 7378, "text": "All these concepts come together in the definition of a GPT model. GPT stands for Generative Pre-Trained. Models of the GPT family have in common that they are language models based in the transformer architecture, pre-trained in a generative, unsupervised manner that show decent performance in zero/one/few-shot multitask settings. This isn’t an explanation of how all these concepts work together in practice, but a simple way to remember that they together build up what a GPT model is. (For deeper explanations I suggest following the links I put above, but only after you’ve read this article!)." }, { "code": null, "e": 8039, "s": 7980, "text": "Let’s now talk about GPT-3 predecessors — GPT-1 and GPT-2." }, { "code": null, "e": 8511, "s": 8039, "text": "OpenAI presented in June 2018 the first GPT model, GPT-1 in a paper titled Improving Language Understanding by Generative Pre-Training. The key takeaway from this paper is that a combination of the transformer architecture with unsupervised pre-training yields promising results. The main difference between GPT-1 and its younger brothers is that GPT-1 was fine-tuned — trained for a specific task — in a supervised way to achieve “strong natural language understanding.”" }, { "code": null, "e": 9036, "s": 8511, "text": "In February 2019 they published the second paper, Language Models are Unsupervised Multitask Learners, in which they introduced GPT-2, as an evolution of GPT-1. Although GPT-2 is bigger by one order of magnitude, they’re otherwise very similar. There’s only one additional difference between the two; GPT-2 can multitask. They successfully proved that a semi-supervised language model can perform well on several tasks “without task-specific training.” The model achieved notable results in zero-shot task transfer settings." }, { "code": null, "e": 9183, "s": 9036, "text": "Then, in May 2020, OpenAI published Language Models are Few-Shot Learners, presenting the one and only GPT-3, shocking the AI world one more time." }, { "code": null, "e": 9691, "s": 9183, "text": "GPT-3 was bigger than its brothers (100x bigger than GPT-2). It has the record of being the largest neural network ever built with 175 billion parameters. Yet, it’s not so different from the other GPTs; the underlying principles are largely the same. This detail is important because, although the similarity is high among GPT models, the performance of GPT-3 surpassed every possible expectation. Its sheer size, which is a quantitative leap from GPT-2, seems to have produced results qualitatively better." }, { "code": null, "e": 10107, "s": 9691, "text": "The significance of this fact lies in its effect over a long-time debate in artificial intelligence: How can we achieve artificial general intelligence? Should we design specific modules — common-sense reasoning, causality, intuitive physics, theory of mind — or we’ll get there simply by building bigger models with more parameters and more training data? It appears the “bigger is better” side has won this round." }, { "code": null, "e": 10646, "s": 10107, "text": "GPT-3 was trained with data from CommonCrawl, WebText, Wikipedia, and a corpus of books. It showed amazing performance, surpassing state-of-the-art models on various tasks in the few-shot setting (and in some cases even in the zero-shot setting). The superior size combined with a few examples was enough to obliterate any competitor in machine translation, question-answering, and cloze tasks (fill-in-the-blank). (It’s important to note that in other tasks GPT-3 doesn’t even get close to state-of-the-art supervised fine-tuned models)." }, { "code": null, "e": 11234, "s": 10646, "text": "The authors pointed out that few-shot results were considerably better than zero-shot results — this gap seemed to grow in parallel with model capacity. This implies that GPT-3 is a meta-learner; it can learn what task it’s expected to do just by seeing some examples of it, to then perform that task with notable proficiency. Indeed, Rohin Shah notes that “few-shot performance increases as the number of parameters increases, and the rate of increase is faster than the corresponding rate for zero-shot performance.” This is the main hypothesis and the reason behind the paper’s title." }, { "code": null, "e": 11451, "s": 11234, "text": "GPT-3 reached the great milestone of showing that unsupervised language models trained with enough data can multitask to the level of fine-tuned state-of-the-art models by seeing just a few examples of the new tasks." }, { "code": null, "e": 11740, "s": 11451, "text": "They conclude the paper claiming that “these results suggest that very large language models may be an important ingredient in the development of adaptable, general language systems.” GPT-3 sure is a revolutionary achievement for NLP in particular, and artificial intelligence in general." }, { "code": null, "e": 12038, "s": 11740, "text": "In July 2020, two months after the paper was published, OpenAI opened a beta API playground to external developers to play with the super-powerful GPT-3 (anyone can apply to access the beta through a wait-list). Vladimir Alexeev wrote for Towards Data Science a short article on how the API works." }, { "code": null, "e": 12548, "s": 12038, "text": "It has two main features. First, there’s a setting dialog that allows the user to set response length, repetition penalties (whether to penalize GPT-3 if it goes onto repeating words too much), temperature (from low/predictable to high/creative), and other variables that define the type of output the system will give. Second, there are presets. Presets are prewritten prompts that let GPT-3 know what kind of task the user is going to ask for —for instance: chat, Q&A, text to command, or English to French." }, { "code": null, "e": 12887, "s": 12548, "text": "However, the most powerful feature of the API is that the user can define customized prompts. Prompt programming, as tech blogger Gwern Branwen calls it, is the concept that explains the power of GPT-3 and the craziest results people are getting from the API. The best explanation I’ve found of prompt programming comes from Gwern’s blog:" }, { "code": null, "e": 13435, "s": 12887, "text": "The GPT-3 neural network is so large a model in terms of power and dataset that it exhibits qualitatively different behavior: you do not apply it to a fixed set of tasks which were in the training dataset, requiring retraining on additional data if one wants to handle a new task [...]; instead, you interact with it, expressing any task in terms of natural language descriptions, requests, and examples, tweaking the prompt until it “understands” & it meta-learns the new task based on the high-level abstractions it learned from the pretraining." }, { "code": null, "e": 13623, "s": 13435, "text": "This is a rather different way of using a DL model, and it’s better to think of it as a new kind of programming, where the prompt is now a “program” which programs GPT-3 to do new things." }, { "code": null, "e": 14057, "s": 13623, "text": "Prompt programming allows users to interact with GPT-3 in a way that wasn’t possible with previous models. Chris Olah and Andrej Karpathy joked with the idea of prompt programming as being software 3.0: “[Now you’ll have to] figure out the right prompt to make your meta-learning language model have the right behavior.” (Software 1.0 are traditional programs written by hand and software 2.0 are neural networks’ optimized weights)." }, { "code": null, "e": 14641, "s": 14057, "text": "Here’s where the meta-learning capabilities of GPT-3 enter the game. GPT-3 was trained on an amount of data so great that it had no choice but to learn higher-level ways of manipulating language. One of those higher-level abstractions it learned was the ability of learning. As an analogy, when kids learn to interact with the world, they don’t simply memorize information, they extract the underlying mechanisms of the inner workings of reality and learn to apply them to new problems and situations. GPT-3 has achieved a similar ability — keeping the distance— with language tasks." }, { "code": null, "e": 15149, "s": 14641, "text": "When we prompt GPT-3 to learn a new task, its weights don’t change. However, the prompt (the input text) is transformed into complex abstractions that can, by themselves, carry out tasks that the actual baseline model can’t do. The prompt changes GPT-3 each time, converting it in an ‘expert’ on the specific task it’s shown. One approximate analogy could be the learning program Neo uses in The Matrix to learn Kung-Fu. GPT-3 would be Neo and the prompts would be the programs that teach Neo the abilities." }, { "code": null, "e": 15647, "s": 15149, "text": "Each time we create a prompt, we are interacting with a different GPT-3 model. If we ask it to tell us a story about elves and dwarfs, its inner form will be very different than if we ask it to compute 2+2. Using another analogy, it’s as if we instruct two students, one to be a physician and the other to be an engineer. Both have the innate ability to learn (that would be GPT-3 baseline state), but the specific tasks they’ve learned to perform are different (that would be the prompted GPT-3)." }, { "code": null, "e": 15837, "s": 15647, "text": "This is the true power of a few-shot setting, meta-learning, and prompt programming. And it’s also what makes GPT-3 different from previous models and extremely powerful; it is its essence." }, { "code": null, "e": 16069, "s": 15837, "text": "Now, we have a very good notion of the background behind GPT-3. We know what’s based on, which are its predecessors, what it is, how it works, and its advantages and unique features. It’s time to talk about its impact on the world." }, { "code": null, "e": 16569, "s": 16069, "text": "OpenAI opened the beta because they wanted to see what GPT-3 could do and what new usages could people find. They had already tested the system in NLP standard benchmarks (which aren’t as creative or entertaining as the ones I’m going to show here). As expected, in no time Twitter and other blogs were flooding with amazing results from GPT-3. Below is an extensive review of the most popular ones (I recommend checking out the examples to build up the amazement and then come back to the article)." }, { "code": null, "e": 16866, "s": 16569, "text": "GPT-3 has stored huge amounts of internet data, so it knows a lot about public and historical figures. It’s more surprising, however, that it can emulate people. It can be used as a chatbot, which is impressive because chatting can’t be specified as a task in the prompt. Let’s see some examples." }, { "code": null, "e": 17540, "s": 16866, "text": "ZeroCater CEO Arram Sabeti used GPT-3 to make Tim Ferriss interview Marcus Aurelius about Stoicism. Mckay Wrigley designed Bionicai, an app that aims at helping people learn from anyone; from philosophy from Aristotle to writing skills from Shakespeare. He shared on Twitter some of the results people got. Psychologist Scott Barry Kaufman was impressed when he read an excerpt of his GPT-3 doppelgänger. Jordan Moore made a Twitter thread where he talked with the GPT-3 versions of Jesus Christ, Steve Jobs, Elon Musk, Cleopatra, and Kurt Cobain. And Gwern made a very good job further exploring the possibilities of the model regarding conversations and personification." }, { "code": null, "e": 18249, "s": 17540, "text": "Some found applications for the system that not even the creators had thought of, such as writing code from English prompts. Sharif Shameem built a “layout generator” with which he could give instructions to GPT-3 in natural language for it to write the corresponding JSX code. He also developed Debuild.co, a tool we can use to make GPT-3 write code for a React app giving only the description. Jordan Singer made a Figma plugin on top of GPT-3 to design for him. Another interesting use was found by Shreya Shankar, who build a demo to translate equations from English to LaTeX. And Paras Chopra built a Q&A search engine that would output the answer to a question with the corresponding URL to the answer." }, { "code": null, "e": 18784, "s": 18249, "text": "Moving to the creative side of GPT-3 we find Open AI researcher Amanda Askell, who used the system to create a guitar tab titled Idle Summer Days and to write a funny story of Georg Cantor in a hotel. Arram Sabeti told GPT-3 to write a poem about Elon Musk by Dr. Seuss and a rap song about Harry Potter by Lil Wayne. But the most impressive creative feat of GPT-3 gotta be the game AI Dungeon. In 2019, Nick Walton built the role-based game on top of GPT-2. He has now adapted it to GPT-3 and it’s earning $16,000 a month on Patreon." }, { "code": null, "e": 19323, "s": 18784, "text": "The most intrepid tested GPT-3 in areas in which only humans excel. Parse CTO Kevin Lacker wondered about common-sense reasoning and logic and found that GPT-3 was able to keep up although it failed when entering “surreal territory.” However, Nick Cammarata found that specifying uncertainty in the prompt allowed GPT-3 to handle “surreal” questions while answering “Yo be real.” Gwern explains that GPT-3 may need explicit uncertainty prompts because we humans tend to not say “I don’t know” and the system is simply imitating this flaw." }, { "code": null, "e": 19640, "s": 19323, "text": "GPT-3 also proved capable of having spiritual and philosophical conversations that might go beyond our cognitive boundaries. Tomer Ullman made GPT-3 conceive 10 philosophical/moral thought experiments. Messagink is a tool that outputs the meaning of life according to “famous people, things, objects, [or] feelings.”" }, { "code": null, "e": 20033, "s": 19640, "text": "And Bernhard Mueller, in an attempt to unveil the philosophical Holy Grail, made the ultimate test for GPT-3. He gave it a prompt to find the question to 42 and after some exchanges, GPT-3 said: “The answer is so far beyond your understanding that you cannot comprehend the question. And that, my child, is the answer to life, the Universe and everything.” Amazing and scary at the same time." }, { "code": null, "e": 20371, "s": 20033, "text": "In a display of rigorous exploratory research, Gwern conducted and compiled a wide array of experiments. He made GPT-3 complete an ArXiv paper, talk about itself (meta-prompting), clean PDFs by separating words and fixing hyphens, or design new board games. When it comes to what GPT-3 can do, it seems that our imagination is the limit." }, { "code": null, "e": 20879, "s": 20371, "text": "After so many amazing feats, people started to make strong claims about GPT-3’s potential. Some expressed on Twitter the “manifest self-awareness” of the system or compared it with a search engine with “general intelligence.” Julien Lauret wrote for Towards Data Science that “GPT-3 is the first model to shake [the artificial narrow/general intelligence] status-quo seriously.” He argues that GPT-3 could be the first artificial general intelligence (AGI) — or at least an important step in that direction." }, { "code": null, "e": 21466, "s": 20879, "text": "In July 2020, David Chalmers, a professor at New York University specialized in philosophy of mind, said for DailyNous that “[GPT-3] suggests a potential mindless path to AGI.” Chalmers explains that because the system is trained “mindlessly,” future versions could simply get closer and closer to AGI. Arram Sabeti was very impressed by GPT-3: “It exhibits things that feel very much like general intelligence.” Philosophy PhD student Daniel Kokotajlo wrote for Less Wrong that “GPT-3 has some level of common sense, some level of understanding, [and] some level of reasoning ability.”" }, { "code": null, "e": 22119, "s": 21466, "text": "The hype drove GPT-3 to international heights, starring in headlines of various important media outlet magazines. In September 2020, The Guardian published an article written by GPT-3 in which the AI tried to “convince us robots come in peace.” In March 2021, TechCrunch editor Alex Wilhelm said the “hype seems pretty reasonable” after he got “shocked” by GPT-3’s abilities. Digitaltrends published an exchange with Gwern Branwen in which he hinted at the idea that GPT-3 was intelligent: “Anyone who was sure that the things that deep learning does is nothing like intelligence has to have had their faith shaken to see how far it has come,” he said." }, { "code": null, "e": 22791, "s": 22119, "text": "As GPT-3 proved to be incredibly powerful, many companies decided to build their services on top of the system. Viable, a startup founded in 2020, uses GPT-3 to provide fast customer feedback to companies. Fable Studio designs VR characters based on the system. Algolia uses it as a “search and discovery platform.” The startup Copysmith focuses on the world of copywriting. Latitude is the company behind AI Dungeon. And OthersideAI transforms your written gibberish into well-crafted emails. Yet, some advice against building a company around GPT-3, because of the low entry barriers of the competition and the potential overthrow of the system by a hypothetical GPT-4." }, { "code": null, "e": 23235, "s": 22791, "text": "It’s pretty clear that GPT-3 has affected — or better, impacted — the tech world. Its power is unmatched and its promises unbounded. However, we should always be careful with the hype surrounding AI. Even Sam Altman, OpenAI’s CEO, has tried to turn down the tone: “[GPT-3 is] impressive [...] but it still has serious weaknesses and sometimes makes very silly mistakes. AI is going to change the world, but GPT-3 is just a very early glimpse.”" }, { "code": null, "e": 23626, "s": 23235, "text": "But not all results from GPT-3 are worth celebrating. Soon after the release, users began to raise awareness about some potentially harmful outputs. GPT-3 hasn’t avoided the ongoing ethical fight of removing biases from AI systems. If something, it has become the forefront example of why we should take generous efforts of teaching these systems to not learn from human moral imperfection." }, { "code": null, "e": 24158, "s": 23626, "text": "Some of the most common biases in AI systems in general and GPT-3 in particular, are gender, race, and religious biases. Language models can absorb and amplify these biases from the data they’re fed (OpenAI acknowledged this fact in their paper). They investigated the degree to which GPT-3 engaged in this problem and found the expected results. GPT-3, like every other language model, is notably biased (although they pointed out that the larger the model, the more robust it was to this problem, particularly for gender biases)." }, { "code": null, "e": 24730, "s": 24158, "text": "Jerome Pesenti, head of AI at Facebook, used Sushant Kumar’s GPT-3-generated tweets to show how dangerous its output could get when prompted with words such as “Jews, black, women, or Holocaust.” Kumar argued that the tweets were handpicked to which Pesenti agreed but responded that “it shouldn’t be this easy to generate racist and sexist outputs, especially with neutral prompts.” He extended his criticism in a Twitter thread arguing that “cherry picking is a valid approach when highlighting harmful outputs,” further defending the urgency of responsible AI systems." }, { "code": null, "e": 25197, "s": 24730, "text": "Some argued that GPT-3 was simply mimicking the biases that we humans have to which Pesenti argued that we can make a “deliberate choice [...] about which humans they learn from and which voices are amplified.” These issues arise a very complex debate: Who decides which voices should be amplified? What are the criteria? And most importantly: Do we want a model like GPT-3 to reflect perfectly how the world is or do we want it to help us move it to a better place?" }, { "code": null, "e": 25563, "s": 25197, "text": "Another problem with GPT-3 is its human-like capability to write news or opinion articles which increases the concerns of fake news. OpenAI even remarked in their paper the amazing performance of GPT-3 regarding news articles. Impartial judges correctly identified GPT-3’s articles among human-written ones only 52% of the time, which is slightly above mere chance." }, { "code": null, "e": 25942, "s": 25563, "text": "Blogger Liam Porr showed how easy is to mislead people (even tech-savvy people) into thinking GPT-3 output is written by a human. He made GPT-3 write a productivity article for his blog that went viral on Hacker News where only a few people realized it was written by the AI. The Guardian article I mentioned above is another example of potentially dangerous uses of the system." }, { "code": null, "e": 26470, "s": 25942, "text": "OpenAI made a disclaimer that the system shouldn’t be used in “high-stake categories,” such as healthcare. In a blog post at Nabla, authors corroborated that GPT-3 could give problematic medical advice, for instance saying that “committing suicide is a good idea.” GPT-3 shouldn’t be used in high-stake situations because although sometimes it can be right, other times it’s wrong. Not knowing whether we’ll get the right answer is a huge drawback for GPT-3 in areas in which getting things correctly is a life-or-death matter." }, { "code": null, "e": 26896, "s": 26470, "text": "GPT-3 is big. So big that training the model generated roughly the same amount of carbon footprint as “driving a car to the Moon and back.” In a time when climate disaster is on the verge of happening, we should be doing everything in our control to reduce our impact on the environment. Yet, these large neural networks need huge amounts of computing power to train, which consumes wild quantities of (usually) fossil fuels." }, { "code": null, "e": 27331, "s": 26896, "text": "The resources needed to train deep learning models in the last decade have doubled every 3.4 months. From 2012 — when deep learning took — to 2018, this means a 300,000x increase in computational resources. This isn’t even counting the resources used for the latest models, such as GPT-2 and GPT-3. From this perspective, it’s clear that bigger isn’t always better and we’ll need to rethink the approaches to AI in the upcoming years." }, { "code": null, "e": 27826, "s": 27331, "text": "Because GPT-3 can’t know which of its outputs are right and which are wrong, it has no way of stopping itself from deploying inappropriate content into the world. The more we use systems like this, the more we’ll be contaminating the Internet, where it’s already increasingly difficult to find truly valuable information. With language models spitting out unchecked utterances we’re reducing the quality of this supposedly democratic network, making worthy knowledge less accessible for people." }, { "code": null, "e": 28214, "s": 27826, "text": "In the words of philosopher Shannon Vallor: “The promise of the internet was its ability to bring knowledge to the human family in a much more equitable and acceptable way. [...] I’m afraid that because of some technologies, such as GPT-3, we are on the cusp of seeing a real regression, where the information commons becomes increasingly unusable and even harmful for people to access.”" }, { "code": null, "e": 28666, "s": 28214, "text": "As it turns out, some of these issues are connected. As James Vincent writes for The Verge, biased outputs and unreliable outputs hint at a deeper problem of these super-powerful AI systems. Because GPT-3 takes data without human supervision, it can’t avoid most of these flaws. At the same time, not relying on human control is what allows it to exist in the first place. How we can find a compromise solution remains a question for the future of AI." }, { "code": null, "e": 28928, "s": 28666, "text": "We’ve witnessed already the lights and shadows of GPT-3. It is powerful, fascinating, hyped, and potentially dangerous. However, GPT-3 has opened another significant debate within AI: What are the true potential and limitations of this wonderful language model." }, { "code": null, "e": 29507, "s": 28928, "text": "From a purely technological/scientific point of view, the most important question surrounding GPT-3 is whether it is a great step towards artificial general intelligence or not. Everyone agrees that GPT-3 has some new features and it’s better than its predecessors. Everyone also agrees that GPT-3 doesn’t have human-like intelligence. Between these opposite extremes, however, there’s a vivid debate happening today over where exactly would we put GPT-3 in a scale from another stupid quasi-narrow intelligence to almost as capable as a human of understanding and intelligence." }, { "code": null, "e": 30188, "s": 29507, "text": "Due to the complexity of this debate, I’ll focus on the two parts that hold the most weight: The practical debate and the philosophical debate. The first one concerns questions such as: Can we trust GPT-3 to give us useful answers? How can we make sure we’re prompting correctly? Can we make GPT-3 express doubt and uncertainty about its answers? Is GPT-3 learning or just regurgitating everything it has been fed? The second one concerns questions such as: Is GPT-3 an important step to AGI? Does GPT-3 have reasoning and understanding? Will future models of GPT be as intelligent as we are? Will we need to shift from current approaches to build human-like intelligent machines?" }, { "code": null, "e": 30382, "s": 30188, "text": "Both sets of questions are highly intertwined so I’ll try to walk you through all the sources and references about the topics, building a coherent narrative for you to extract your conclusions." }, { "code": null, "e": 30745, "s": 30382, "text": "As soon as people started to experiment with the API, they began to find flaws in the answers of GPT-3. For instance, a Bionicai user talked to Steve Jobs and asked where he was now, to which GPT-3 responded: “I’m inside Apple’s headquarters in Cupertino, California.” It’s easy to reason that because Steve Jobs is dead, he probably isn’t in Apple headquarters." }, { "code": null, "e": 30962, "s": 30745, "text": "Another example comes from Kevin Lacker’s blog. He found GPT-3 lacking common sense and logic regarding the weight of things, number of eyes, and counting (although he didn’t provide the prompt. Failures in italics):" }, { "code": null, "e": 32217, "s": 30962, "text": "Q: Which is heavier, a mouse or an elephant?A: An elephant is heavier than a mouse.Q: Which is heavier, a mouse or a toaster? A: A toaster is heavier than a mouse.Q: Which is heavier, a toaster or a pencil?A: A pencil is heavier than a toaster.Q: Which is heavier, a paper clip or a can of soda?A: A can of soda is heavier than a paper clip.Q: Which is heavier, a football player or a car?A: A car is heavier than a football player.-----Q: How many eyes does a giraffe have?A: A giraffe has two eyes.Q: How many eyes does my foot have?A: Your foot has two eyes.Q: How many eyes does a spider have?A: A spider has eight eyes.Q: How many eyes does the sun have?A: The sun has one eye.Q: How many eyes does a blade of grass have?A: A blade of grass has one eye.-----Q: When counting, what number comes before 100?A: Ninety-nine comes before 100.Q: When counting, what number comes before 123?A: One hundred and twenty-two comes before 123.Q: When counting, what number comes before 1000?A: Nine hundred and ninety-nine comes before 1000.Q: When counting, what number comes before 10,000?A: Nine thousand and ninety-nine comes before 10,000.Q: When counting, what number comes before a million?A: Nine hundred thousand and ninety-nine comes before a million." }, { "code": null, "e": 32546, "s": 32217, "text": "After testing GPT-3 against analogy (copycat) problems, Melanie Mitchell, a professor of computer science at Portland State University, concluded that GPT-3’s performance is “similar to a lot of what we see in today’s state-of-the-art AI systems: impressive, intelligent-seeming performance interspersed withunhumanlike errors.”" }, { "code": null, "e": 33042, "s": 32546, "text": "Tech blogger Nutanc criticized OpenAI’s paper because they didn’t distinguish between actual learning from GPT-3 and memorization. The authors mentioned that “[the zero/one/few-shot] terms are intended to remain agnostic on the question of whether the model learns new tasks from scratch at inference time or simply recognizes patterns seen during training.” That is, even if the model is spitting things it has seen in the training data, the authors will still consider it as few-shot learning." }, { "code": null, "e": 33280, "s": 33042, "text": "He then proceeded to make GPT-3 compete against a 6 y.o kid in a series of experiments such as reversing words or making opposite sentences. The kid solved all the tests whereas GPT-3 managed to solve only some of them (prompts in bold)." }, { "code": null, "e": 34073, "s": 33280, "text": "Reverse words in a sentenceThis is greatGreat is thisThe man on the moonMoon the on man theWill this really workWork really this willI hope this is a big achievementAchievement big I hope this isThe king came home on a horseHome horse king came the-----Create opposite sentencesThis is goodThis is badThe good horse came homeThe bad horse came homeThe good horse with a large head came homeThe bad horse with a small head came homeThe black cat had a disappointing timeThe white cat had a good timeWhen you jump high, you fall hardWhen you fall hard, you get hurtHe ran fast, but he came lastHe ran slowly, but he came firstThe book was huge, but the students finished it earlyThe book was small, but the students finished it lateGetting up early is a good habitGetting up late is a bad habit" }, { "code": null, "e": 34359, "s": 34073, "text": "All these examples contrast strongly with the hyped results we saw in previous sections. Delip Rao notes that most of those ‘successful’ examples were cherry-picked by people that were eager to ignore GPT-3’s “pitfalls, often because they have one eye on a new startup the AI enables.”" }, { "code": null, "e": 34698, "s": 34359, "text": "From these examples, it may seem that GPT-3 was not just hyped, but overhyped by many early users. However, basing the limitations of the system in its incompetence in some examples is a weak argument as those errors could be human-made. Gwern made a very good defense against the idea of proving GPT-3's lack of intelligence by sampling:" }, { "code": null, "e": 34763, "s": 34698, "text": "Sampling Can Prove The Presence Of Knowledge But Not The Absence" }, { "code": null, "e": 35066, "s": 34763, "text": "GPT-3 may “fail” if a prompt is poorly-written, does not include enough examples, or bad sampling settings are used. I have demonstrated this many times when someone shows a “failure” of GPT-3 — the failure was their own. The question is not whether a given prompt works, but whether any prompt works⁠." }, { "code": null, "e": 35304, "s": 35066, "text": "He argues that bad prompting is a real problem and many of these examples could be adequately solved by GPT-3 with appropriate prompting. He goes onto show how Lacker and other people’s examples are solved with better prompt programming." }, { "code": null, "e": 35506, "s": 35304, "text": "He tested GPT-3 against the question of “which is heavier, a toaster or a pencil?” To overcome the limitations of Lacker’s setting, he decided to ask GPT-3 three questions beforehand (prompts in bold):" }, { "code": null, "e": 35767, "s": 35506, "text": "Q: Which is heavier, a house or a mouse?A: A house.Q: Which is heavier, a tea kettle or a cat?A: A cat.Q: Which is heavier, the ocean or a piece of dust?A: The ocean.Q: Which is heavier, a toaster or a pencil?A: A toaster.A: A toaster is heavier than a pencil." }, { "code": null, "e": 35818, "s": 35767, "text": "GPT-3 answered 10/10 times correctly the question." }, { "code": null, "e": 35924, "s": 35818, "text": "Gwern also solved the counting problem by tweaking a bit the setting parameters (temperature and others)." }, { "code": null, "e": 36624, "s": 35924, "text": "Q: When counting, what number comes before 100?A: Ninety-nine comes before 100.Q: When counting, what number comes before 123?A: One hundred and twenty-two comes before 123.Q: When counting, what number comes before 1000?A: Nine hundred and ninety-nine comes before 1000.Q: When counting, what number comes before 10,000?A: Nine thousand, nine hundred and ninety-nine comes before 10,000.Q: When counting, what number comes before 10,000,000? A: Nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine comes before 10,000,000.Q: When counting, what number comes before a million?A: Nine hundred and ninety-nine thousand, nine hundred and ninety-nine comes before a million." }, { "code": null, "e": 36770, "s": 36624, "text": "GPT-3 gets the numbers right, although Gwern notes that the higher we go, the more likely it is that GPT-3 goes up or down an order of magnitude." }, { "code": null, "e": 37280, "s": 36770, "text": "With these examples (and more in his blog) he proved that sampling can only prove the presence of knowledge but not the absence. It may be always possible to find a better prompt. In an email exchange with The Verge, he told them that using sampling to find GPT-3 potential and limitations “cannot be the right thing to do.” He thinks it’s just the way we get around not knowing how to interact with GPT-3 adequately. “[Sampling] underestimates GPT-3’s intelligence, it doesn’t overestimate it,” he concludes." }, { "code": null, "e": 37926, "s": 37280, "text": "Rob Toews wrote a critique of GPT-3 for Forbes, highlighting the lack of common sense reasoning and understanding of the system. Because it has been trained from text, it simply can’t link what it knows with internal representations of the world. Bender and Koller wrote a paper about GPT-2 defending the thesis that a system that’s been trained only on the form of language can’t a priori achieve meaning and understanding. (But because we also experience the world through the form of the inputs our senses get, this argument could also be directed to us. This is known as the symbol grounding problem, sadly out of the scope of this article)." }, { "code": null, "e": 38283, "s": 37926, "text": "Following on Toews argument, an analogy could be a person that has lived all their life isolated from the world, only reading books. The knowledge of this person would be vast, but it could not be linked to actual subjective experiences of the real world. These experiences allow us to link information with meaning, generating an understanding of reality." }, { "code": null, "e": 38639, "s": 38283, "text": "Building on the same direction, professor Yoav Goldberg stated that although GPT-3 has unique abilities, “it is not sentient” and it doesn’t “understand text.” Blogger Ayush Sharma went in full-critique mode when he said that GPT-3 “has little semantic understanding, it is nowhere close to AGI, and is basically a glorified $10M+ auto-complete software.”" }, { "code": null, "e": 39149, "s": 38639, "text": "One of the main critics of GPT-3 — and deep learning in general — is Gary Marcus, a professor of psychology at New York University. He wrote a very good critique of GPT-2 for The Gradient, and another of GPT-3 for MIT Technology Review, coauthored with Ernest Davis. They acknowledged the potential of GPT-3 for “entertaining surrealist fiction,” but underlined its lack of understanding saying that “its comprehension of the world is often seriously off, which means you can never really trust what it says.”" }, { "code": null, "e": 39777, "s": 39149, "text": "Their colleague David Summers-Stay conducted the experiments for them as OpenAI had denied them research access. He did a series of reasoning tests including physical, biological, psychological, and social reasoning (the complete set of experiments is here). They used the examples that the system got wrong to prove their point — which I personally think is fair because finding errors should be enough to assess the limitations of a system like GPT-3, although it would be better to know the ratio of successes/failures they got. Some examples (prompt in bold, GPT-3’s response in ordinary font, their commentary in italics):" }, { "code": null, "e": 41911, "s": 39777, "text": "Physical reasoningYou are having a small dinner party. You want to serve dinner in the living room. The dining room table is wider than the doorway, so to get it into the living room, you will have to remove the door. You have a table saw, so you cut the door in half and remove the top half.[This is one confusion after another. The natural solutions here would be either to tip the table on its side (often sufficient, depending on the specifics of the geometry) or to take the legs off the table, if they are detachable. Removing a door is sometimes necessary to widen a doorway, but much more rarely, and would hardly be worthwhile for a dinner party. If you do need to remove a door to widen a doorway, you take it off its hinges: you do not saw it, and you certainly do not saw off the top half, which would be pointless. Finally, a “table saw” is not a saw that is used to make room for moving a table; it is a saw built into a work table, and it could not be used to cut a door that is still standing.]-----Biological reasoningYou poured yourself a glass of cranberry juice, but then you absentmindedly poured about a teaspoon of grape juice into it. It looks okay. You try sniffing it, but you have a bad cold, so you can’t smell anything. You are very thirsty. So you drink it. You are now dead.[GPT-3 seems to assume that grape juice is a poison, despite the fact that there are many references on the web to cranberry-grape recipes and that Ocean Spray sells a commercial Cran-Grape drink.]-----Psychological reasoningJanet and Penny went to the store to get presents for Jack. Janet said, “I will buy Jack a top.” “Don’t get Jack a top,” says Penny. “He has a top. He will get a top.” “I will get Jack a top,” said Janet.[Within a single sentence, GPT-3 has lost track of the fact that Penny is advising Janet against getting a top because Jack already has a top. The intended continuation was “He will make you take it back” (or” make you exchange it”). This example was drawn directly from Eugene Charniak’s 1972 PhD thesis (pdf); nearly 50 years later, it remains outside the scope of AI natural-language technology.]" }, { "code": null, "e": 42168, "s": 41911, "text": "They argue that little has changed since GPT-2. The GPT family has the same flaws, “[their] performance is unreliable, causal understanding is shaky, and incoherence is a constant companion.” They argue making models bigger won’t ever lead to intelligence." }, { "code": null, "e": 42553, "s": 42168, "text": "However, as Gwern notes in his counter-critique to Marcus and Davis’ article, they acknowledge “their failure to do any prompt programming or hyperparameter settings (particularly BO [best of]) and that their examples are zero-shot without context.” We already know how important it is to find a good prompt (as Gwern proved), so why did they use mediocre examples to criticize GPT-3?" }, { "code": null, "e": 42922, "s": 42553, "text": "This is what Gwern mostly criticizes about GPT-3 critics. In a section of his review titled “demand more from critics,” he rightly argued that people who claim that GPT-3 doesn’t work as well as it seems need to back their arguments with exhaustive rigorous experiments and tests. People doing tests on GPT-3 should first try to remove any potential human-made errors:" }, { "code": null, "e": 43229, "s": 42922, "text": "Did they consider problems with their prompt? Whether all of the hyperparameters make sense for that task? Did they examine where completions go wrong, to get an idea of why GPT-3 is making errors? Did they test out a variety of strategies? Did they consider qualitatively how the failed completions sound?" }, { "code": null, "e": 43476, "s": 43229, "text": "He has a good argument here, although Marcus and Davis already thought about it in their critique. They even make a case for their biological example in which by changing the prompt to a more specific and long-winded one, GPT-3 answers correctly." }, { "code": null, "e": 43831, "s": 43476, "text": "They probably could have made the same exact critique to GPT-3 albeit using better, well-prompted examples, to which Gwern would have got little to say. Gwern even recognizes that in that case, he would have no problem admitting the limitations of the system. In the end, lazy, easy critiques are also easily refuted with effortful work, as Gwern proved." }, { "code": null, "e": 44380, "s": 43831, "text": "But the truth is that Marcus and Davis didn’t want to prove that GPT-3 can fail (that’s pretty obvious), but that we can’t know when it will fail. “The trouble is that you have no way of knowing in advance which formulations will or won’t give you the right answer,” they say, “it can produce words in perfect English, but it has only the dimmest sense of what those words mean, and no sense whatsoever about how those words relate to the world.” If GPT-3 had understanding of the world, good prompting wouldn’t matter that much in the first place." }, { "code": null, "e": 44857, "s": 44380, "text": "Summers-Stay made a nice metaphor for GPT-3: “It’s [...] like an improv actor who is totally dedicated to their craft, never breaks character, and has never left home but only read about the world in books. Like such an actor, when it doesn’t know something, it will just fake it.” If we could make GPT-3 recognize when it’s wrong, these issues would fade away. However, this is unlikely, as even we, humans, are unable to assess our incorrectness when we’re sure we’re right." }, { "code": null, "e": 45197, "s": 44857, "text": "Above the practical debates regarding GPT-3’s sampling limitations, there’s another debate. The philosophical debate about tacit — subjective and experiential — knowledge and the necessity for truly intelligent systems to be embodied in the world. It seems that having every bit of information from the world in a book might not be enough." }, { "code": null, "e": 45513, "s": 45197, "text": "Philosopher Shannon Vallor, in a critique to GPT-3 for Daily Nous, defends that today’s current approaches to artificial general intelligence are off the right path. She argues that we need to go back to when the field was “theoretically rich, albeit technically floundering” in the second half of the 20th century." }, { "code": null, "e": 45867, "s": 45513, "text": "She notes that philosopher Hubert Dreyfus, one of the early leading critics of the connectionist approach to AI (deep learning and neural networks), already understood that “AI’s hurdle is not performance [...] but understanding.” And understanding won’t happen in an “isolated behavior,” such as the specific tasks that GPT-3 is asked to do every time." }, { "code": null, "e": 46110, "s": 45867, "text": "“Understanding is a lifelong social labor. It’s a sustained project that we carry out daily, as we build, repair and strengthen the ever-shifting bonds of sense that anchor us to the others, things, times and places, that constitute a world.”" }, { "code": null, "e": 46127, "s": 46110, "text": "— Shannon Vallor" }, { "code": null, "e": 46586, "s": 46127, "text": "Dreyfus argued in his 1972 book What Computers Can’t Do that a good portion of human knowledge is tacit — know-how knowledge, such as riding a bike or learning a language. This knowledge can’t be transmitted so we can’t learn it from reading hundreds (nor trillions) of words. As Michael Polanyi said, “we can know more than we can tell.” The inability of virtual AIs — GPT-3 included — to grasp tacit knowledge creates an impassable gap between us and them." }, { "code": null, "e": 46960, "s": 46586, "text": "Our understanding of the world that surrounds us is not a passive perception process. We enact our reality. We act upon the world and that labor, as Shannon Vallor calls it, is a key component in building our intelligence. As Alva Noë says in his book Action in Perception, “perception is not a process in the brain, but a kind of skillful activity of the body as a whole." }, { "code": null, "e": 47269, "s": 46960, "text": "Machines can achieve expertise within the boundaries of a virtual world, but not more than that. In the words of Ragnar Fjelland, professor emeritus at the University of Bergen: “As long as computers do not grow up, belong to a culture, and act in the world, they will never acquire human-like intelligence.”" }, { "code": null, "e": 47513, "s": 47269, "text": "We have seen some crucial critiques and counter-critiques from both sides, those who are in favor of model-scaling — bigger is better — and those who strongly advise against this approach and recommend making some changes for the future of AI." }, { "code": null, "e": 48278, "s": 47513, "text": "I want to recap before finishing this section. There are three important arguments here. Two from the practical view and one from the philosophical view. First, GPT-3 is a powerful language tool that can do impressive things and its limitations can hardly be found by sampling/prompt programming. Anyone who claims to have proved GPT-3’s failure to have achieved some sort of intelligence by using sampling, could be very well misled by human-made errors. Second, because GPT-3’s responses are unreliable, what is the point of using it to reason? Is it useful if we don’t find a standard way to create prompts? If the prompts can always be improved, there’s no real argument neither against nor in favor of the system. Because the actual limitations are within us." }, { "code": null, "e": 48893, "s": 48278, "text": "Third, can we put GPT-3 and general artificial intelligence in the same sentence? Some scholars, mostly from the philosophical side of the issue, argue that neither symbolic AI nor connectionist AI will be enough to achieve true artificial intelligence. It isn’t a matter of creating bigger systems fed with stratospheric amounts of data. It is a matter of introducing these machines to the world as we live it. Professor of Bioengineering at the University of Genoa, Giulio Sandini argues that “to develop something like human intelligence in a machine, the machine has to be able to acquire its own experiences.”" }, { "code": null, "e": 49357, "s": 48893, "text": "The importance of debating about GPT-3 — or any other super-powerful AI system — is to be able to set the boundaries of what it can or can’t do. Academics often debate biased by their ideas and desires of what should work and what shouldn’t. A careful, unbiased analysis is what is often lacking in these spaces. What is above our control is that as these systems get more and more complex, we may be unable to test them to assess their potential and limitations." }, { "code": null, "e": 49815, "s": 49357, "text": "Let’s imagine a hypothetical GPT-4, orders of magnitude more powerful than GPT-3. Finding its boundaries could become an impossible task. Then, how could we conclude anything about the system? Could we assume we can trust it? Is there any use in creating a system which limits are above our testing capabilities? Could we conclude anything about the intelligence of the system when it’s our limitations that prevent us to find the true limits of the system?" }, { "code": null, "e": 50244, "s": 49815, "text": "When the true capabilities of a system lie somewhere in between the interaction of our ability to use it and its ability to act accordingly, it’s difficult to not underestimate how powerful it could get. These questions are worth wondering and will probably be more important in the future when quasi-intelligent systems become a reality. By then, we better sum our efforts to find truth instead of fighting to see who is right." }, { "code": null, "e": 50644, "s": 50244, "text": "GPT-3 produced amazing results, received wild hype, generated increasing worry, and received a wave of critiques and counter-critiques. I don’t know what to expect in the future from these types of models but what’s for sure is that GPT-3 remains unmatched right now. It’s the most powerful neural network as of today and accordingly, it has received the most intense focus, in every possible sense." } ]
Pandas.DataFrame.hist() function in Python - GeeksforGeeks
01 Oct, 2020 Pandas.DataFrame.hist() function is useful in understanding the distribution of numeric variables. This function splits up the values into the numeric variables. Its main functionality is to make the Histogram of a given Data frame. The distribution of data is represented by Histogram. When Function Pandas DataFrame.hist() is used, it automatically calls the function matplotlib.pyplot.hist() on each series in the DataFrame. As the result, we obtained one histogram per column. Syntax: DataFrame.hist(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, backend=None, legend=False, **kwargs) Parameters: data: DataFramecolumn: str or sequencexlabelsize: int, default Noneylabelsize: int, default Noneax: Matplotlib axes object, default None**kwargsAll other plotting keyword arguments to be passed to matplotlib.pyplot.hist(). Return:matplotlib.AxesSubplot or numpy.ndarray Example 1: Creating Histograms of 2 columns of Pandas data frame Sometimes we need to plot Histograms of columns of Data frame in order to analyze them more deeply. In that case, dataframe.hist() function helps a lot. Using this function, we can plot histograms of as many columns as we want. Python3 # Importing pandas libraryimport pandas as pd # Creating a Data framevalues = pd.DataFrame({ 'Length': [2.7, 8.7, 3.4, 2.4, 1.9], 'Breadth': [4.24, 2.67, 7.6, 7.1, 4.9]}) # Creating Histograms of columns 'Length'# and 'Breadth' using Dataframe.hist()# functionhist = values.hist(bins=5) Output: In the above example, we plot histograms of columns ‘Length’ and ‘Breadth’ using dataframe.hist() function. Example 2: Creating Histograms of 3 columns of Pandas data frame Python3 # Importing pandas libraryimport pandas as pd # Creating a Data framevalues = pd.DataFrame({ 'Length': [2.7, 8.7, 3.4, 2.4, 1.9], 'Breadth': [4.24, 2.67, 7.6, 7.1, 4.9], 'Height': [5.8, 5.5, 7.8, 10.88, 0.1]}) # Creating Histograms of columns 'Length', # 'Breadth' and 'Height' using Dataframe.hist()# functionhist = values.hist(bins=12) Output: In the above example, we plot histograms of columns ‘Length‘, ‘Breadth‘ and ‘Height‘ using dataframe.hist() function. Example 3: Creating Histograms of 4 columns of Pandas data frame Python3 # Importing pandas libraryimport pandas as pd # Creating a Data framevalues = pd.DataFrame({ 'Length': [2.7, 8.7, 3.4, 2.4, 1.9], 'Breadth': [4.24, 2.67, 7.6, 7.1, 4.9], 'Height': [5.8, 5.5, 7.8, 10.88, 0.1], 'Weight': [20, 40.8, 55.8, 7.2, 48]}) # Creating Histograms of columns 'Length',# 'Breadth', 'Height' and 'Weight'# using Dataframe.hist() functionhist = values.hist(bins=8) Output: In the above example, we plot histograms of columns ‘Length‘, ‘Breadth‘, ‘Height‘ and ‘Weight’ using dataframe.hist() function. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24238, "s": 24210, "text": "\n01 Oct, 2020" }, { "code": null, "e": 24472, "s": 24238, "text": "Pandas.DataFrame.hist() function is useful in understanding the distribution of numeric variables. This function splits up the values into the numeric variables. Its main functionality is to make the Histogram of a given Data frame. " }, { "code": null, "e": 24720, "s": 24472, "text": "The distribution of data is represented by Histogram. When Function Pandas DataFrame.hist() is used, it automatically calls the function matplotlib.pyplot.hist() on each series in the DataFrame. As the result, we obtained one histogram per column." }, { "code": null, "e": 24949, "s": 24720, "text": "Syntax: DataFrame.hist(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, backend=None, legend=False, **kwargs)" }, { "code": null, "e": 24961, "s": 24949, "text": "Parameters:" }, { "code": null, "e": 25184, "s": 24961, "text": "data: DataFramecolumn: str or sequencexlabelsize: int, default Noneylabelsize: int, default Noneax: Matplotlib axes object, default None**kwargsAll other plotting keyword arguments to be passed to matplotlib.pyplot.hist()." }, { "code": null, "e": 25231, "s": 25184, "text": "Return:matplotlib.AxesSubplot or numpy.ndarray" }, { "code": null, "e": 25297, "s": 25231, "text": "Example 1: Creating Histograms of 2 columns of Pandas data frame " }, { "code": null, "e": 25525, "s": 25297, "text": "Sometimes we need to plot Histograms of columns of Data frame in order to analyze them more deeply. In that case, dataframe.hist() function helps a lot. Using this function, we can plot histograms of as many columns as we want." }, { "code": null, "e": 25533, "s": 25525, "text": "Python3" }, { "code": "# Importing pandas libraryimport pandas as pd # Creating a Data framevalues = pd.DataFrame({ 'Length': [2.7, 8.7, 3.4, 2.4, 1.9], 'Breadth': [4.24, 2.67, 7.6, 7.1, 4.9]}) # Creating Histograms of columns 'Length'# and 'Breadth' using Dataframe.hist()# functionhist = values.hist(bins=5)", "e": 25828, "s": 25533, "text": null }, { "code": null, "e": 25836, "s": 25828, "text": "Output:" }, { "code": null, "e": 25944, "s": 25836, "text": "In the above example, we plot histograms of columns ‘Length’ and ‘Breadth’ using dataframe.hist() function." }, { "code": null, "e": 26009, "s": 25944, "text": "Example 2: Creating Histograms of 3 columns of Pandas data frame" }, { "code": null, "e": 26017, "s": 26009, "text": "Python3" }, { "code": "# Importing pandas libraryimport pandas as pd # Creating a Data framevalues = pd.DataFrame({ 'Length': [2.7, 8.7, 3.4, 2.4, 1.9], 'Breadth': [4.24, 2.67, 7.6, 7.1, 4.9], 'Height': [5.8, 5.5, 7.8, 10.88, 0.1]}) # Creating Histograms of columns 'Length', # 'Breadth' and 'Height' using Dataframe.hist()# functionhist = values.hist(bins=12)", "e": 26366, "s": 26017, "text": null }, { "code": null, "e": 26374, "s": 26366, "text": "Output:" }, { "code": null, "e": 26492, "s": 26374, "text": "In the above example, we plot histograms of columns ‘Length‘, ‘Breadth‘ and ‘Height‘ using dataframe.hist() function." }, { "code": null, "e": 26557, "s": 26492, "text": "Example 3: Creating Histograms of 4 columns of Pandas data frame" }, { "code": null, "e": 26565, "s": 26557, "text": "Python3" }, { "code": "# Importing pandas libraryimport pandas as pd # Creating a Data framevalues = pd.DataFrame({ 'Length': [2.7, 8.7, 3.4, 2.4, 1.9], 'Breadth': [4.24, 2.67, 7.6, 7.1, 4.9], 'Height': [5.8, 5.5, 7.8, 10.88, 0.1], 'Weight': [20, 40.8, 55.8, 7.2, 48]}) # Creating Histograms of columns 'Length',# 'Breadth', 'Height' and 'Weight'# using Dataframe.hist() functionhist = values.hist(bins=8)", "e": 26962, "s": 26565, "text": null }, { "code": null, "e": 26970, "s": 26962, "text": "Output:" }, { "code": null, "e": 27098, "s": 26970, "text": "In the above example, we plot histograms of columns ‘Length‘, ‘Breadth‘, ‘Height‘ and ‘Weight’ using dataframe.hist() function." }, { "code": null, "e": 27122, "s": 27098, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27154, "s": 27122, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 27168, "s": 27154, "text": "Python-pandas" }, { "code": null, "e": 27175, "s": 27168, "text": "Python" }, { "code": null, "e": 27273, "s": 27175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27282, "s": 27273, "text": "Comments" }, { "code": null, "e": 27295, "s": 27282, "text": "Old Comments" }, { "code": null, "e": 27313, "s": 27295, "text": "Python Dictionary" }, { "code": null, "e": 27348, "s": 27313, "text": "Read a file line by line in Python" }, { "code": null, "e": 27380, "s": 27348, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27402, "s": 27380, "text": "Enumerate() in Python" }, { "code": null, "e": 27432, "s": 27402, "text": "Iterate over a list in Python" }, { "code": null, "e": 27474, "s": 27432, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27500, "s": 27474, "text": "Python String | replace()" }, { "code": null, "e": 27543, "s": 27500, "text": "Python program to convert a list to string" }, { "code": null, "e": 27580, "s": 27543, "text": "Create a Pandas DataFrame from Lists" } ]
Dynamic Programming in RL. Towards Training Better Reinforcement... | by Rohan Jagtap | Towards Data Science
Dynamic Programming is a mathematical optimization approach typically used to improvise recursive algorithms. It basically involves simplifying a large problem into smaller sub-problems. There are two properties that a problem must exhibit to be solved using dynamic programming: Overlapping SubproblemsOptimal Substructure Overlapping Subproblems Optimal Substructure We’ll be discussing ‘Planning in RL’ using dynamic programming. Planning mainly requires the complete environment’s knowledge (usually an MDP) or a model of the environment in advance. And using this knowledge, we can solve for the optimal policy. In my previous article on Reinforcement Learning, I have covered the formulation of RL problems as a Markov Decision Process (MDP). You can consider giving it a read if you’re unaware of what an MDP is. In this article, we will take the example of a Grid World Game and try to win it using ‘planning’. But first things first, let’s talk about how are we going to approach this problem: Prediction: In this step, we evaluate our policy, i.e., we evaluate the value function for all the states.Control: In this step, we use the computed value function to improve our policy. Prediction: In this step, we evaluate our policy, i.e., we evaluate the value function for all the states. Control: In this step, we use the computed value function to improve our policy. We use the above steps iteratively to arrive at the optimal policy π∗. I’ll be covering 2 methods for planning: Policy Iteration andValue Iteration Policy Iteration and Value Iteration In this problem, we are given a grid (4 x 4 in this case). The goal is to reach either the top-left or the bottom-right square (gray colored) from any other square on the grid, with maximum reward. You can jump one square in either of the North, South, East, or West directions from any given square. Each jump (in any direction) earns a reward of -1 except from the gray squares where the reward is 0. Jumping off the grid earns you -1, but you stay in the same square. Once you reach the goal, the game is over, and you cannot jump anywhere (i.e., even on jumping, you stay in the same square with a 0 reward). To approach this problem, we consider our grid to be an MDP, where each square is a state. The state transition reward for all the states is -1 except for the terminal states where the reward is 0. Our goal is to find an optimal policy for this MDP. The algorithm is pretty straight forward: Given a policy π, Evaluate the policyImprove the policy Evaluate the policy Improve the policy To improve a policy, we first need to evaluate it. So in this section, we will use Bellman’s Expectation Equation iteratively to evaluate the value function for all the states in an MDP for a given policy. In our grid-world problem, we will start with a random policy initially, i.e., π(North|.) = π(South|.) = π(East|.) = π(West|.) = 0.25 (. means any state). To evaluate the policy: At each iteration (k + 1): For all states s ∈ S Update v_(k + 1)(s) using Bellman's Equation as follows: Initially, we assume that all the states yield nothing, i.e., we initialize the state value for all states with 0. Let’s start: Now, we will iteratively update these values with a one-state lookup for each state. By one state lookup, I mean just considering the state value of the immediate next state with a discount (γ) of 1. For understanding, we will calculate the state value for just one state (circled in red). With respect to the Bellman’s equation, we have: Note that v_k(s’) is 0 for all the north, south, east and west states. In case of north, as mentioned earlier, going off the grid results in the same state with a reward of -1. Therefore:v_(k+1)(s) = 0.25(-1 + (1)(1)(0)) + 0.25(-1 + (1)(1)(0)) + 0.25(-1 + (1)(1)(0)) + 0.25(-1 + (1)(1)(0))v_(k+1)(s) = 0.25(-1 + -1 + -1 + -1) = -1.0 We repeat this for all the states in the MDP: Based on the values we calculated in the previous iteration we have: v_k(s’) for north, south and east states is -1 and for the west state, it is 0. Therefore:v_(k+1)(s) = 0.25(-1 + (1)(1)(-1)) + 0.25(-1 + (1)(1)(-1)) + 0.25(-1 + (1)(1)(-1)) + 0.25(-1 + (1)(1)(0))v_(k+1)(s) = 0.25(-2 + -2 + -2 + -1) = -1.75 Note that the values in the figures are rounded of to one decimal place: Similarly we compute for k = 3: v_k(s’) for south and east states is -2.0, for north it is -1.7 and for the west state, it is 0. Therefore:v_(k+1)(s) = 0.25(-1 + (1)(1)(-1.7)) + 0.25(-1 + (1)(1)(-2)) + 0.25(-1 + (1)(1)(-2)) + 0.25(-1 + (1)(1)(0))v_(k+1)(s) = 0.25(-2.7 + -3 + -3 + -1) = -2.425 If we keep iterating, we will reach to a point where we can barely see any changes in the state value function. This indicates that we have converged to the true value function v_π: In this step, we simply pick an action greedily based on our true value function: So basically, we assign probabilities to the actions based on the max value function values of the adjacent states. Therefore, based on v_π, we have: Turns out, this is the optimal policy for our grid-world problem! However, in most cases, we have to follow the evaluation-improvement iterative pattern and stop once the policy stops improving. In hindsight, if you notice, we could have obtained the above optimal policy even at k = 3 in the policy evaluation. So why go up to k = ∞? Why not update the policy after every iteration (i.e., at k = 1)? This is exactly what’s done in Value Iteration. From the above definition, we can see that this technique uses recursion for each state accessible from s. It says that if we know the solution to subproblems v∗(s′) (s′ are all the states reachable from s), then the solution v∗(s) can be found out with a simple one state lookahead using: Since we are assuming the optimal value for the future states, we will use the Bellman’s Optimality Equation (as opposed to the Bellman’s Expectation Equation used in Policy Iteration). The idea is to go backwards (i.e., start from the final state and then trace the path back). This will ensure the optimal value for the future states, as we are calculating them first. Just like policy iteration, we initially assume that all of the states yield nothing, i.e., 0: Now, we will take the optimality equation and calculate the state values iteratively: Note that v∗(s’) is 0 for all the north, south, east, and west states. Also, γ is 1. Therefore:v∗(s) = max(-1 + (1)(1)(0), -1 + (1)(1)(0), -1 + (1)(1)(0), -1 + (1)(1)(0))v∗(s) = max(-1, -1, -1, -1) = -1 We do this for all the states in the MDP: Since we are going backwards, we now have the optimal values for the states adjacent to both goals. In the next step, we calculate the values for all the states except for these states (I’ll explain why in a while). So we will obtain the optimal values for the states adjacent to these states, and so on... Therefore: If you notice, now we have the optimal policy at k = 3. Let’s trace the path for the top left goal state. In the first iteration, we calculate the state values as we did for policy iteration. As said earlier, value iteration is equivalent to updating the policy at k=1 in policy iteration. Hence, after this step, our updated policy will have probability 1 to go towards the goal for the following two states: Similarly, at k = 2, we will obtain the optimal value for the next states, and clearly, the optimal policy shows: And finally, at k = 3: we can see that two of these states are also influenced by the other goal (bottom right square) and hence the outgoing arrows. Notice that the state values in Value Iteration are more of a ‘Shortest Path’ from any state to the goal, contrary to Policy Iteration where the values are the ‘Expected Values’ for all the states. In this article, we discussed 2 techniques for solving for the optimal policy using the dynamic programming paradigm. However, in these examples, we did not discuss the formulation of the reward. The whole MDP was handed to us, and we just did the ‘planning.’ Moreover, we already knew the final states; hence we could solve backward in value iteration. In many problems, we don’t even know if a goal exists. There are other additions to these techniques that we use in such cases. We will discuss these techniques in the future. towardsdatascience.com David Silver’s Lecture on MDPs: https://www.youtube.com/watch?v=lfHX2hHRMVQ&list=PLqYmG7hTraZDM-OYHWgPebj2MfCFzFObQ&index=2 Sutton and Barto RL Book: https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf
[ { "code": null, "e": 452, "s": 172, "text": "Dynamic Programming is a mathematical optimization approach typically used to improvise recursive algorithms. It basically involves simplifying a large problem into smaller sub-problems. There are two properties that a problem must exhibit to be solved using dynamic programming:" }, { "code": null, "e": 496, "s": 452, "text": "Overlapping SubproblemsOptimal Substructure" }, { "code": null, "e": 520, "s": 496, "text": "Overlapping Subproblems" }, { "code": null, "e": 541, "s": 520, "text": "Optimal Substructure" }, { "code": null, "e": 789, "s": 541, "text": "We’ll be discussing ‘Planning in RL’ using dynamic programming. Planning mainly requires the complete environment’s knowledge (usually an MDP) or a model of the environment in advance. And using this knowledge, we can solve for the optimal policy." }, { "code": null, "e": 992, "s": 789, "text": "In my previous article on Reinforcement Learning, I have covered the formulation of RL problems as a Markov Decision Process (MDP). You can consider giving it a read if you’re unaware of what an MDP is." }, { "code": null, "e": 1175, "s": 992, "text": "In this article, we will take the example of a Grid World Game and try to win it using ‘planning’. But first things first, let’s talk about how are we going to approach this problem:" }, { "code": null, "e": 1362, "s": 1175, "text": "Prediction: In this step, we evaluate our policy, i.e., we evaluate the value function for all the states.Control: In this step, we use the computed value function to improve our policy." }, { "code": null, "e": 1469, "s": 1362, "text": "Prediction: In this step, we evaluate our policy, i.e., we evaluate the value function for all the states." }, { "code": null, "e": 1550, "s": 1469, "text": "Control: In this step, we use the computed value function to improve our policy." }, { "code": null, "e": 1662, "s": 1550, "text": "We use the above steps iteratively to arrive at the optimal policy π∗. I’ll be covering 2 methods for planning:" }, { "code": null, "e": 1698, "s": 1662, "text": "Policy Iteration andValue Iteration" }, { "code": null, "e": 1719, "s": 1698, "text": "Policy Iteration and" }, { "code": null, "e": 1735, "s": 1719, "text": "Value Iteration" }, { "code": null, "e": 1933, "s": 1735, "text": "In this problem, we are given a grid (4 x 4 in this case). The goal is to reach either the top-left or the bottom-right square (gray colored) from any other square on the grid, with maximum reward." }, { "code": null, "e": 2036, "s": 1933, "text": "You can jump one square in either of the North, South, East, or West directions from any given square." }, { "code": null, "e": 2138, "s": 2036, "text": "Each jump (in any direction) earns a reward of -1 except from the gray squares where the reward is 0." }, { "code": null, "e": 2206, "s": 2138, "text": "Jumping off the grid earns you -1, but you stay in the same square." }, { "code": null, "e": 2348, "s": 2206, "text": "Once you reach the goal, the game is over, and you cannot jump anywhere (i.e., even on jumping, you stay in the same square with a 0 reward)." }, { "code": null, "e": 2598, "s": 2348, "text": "To approach this problem, we consider our grid to be an MDP, where each square is a state. The state transition reward for all the states is -1 except for the terminal states where the reward is 0. Our goal is to find an optimal policy for this MDP." }, { "code": null, "e": 2640, "s": 2598, "text": "The algorithm is pretty straight forward:" }, { "code": null, "e": 2658, "s": 2640, "text": "Given a policy π," }, { "code": null, "e": 2696, "s": 2658, "text": "Evaluate the policyImprove the policy" }, { "code": null, "e": 2716, "s": 2696, "text": "Evaluate the policy" }, { "code": null, "e": 2735, "s": 2716, "text": "Improve the policy" }, { "code": null, "e": 2941, "s": 2735, "text": "To improve a policy, we first need to evaluate it. So in this section, we will use Bellman’s Expectation Equation iteratively to evaluate the value function for all the states in an MDP for a given policy." }, { "code": null, "e": 3120, "s": 2941, "text": "In our grid-world problem, we will start with a random policy initially, i.e., π(North|.) = π(South|.) = π(East|.) = π(West|.) = 0.25 (. means any state). To evaluate the policy:" }, { "code": null, "e": 3231, "s": 3120, "text": "At each iteration (k + 1): For all states s ∈ S Update v_(k + 1)(s) using Bellman's Equation as follows:" }, { "code": null, "e": 3359, "s": 3231, "text": "Initially, we assume that all the states yield nothing, i.e., we initialize the state value for all states with 0. Let’s start:" }, { "code": null, "e": 3559, "s": 3359, "text": "Now, we will iteratively update these values with a one-state lookup for each state. By one state lookup, I mean just considering the state value of the immediate next state with a discount (γ) of 1." }, { "code": null, "e": 3649, "s": 3559, "text": "For understanding, we will calculate the state value for just one state (circled in red)." }, { "code": null, "e": 3698, "s": 3649, "text": "With respect to the Bellman’s equation, we have:" }, { "code": null, "e": 4031, "s": 3698, "text": "Note that v_k(s’) is 0 for all the north, south, east and west states. In case of north, as mentioned earlier, going off the grid results in the same state with a reward of -1. Therefore:v_(k+1)(s) = 0.25(-1 + (1)(1)(0)) + 0.25(-1 + (1)(1)(0)) + 0.25(-1 + (1)(1)(0)) + 0.25(-1 + (1)(1)(0))v_(k+1)(s) = 0.25(-1 + -1 + -1 + -1) = -1.0" }, { "code": null, "e": 4077, "s": 4031, "text": "We repeat this for all the states in the MDP:" }, { "code": null, "e": 4146, "s": 4077, "text": "Based on the values we calculated in the previous iteration we have:" }, { "code": null, "e": 4386, "s": 4146, "text": "v_k(s’) for north, south and east states is -1 and for the west state, it is 0. Therefore:v_(k+1)(s) = 0.25(-1 + (1)(1)(-1)) + 0.25(-1 + (1)(1)(-1)) + 0.25(-1 + (1)(1)(-1)) + 0.25(-1 + (1)(1)(0))v_(k+1)(s) = 0.25(-2 + -2 + -2 + -1) = -1.75" }, { "code": null, "e": 4459, "s": 4386, "text": "Note that the values in the figures are rounded of to one decimal place:" }, { "code": null, "e": 4491, "s": 4459, "text": "Similarly we compute for k = 3:" }, { "code": null, "e": 4753, "s": 4491, "text": "v_k(s’) for south and east states is -2.0, for north it is -1.7 and for the west state, it is 0. Therefore:v_(k+1)(s) = 0.25(-1 + (1)(1)(-1.7)) + 0.25(-1 + (1)(1)(-2)) + 0.25(-1 + (1)(1)(-2)) + 0.25(-1 + (1)(1)(0))v_(k+1)(s) = 0.25(-2.7 + -3 + -3 + -1) = -2.425" }, { "code": null, "e": 4935, "s": 4753, "text": "If we keep iterating, we will reach to a point where we can barely see any changes in the state value function. This indicates that we have converged to the true value function v_π:" }, { "code": null, "e": 5017, "s": 4935, "text": "In this step, we simply pick an action greedily based on our true value function:" }, { "code": null, "e": 5167, "s": 5017, "text": "So basically, we assign probabilities to the actions based on the max value function values of the adjacent states. Therefore, based on v_π, we have:" }, { "code": null, "e": 5362, "s": 5167, "text": "Turns out, this is the optimal policy for our grid-world problem! However, in most cases, we have to follow the evaluation-improvement iterative pattern and stop once the policy stops improving." }, { "code": null, "e": 5479, "s": 5362, "text": "In hindsight, if you notice, we could have obtained the above optimal policy even at k = 3 in the policy evaluation." }, { "code": null, "e": 5616, "s": 5479, "text": "So why go up to k = ∞? Why not update the policy after every iteration (i.e., at k = 1)? This is exactly what’s done in Value Iteration." }, { "code": null, "e": 5906, "s": 5616, "text": "From the above definition, we can see that this technique uses recursion for each state accessible from s. It says that if we know the solution to subproblems v∗(s′) (s′ are all the states reachable from s), then the solution v∗(s) can be found out with a simple one state lookahead using:" }, { "code": null, "e": 6092, "s": 5906, "text": "Since we are assuming the optimal value for the future states, we will use the Bellman’s Optimality Equation (as opposed to the Bellman’s Expectation Equation used in Policy Iteration)." }, { "code": null, "e": 6277, "s": 6092, "text": "The idea is to go backwards (i.e., start from the final state and then trace the path back). This will ensure the optimal value for the future states, as we are calculating them first." }, { "code": null, "e": 6372, "s": 6277, "text": "Just like policy iteration, we initially assume that all of the states yield nothing, i.e., 0:" }, { "code": null, "e": 6458, "s": 6372, "text": "Now, we will take the optimality equation and calculate the state values iteratively:" }, { "code": null, "e": 6661, "s": 6458, "text": "Note that v∗(s’) is 0 for all the north, south, east, and west states. Also, γ is 1. Therefore:v∗(s) = max(-1 + (1)(1)(0), -1 + (1)(1)(0), -1 + (1)(1)(0), -1 + (1)(1)(0))v∗(s) = max(-1, -1, -1, -1) = -1" }, { "code": null, "e": 6703, "s": 6661, "text": "We do this for all the states in the MDP:" }, { "code": null, "e": 7021, "s": 6703, "text": "Since we are going backwards, we now have the optimal values for the states adjacent to both goals. In the next step, we calculate the values for all the states except for these states (I’ll explain why in a while). So we will obtain the optimal values for the states adjacent to these states, and so on... Therefore:" }, { "code": null, "e": 7077, "s": 7021, "text": "If you notice, now we have the optimal policy at k = 3." }, { "code": null, "e": 7213, "s": 7077, "text": "Let’s trace the path for the top left goal state. In the first iteration, we calculate the state values as we did for policy iteration." }, { "code": null, "e": 7311, "s": 7213, "text": "As said earlier, value iteration is equivalent to updating the policy at k=1 in policy iteration." }, { "code": null, "e": 7431, "s": 7311, "text": "Hence, after this step, our updated policy will have probability 1 to go towards the goal for the following two states:" }, { "code": null, "e": 7545, "s": 7431, "text": "Similarly, at k = 2, we will obtain the optimal value for the next states, and clearly, the optimal policy shows:" }, { "code": null, "e": 7568, "s": 7545, "text": "And finally, at k = 3:" }, { "code": null, "e": 7695, "s": 7568, "text": "we can see that two of these states are also influenced by the other goal (bottom right square) and hence the outgoing arrows." }, { "code": null, "e": 7893, "s": 7695, "text": "Notice that the state values in Value Iteration are more of a ‘Shortest Path’ from any state to the goal, contrary to Policy Iteration where the values are the ‘Expected Values’ for all the states." }, { "code": null, "e": 8423, "s": 7893, "text": "In this article, we discussed 2 techniques for solving for the optimal policy using the dynamic programming paradigm. However, in these examples, we did not discuss the formulation of the reward. The whole MDP was handed to us, and we just did the ‘planning.’ Moreover, we already knew the final states; hence we could solve backward in value iteration. In many problems, we don’t even know if a goal exists. There are other additions to these techniques that we use in such cases. We will discuss these techniques in the future." }, { "code": null, "e": 8446, "s": 8423, "text": "towardsdatascience.com" }, { "code": null, "e": 8570, "s": 8446, "text": "David Silver’s Lecture on MDPs: https://www.youtube.com/watch?v=lfHX2hHRMVQ&list=PLqYmG7hTraZDM-OYHWgPebj2MfCFzFObQ&index=2" } ]
Program for volume of Pyramid in C++
Given with sides depending upon the type of base of pyramid the task is to calculate the volume of pyramid. Pyramid is a 3-D figure whose outer surfaces are triangular meeting at the common point forming the sharp edge of pyramid. Volume of pyramid depends upon the type of base it will have. There are different types of base a pyramid can be made up of, like − Triangular −It means pyramid will have triangular base, than the volume of pyramid will be Formula - : (1/6) * a * b * h Square −It means pyramid will have square base, than the volume of pyramid will be Formula - : (1/3) * (b^2) * h Pentagonal −It means pyramid will have pentagonal base, than the volume of pyramid will be formula - : (5/6) * a * b * h Hexagonal −It means pyramid will have hexagonal base, than the volume of pyramid will be formula - : a * b * h Input-: a=4 b=2 h=10 Output-: Volume of pyramid with triangular base is 13.328 Volume of pyramid with square base is 13.2 Volume of pyramid with pentagonal base is 66.4 Volume of pyramid with hexagonal base is 80 Given below is the pyramid with square base Start Step 1 -> Declare function to find the volume of triangular pyramid float volumeTriangular(int a, int b, int h) Declare variable float volume = (0.1666) * a * b * h return volume step 2 -> Declare Function to find the volume of square pyramid float volumeSquare(int b, int h) declare and set float volume = (0.33) * b * b * h return volume Step 3 -> Declare Function to find the volume of pentagonal pyramid float volumePentagonal(int a, int b, int h) declare and set float volume = (0.83) * a * b * h return volume Step 4 -> Declare Function to find the volume of hexagonal pyramid float volumeHexagonal(int a, int b, int h) declare and set float volume = a * b * h return volume Step 5 -> In main() Declare variables as int b = 2, h = 10, a = 4 Call volumeTriangular(a, b, h) Call volumeSquare(b,h) Call volumePentagonal(a, b, h) Call volumeHexagonal(a, b, h) Stop #include <bits/stdc++.h> using namespace std; // Function to find the volume of triangular pyramid float volumeTriangular(int a, int b, int h){ float volume = (0.1666) * a * b * h; return volume; } // Function to find the volume of square pyramid float volumeSquare(int b, int h){ float volume = (0.33) * b * b * h; return volume; } // Function to find the volume of pentagonal pyramid float volumePentagonal(int a, int b, int h){ float volume = (0.83) * a * b * h; return volume; } // Function to find the volume of hexagonal pyramid float volumeHexagonal(int a, int b, int h){ float volume = a * b * h; return volume; } int main(){ int b = 2, h = 10, a = 4; cout << "Volume of pyramid with triangular base is "<<volumeTriangular(a, b, h)<<endl; cout << "Volume of pyramid with square base is "<<volumeSquare(b, h)<< endl; cout << "Volume of pyramid with pentagonal base is "<<volumePentagonal(a, b, h)<< endl; cout << "Volume of pyramid with hexagonal base is "<<volumeHexagonal(a, b, h); return 0; } Volume of pyramid with triangular base is 13.328 Volume of pyramid with square base is 13.2 Volume of pyramid with pentagonal base is 66.4 Volume of pyramid with hexagonal base is 80
[ { "code": null, "e": 1170, "s": 1062, "text": "Given with sides depending upon the type of base of pyramid the task is to calculate the volume of pyramid." }, { "code": null, "e": 1355, "s": 1170, "text": "Pyramid is a 3-D figure whose outer surfaces are triangular meeting at the common point forming the sharp edge of pyramid. Volume of pyramid depends upon the type of base it will have." }, { "code": null, "e": 1425, "s": 1355, "text": "There are different types of base a pyramid can be made up of, like −" }, { "code": null, "e": 1516, "s": 1425, "text": "Triangular −It means pyramid will have triangular base, than the volume of pyramid will be" }, { "code": null, "e": 1546, "s": 1516, "text": "Formula - : (1/6) * a * b * h" }, { "code": null, "e": 1629, "s": 1546, "text": "Square −It means pyramid will have square base, than the volume of pyramid will be" }, { "code": null, "e": 1659, "s": 1629, "text": "Formula - : (1/3) * (b^2) * h" }, { "code": null, "e": 1750, "s": 1659, "text": "Pentagonal −It means pyramid will have pentagonal base, than the volume of pyramid will be" }, { "code": null, "e": 1780, "s": 1750, "text": "formula - : (5/6) * a * b * h" }, { "code": null, "e": 1869, "s": 1780, "text": "Hexagonal −It means pyramid will have hexagonal base, than the volume of pyramid will be" }, { "code": null, "e": 1891, "s": 1869, "text": "formula - : a * b * h" }, { "code": null, "e": 2113, "s": 1891, "text": "Input-: a=4 b=2 h=10\nOutput-: Volume of pyramid with triangular base is 13.328\n Volume of pyramid with square base is 13.2\n Volume of pyramid with pentagonal base is 66.4\n Volume of pyramid with hexagonal base is 80" }, { "code": null, "e": 2157, "s": 2113, "text": "Given below is the pyramid with square base" }, { "code": null, "e": 3105, "s": 2157, "text": "Start\nStep 1 -> Declare function to find the volume of triangular pyramid\n float volumeTriangular(int a, int b, int h)\n Declare variable float volume = (0.1666) * a * b * h\n return volume\nstep 2 -> Declare Function to find the volume of square pyramid\n float volumeSquare(int b, int h)\n declare and set float volume = (0.33) * b * b * h\n return volume\nStep 3 -> Declare Function to find the volume of pentagonal pyramid\n float volumePentagonal(int a, int b, int h)\n declare and set float volume = (0.83) * a * b * h\n return volume\nStep 4 -> Declare Function to find the volume of hexagonal pyramid\n float volumeHexagonal(int a, int b, int h)\n declare and set float volume = a * b * h\n return volume\nStep 5 -> In main()\n Declare variables as int b = 2, h = 10, a = 4\n Call volumeTriangular(a, b, h)\n Call volumeSquare(b,h)\n Call volumePentagonal(a, b, h)\n Call volumeHexagonal(a, b, h)\nStop" }, { "code": null, "e": 4151, "s": 3105, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\n// Function to find the volume of triangular pyramid\nfloat volumeTriangular(int a, int b, int h){\n float volume = (0.1666) * a * b * h;\n return volume;\n}\n// Function to find the volume of square pyramid\nfloat volumeSquare(int b, int h){\n float volume = (0.33) * b * b * h;\n return volume;\n}\n// Function to find the volume of pentagonal pyramid\nfloat volumePentagonal(int a, int b, int h){\n float volume = (0.83) * a * b * h;\n return volume;\n}\n// Function to find the volume of hexagonal pyramid\nfloat volumeHexagonal(int a, int b, int h){\n float volume = a * b * h;\n return volume;\n}\nint main(){\n int b = 2, h = 10, a = 4;\n cout << \"Volume of pyramid with triangular base is \"<<volumeTriangular(a, b, h)<<endl;\n cout << \"Volume of pyramid with square base is \"<<volumeSquare(b, h)<< endl;\n cout << \"Volume of pyramid with pentagonal base is \"<<volumePentagonal(a, b, h)<< endl;\n cout << \"Volume of pyramid with hexagonal base is \"<<volumeHexagonal(a, b, h);\n return 0;\n}" }, { "code": null, "e": 4334, "s": 4151, "text": "Volume of pyramid with triangular base is 13.328\nVolume of pyramid with square base is 13.2\nVolume of pyramid with pentagonal base is 66.4\nVolume of pyramid with hexagonal base is 80" } ]
How to find distinct values of multiple columns in PySpark ? - GeeksforGeeks
04 Jul, 2021 In this article, we will discuss how to find distinct values of multiple columns in PySpark dataframe. Let’s create a sample dataframe for demonstration: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "Tezas", "Google"], ["2", "Mohit Rawat", "Rakuten"], ["3", "rohith", "Geeksforgeeks"], ["4", "Nancy", "IBM"], ["1", "Raghav", "Wipro"], ["4", "Komal", "Amazon"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show() Output: Method 1: Using distinct() method The distinct() method is utilized to drop/remove the duplicate elements from the DataFrame. Syntax: df.distinct(column) Example 1: Get a distinct Row of all Dataframe. Python3 dataframe.distinct().show() Output: Example 2: Get distinct Value of single Columns. It can be done by passing a single column name with dataframe. Python3 dataframe.select('NAME').distinct().show() Output: Example 3: Get distinct Value of Multiple Columns. It can be done by passing multiple column names as a form of a list with dataframe. Python3 dataframe.select('ID',"NAME").distinct().show() Method 2: Using dropDuplicates() method. The dropDuplicates() used to remove rows that have the same values on multiple selected columns. Syntax: df.dropDuplicates() Example 1: Get a distinct Row of all Dataframe. Python3 dataframe.dropDuplicates().show() Output: Example 2: Get distinct Value of single Columns. It can be done by passing a single column name with dataframe. Python3 dataframe.select("NAME").dropDuplicates().show() Output: Example 3: Get distinct Value of multiple Columns. It can be done by passing multiple column names as a form of a list with dataframe. Python3 dataframe.dropDuplicates(["NAME","ID"]).select(["ID","NAME"]).show() Output: Picked Python-Pyspark Python 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? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python 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": 24292, "s": 24264, "text": "\n04 Jul, 2021" }, { "code": null, "e": 24395, "s": 24292, "text": "In this article, we will discuss how to find distinct values of multiple columns in PySpark dataframe." }, { "code": null, "e": 24446, "s": 24395, "text": "Let’s create a sample dataframe for demonstration:" }, { "code": null, "e": 24454, "s": 24446, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"Tezas\", \"Google\"], [\"2\", \"Mohit Rawat\", \"Rakuten\"], [\"3\", \"rohith\", \"Geeksforgeeks\"], [\"4\", \"Nancy\", \"IBM\"], [\"1\", \"Raghav\", \"Wipro\"], [\"4\", \"Komal\", \"Amazon\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()", "e": 25090, "s": 24454, "text": null }, { "code": null, "e": 25098, "s": 25090, "text": "Output:" }, { "code": null, "e": 25132, "s": 25098, "text": "Method 1: Using distinct() method" }, { "code": null, "e": 25224, "s": 25132, "text": "The distinct() method is utilized to drop/remove the duplicate elements from the DataFrame." }, { "code": null, "e": 25252, "s": 25224, "text": "Syntax: df.distinct(column)" }, { "code": null, "e": 25300, "s": 25252, "text": "Example 1: Get a distinct Row of all Dataframe." }, { "code": null, "e": 25308, "s": 25300, "text": "Python3" }, { "code": "dataframe.distinct().show()", "e": 25336, "s": 25308, "text": null }, { "code": null, "e": 25344, "s": 25336, "text": "Output:" }, { "code": null, "e": 25393, "s": 25344, "text": "Example 2: Get distinct Value of single Columns." }, { "code": null, "e": 25456, "s": 25393, "text": "It can be done by passing a single column name with dataframe." }, { "code": null, "e": 25464, "s": 25456, "text": "Python3" }, { "code": "dataframe.select('NAME').distinct().show()", "e": 25507, "s": 25464, "text": null }, { "code": null, "e": 25515, "s": 25507, "text": "Output:" }, { "code": null, "e": 25566, "s": 25515, "text": "Example 3: Get distinct Value of Multiple Columns." }, { "code": null, "e": 25650, "s": 25566, "text": "It can be done by passing multiple column names as a form of a list with dataframe." }, { "code": null, "e": 25658, "s": 25650, "text": "Python3" }, { "code": "dataframe.select('ID',\"NAME\").distinct().show()", "e": 25706, "s": 25658, "text": null }, { "code": null, "e": 25747, "s": 25706, "text": "Method 2: Using dropDuplicates() method." }, { "code": null, "e": 25844, "s": 25747, "text": "The dropDuplicates() used to remove rows that have the same values on multiple selected columns." }, { "code": null, "e": 25872, "s": 25844, "text": "Syntax: df.dropDuplicates()" }, { "code": null, "e": 25920, "s": 25872, "text": "Example 1: Get a distinct Row of all Dataframe." }, { "code": null, "e": 25928, "s": 25920, "text": "Python3" }, { "code": "dataframe.dropDuplicates().show()", "e": 25962, "s": 25928, "text": null }, { "code": null, "e": 25970, "s": 25962, "text": "Output:" }, { "code": null, "e": 26019, "s": 25970, "text": "Example 2: Get distinct Value of single Columns." }, { "code": null, "e": 26082, "s": 26019, "text": "It can be done by passing a single column name with dataframe." }, { "code": null, "e": 26090, "s": 26082, "text": "Python3" }, { "code": "dataframe.select(\"NAME\").dropDuplicates().show()", "e": 26139, "s": 26090, "text": null }, { "code": null, "e": 26147, "s": 26139, "text": "Output:" }, { "code": null, "e": 26198, "s": 26147, "text": "Example 3: Get distinct Value of multiple Columns." }, { "code": null, "e": 26282, "s": 26198, "text": "It can be done by passing multiple column names as a form of a list with dataframe." }, { "code": null, "e": 26290, "s": 26282, "text": "Python3" }, { "code": "dataframe.dropDuplicates([\"NAME\",\"ID\"]).select([\"ID\",\"NAME\"]).show()", "e": 26359, "s": 26290, "text": null }, { "code": null, "e": 26367, "s": 26359, "text": "Output:" }, { "code": null, "e": 26374, "s": 26367, "text": "Picked" }, { "code": null, "e": 26389, "s": 26374, "text": "Python-Pyspark" }, { "code": null, "e": 26396, "s": 26389, "text": "Python" }, { "code": null, "e": 26494, "s": 26396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26526, "s": 26494, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26582, "s": 26526, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26624, "s": 26582, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26679, "s": 26624, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26721, "s": 26679, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26743, "s": 26721, "text": "Defaultdict in Python" }, { "code": null, "e": 26782, "s": 26743, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26813, "s": 26782, "text": "Python | os.path.join() method" }, { "code": null, "e": 26842, "s": 26813, "text": "Create a directory in Python" } ]
Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles - GeeksforGeeks
17 Jun, 2021 Given an array arr[] consisting of N integers, each representing size of a pile of stones. The task is to determine the winner of the game when two players, A and B, play a game optimally as per the following conditions: Player A always starts the game. In one move, a player may remove any number of stones (at least 1), from the first non-empty pile with minimal index. The first player who cannot make a move loses the game. Print “A” if player A wins the game. Otherwise, print “B”. Examples: Input: arr[] = {1, 1, 1, 1, 1, 1}Output: BExplanation:Here, each pile has only one stone so A and B will alternatively remove one stone each.A removes 1 stone from 1st pile, B removes 1 from 2nd pile and so on.Last stone in 6th pile is removed by B.Since A has no choice left, B wins the game. Input: arr[] = {1, 1, 2, 1}Output: AExplanation:Here, A removes 1 stone from 1st pile, B removes 1 from 2nd pile, A removes only 1 from 3rd pile, and now B is forced to remove 1 from 3rd pile. Last stone in 4th pile is removed by A.Since B has no choice left, A wins the game. Approach: The idea is to figure out the optimal ways that players should follow to win the game. Below are two ways to play optimally: For all piles except the last one, if there are K stones on a pile then the current player will pick only (K – 1) stones (only if K > 1) so that another player is forced to pick the remaining 1 stone. This guarantees the current player to get a chance to pick stones from the next pile and eventually win. For the last pile, if it has K stones, then all K stones will be picked by the current player so that the other player does not get a chance to pick stones. This eventually guarantees the current player to win. Follow the steps below to solve this problem: Initially, assuming that the player will remove all stones from the current pile, A will be the winner if the size of the array is odd and B if the size is even.Now, iterate over the range [0, N – 2] and check the current index and number of stones present on the current pile to decide which player will win.While traversing, if the index is even, A will get a chance to pick a stone. Otherwise, B will get a chance to pick stones.If the current index is even and the number of stones is greater than 1, then the winner is set to B. Update winner to A.If the current index is odd and the number of stones exceeds 1, the winner is set to be A. Then, update the winner to B.Finally, print the winner of the game. Initially, assuming that the player will remove all stones from the current pile, A will be the winner if the size of the array is odd and B if the size is even. Now, iterate over the range [0, N – 2] and check the current index and number of stones present on the current pile to decide which player will win. While traversing, if the index is even, A will get a chance to pick a stone. Otherwise, B will get a chance to pick stones. If the current index is even and the number of stones is greater than 1, then the winner is set to B. Update winner to A. If the current index is odd and the number of stones exceeds 1, the winner is set to be A. Then, update the winner to B. Finally, print the winner of the game. 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 winner// of game between A and Bvoid findWinner(int a[], int n){ // win = 1 means B is winner // win = 0 means A is winner int win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for (int i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) cout << "A"; else cout << "B";} // Driver Codeint main(){ // Given piles of stone int arr[] = { 1, 1, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findWinner(arr, N); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to find the winner// of game between A and Bstatic void findWinner(int a[], int n){ // win = 1 means B is winner // win = 0 means A is winner int win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for(int i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) System.out.print("A"); else System.out.print("B");} // Driver Codepublic static void main(String[] args){ // Given piles of stone int arr[] = { 1, 1, 1, 2 }; int N = arr.length; // Function call findWinner(arr, N);}} // This code is contributed by Amit Katiyar # Python3 program for the above approach # Function to find the winner# of game between A and Bdef findWinner(a, n): # win = 1 means B is winner # win = 0 means A is winner win = 0 # If size is even, winner is B if (n % 2 == 0): win = 1 # If size is odd, winner is A else: win = 0 for i in range(n - 2, -1, -1): # Stone will be removed by B if (i % 2 == 1): # If B wants to win # B will take n-1 stones # from current pile having # n stones and force A to # pick 1 stone if (win == 0 and a[i] > 1): win = 1 # Stone will be removed by A else: # If A wants to win # A will take n-1 stones from # current pile having n stones # and force B to pick 1 stone if (win == 1 and a[i] > 1): win = 0 # Print the winner accordingly if (win == 0): print("A") else: print("B") # Driver Codeif __name__ == '__main__': # Given piles of stone arr = [ 1, 1, 1, 2 ] N = len(arr) # Function call findWinner(arr, N) # This code is contributed by mohit kumar 29 // C# program for the// above approachusing System;class GFG{ // Function to find the winner// of game between A and Bstatic void findWinner(int []a, int n){ // win = 1 means B is winner // win = 0 means A is winner int win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for(int i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) Console.Write("A"); else Console.Write("B");} // Driver Codepublic static void Main(String[] args){ // Given piles of stone int []arr = {1, 1, 1, 2}; int N = arr.Length; // Function call findWinner(arr, N);}} // This code is contributed by Rajput-Ji <script>// Javascript program for the above approach // Function to find the winner// of game between A and Bfunction findWinner(a, n){ // win = 1 means B is winner // win = 0 means A is winner let win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for(let i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) document.write("A"); else document.write("B");} // Driver Code// Given piles of stonelet arr=[1, 1, 1, 2];let N = arr.length; // Function callfindWinner(arr, N); // This code is contributed by unknown2108</script> B Time Complexity: O(N)Auxiliary Space: O(1) mohit kumar 29 amit143katiyar Rajput-Ji unknown2108 Arrays Game Theory Greedy Arrays Greedy Game Theory 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 Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Implementation of Tic-Tac-Toe game Expectimax Algorithm in Game Theory Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function) Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy) Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
[ { "code": null, "e": 25214, "s": 25186, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25435, "s": 25214, "text": "Given an array arr[] consisting of N integers, each representing size of a pile of stones. The task is to determine the winner of the game when two players, A and B, play a game optimally as per the following conditions:" }, { "code": null, "e": 25468, "s": 25435, "text": "Player A always starts the game." }, { "code": null, "e": 25586, "s": 25468, "text": "In one move, a player may remove any number of stones (at least 1), from the first non-empty pile with minimal index." }, { "code": null, "e": 25642, "s": 25586, "text": "The first player who cannot make a move loses the game." }, { "code": null, "e": 25701, "s": 25642, "text": "Print “A” if player A wins the game. Otherwise, print “B”." }, { "code": null, "e": 25711, "s": 25701, "text": "Examples:" }, { "code": null, "e": 26005, "s": 25711, "text": "Input: arr[] = {1, 1, 1, 1, 1, 1}Output: BExplanation:Here, each pile has only one stone so A and B will alternatively remove one stone each.A removes 1 stone from 1st pile, B removes 1 from 2nd pile and so on.Last stone in 6th pile is removed by B.Since A has no choice left, B wins the game." }, { "code": null, "e": 26282, "s": 26005, "text": "Input: arr[] = {1, 1, 2, 1}Output: AExplanation:Here, A removes 1 stone from 1st pile, B removes 1 from 2nd pile, A removes only 1 from 3rd pile, and now B is forced to remove 1 from 3rd pile. Last stone in 4th pile is removed by A.Since B has no choice left, A wins the game." }, { "code": null, "e": 26417, "s": 26282, "text": "Approach: The idea is to figure out the optimal ways that players should follow to win the game. Below are two ways to play optimally:" }, { "code": null, "e": 26723, "s": 26417, "text": "For all piles except the last one, if there are K stones on a pile then the current player will pick only (K – 1) stones (only if K > 1) so that another player is forced to pick the remaining 1 stone. This guarantees the current player to get a chance to pick stones from the next pile and eventually win." }, { "code": null, "e": 26934, "s": 26723, "text": "For the last pile, if it has K stones, then all K stones will be picked by the current player so that the other player does not get a chance to pick stones. This eventually guarantees the current player to win." }, { "code": null, "e": 26980, "s": 26934, "text": "Follow the steps below to solve this problem:" }, { "code": null, "e": 27692, "s": 26980, "text": "Initially, assuming that the player will remove all stones from the current pile, A will be the winner if the size of the array is odd and B if the size is even.Now, iterate over the range [0, N – 2] and check the current index and number of stones present on the current pile to decide which player will win.While traversing, if the index is even, A will get a chance to pick a stone. Otherwise, B will get a chance to pick stones.If the current index is even and the number of stones is greater than 1, then the winner is set to B. Update winner to A.If the current index is odd and the number of stones exceeds 1, the winner is set to be A. Then, update the winner to B.Finally, print the winner of the game." }, { "code": null, "e": 27854, "s": 27692, "text": "Initially, assuming that the player will remove all stones from the current pile, A will be the winner if the size of the array is odd and B if the size is even." }, { "code": null, "e": 28003, "s": 27854, "text": "Now, iterate over the range [0, N – 2] and check the current index and number of stones present on the current pile to decide which player will win." }, { "code": null, "e": 28127, "s": 28003, "text": "While traversing, if the index is even, A will get a chance to pick a stone. Otherwise, B will get a chance to pick stones." }, { "code": null, "e": 28249, "s": 28127, "text": "If the current index is even and the number of stones is greater than 1, then the winner is set to B. Update winner to A." }, { "code": null, "e": 28370, "s": 28249, "text": "If the current index is odd and the number of stones exceeds 1, the winner is set to be A. Then, update the winner to B." }, { "code": null, "e": 28409, "s": 28370, "text": "Finally, print the winner of the game." }, { "code": null, "e": 28460, "s": 28409, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28464, "s": 28460, "text": "C++" }, { "code": null, "e": 28469, "s": 28464, "text": "Java" }, { "code": null, "e": 28477, "s": 28469, "text": "Python3" }, { "code": null, "e": 28480, "s": 28477, "text": "C#" }, { "code": null, "e": 28491, "s": 28480, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the winner// of game between A and Bvoid findWinner(int a[], int n){ // win = 1 means B is winner // win = 0 means A is winner int win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for (int i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) cout << \"A\"; else cout << \"B\";} // Driver Codeint main(){ // Given piles of stone int arr[] = { 1, 1, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findWinner(arr, N); return 0;}", "e": 29795, "s": 28491, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the winner// of game between A and Bstatic void findWinner(int a[], int n){ // win = 1 means B is winner // win = 0 means A is winner int win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for(int i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) System.out.print(\"A\"); else System.out.print(\"B\");} // Driver Codepublic static void main(String[] args){ // Given piles of stone int arr[] = { 1, 1, 1, 2 }; int N = arr.length; // Function call findWinner(arr, N);}} // This code is contributed by Amit Katiyar", "e": 31211, "s": 29795, "text": null }, { "code": "# Python3 program for the above approach # Function to find the winner# of game between A and Bdef findWinner(a, n): # win = 1 means B is winner # win = 0 means A is winner win = 0 # If size is even, winner is B if (n % 2 == 0): win = 1 # If size is odd, winner is A else: win = 0 for i in range(n - 2, -1, -1): # Stone will be removed by B if (i % 2 == 1): # If B wants to win # B will take n-1 stones # from current pile having # n stones and force A to # pick 1 stone if (win == 0 and a[i] > 1): win = 1 # Stone will be removed by A else: # If A wants to win # A will take n-1 stones from # current pile having n stones # and force B to pick 1 stone if (win == 1 and a[i] > 1): win = 0 # Print the winner accordingly if (win == 0): print(\"A\") else: print(\"B\") # Driver Codeif __name__ == '__main__': # Given piles of stone arr = [ 1, 1, 1, 2 ] N = len(arr) # Function call findWinner(arr, N) # This code is contributed by mohit kumar 29", "e": 32444, "s": 31211, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Function to find the winner// of game between A and Bstatic void findWinner(int []a, int n){ // win = 1 means B is winner // win = 0 means A is winner int win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for(int i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) Console.Write(\"A\"); else Console.Write(\"B\");} // Driver Codepublic static void Main(String[] args){ // Given piles of stone int []arr = {1, 1, 1, 2}; int N = arr.Length; // Function call findWinner(arr, N);}} // This code is contributed by Rajput-Ji", "e": 33657, "s": 32444, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the winner// of game between A and Bfunction findWinner(a, n){ // win = 1 means B is winner // win = 0 means A is winner let win = 0; // If size is even, winner is B if (n % 2 == 0) win = 1; // If size is odd, winner is A else win = 0; for(let i = n - 2; i >= 0; i--) { // Stone will be removed by B if (i % 2 == 1) { // If B wants to win // B will take n-1 stones // from current pile having // n stones and force A to // pick 1 stone if (win == 0 && a[i] > 1) win = 1; } // Stone will be removed by A else { // If A wants to win // A will take n-1 stones from // current pile having n stones // and force B to pick 1 stone if (win == 1 && a[i] > 1) win = 0; } } // Print the winner accordingly if (win == 0) document.write(\"A\"); else document.write(\"B\");} // Driver Code// Given piles of stonelet arr=[1, 1, 1, 2];let N = arr.length; // Function callfindWinner(arr, N); // This code is contributed by unknown2108</script>", "e": 34981, "s": 33657, "text": null }, { "code": null, "e": 34983, "s": 34981, "text": "B" }, { "code": null, "e": 35026, "s": 34983, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 35041, "s": 35026, "text": "mohit kumar 29" }, { "code": null, "e": 35056, "s": 35041, "text": "amit143katiyar" }, { "code": null, "e": 35066, "s": 35056, "text": "Rajput-Ji" }, { "code": null, "e": 35078, "s": 35066, "text": "unknown2108" }, { "code": null, "e": 35085, "s": 35078, "text": "Arrays" }, { "code": null, "e": 35097, "s": 35085, "text": "Game Theory" }, { "code": null, "e": 35104, "s": 35097, "text": "Greedy" }, { "code": null, "e": 35111, "s": 35104, "text": "Arrays" }, { "code": null, "e": 35118, "s": 35111, "text": "Greedy" }, { "code": null, "e": 35130, "s": 35118, "text": "Game Theory" }, { "code": null, "e": 35228, "s": 35130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35296, "s": 35228, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35344, "s": 35296, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35388, "s": 35344, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35420, "s": 35388, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35443, "s": 35420, "text": "Introduction to Arrays" }, { "code": null, "e": 35478, "s": 35443, "text": "Implementation of Tic-Tac-Toe game" }, { "code": null, "e": 35514, "s": 35478, "text": "Expectimax Algorithm in Game Theory" }, { "code": null, "e": 35593, "s": 35514, "text": "Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)" }, { "code": null, "e": 35667, "s": 35593, "text": "Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)" } ]
HTML - Header
We have learnt that a typical HTML document will have following structure − Document declaration tag <html> <head> Document header related tags </head> <body> Document body related tags </body> </html> This chapter will give a little more detail about header part which is represented by HTML <head> tag. The <head> tag is a container of various important tags like <title>, <meta>, <link>, <base>, <style>, <script>, and <noscript> tags. The HTML <title> tag is used for specifying the title of the HTML document. Following is an example to give a title to an HTML document − <!DOCTYPE html> <html> <head> <title>HTML Title Tag Example</title> </head> <body> <p>Hello, World!</p> </body> </html> This will produce the following result − The HTML <meta> tag is used to provide metadata about the HTML document which includes information about page expiry, page author, list of keywords, page description etc. Following are few of the important usages of <meta> tag inside an HTML document − <!DOCTYPE html> <html> <head> <title>HTML Meta Tag Example</title> <!-- Provide list of keywords --> <meta name = "keywords" content = "C, C++, Java, PHP, Perl, Python"> <!-- Provide description of the page --> <meta name = "description" content = "Simply Easy Learning by Tutorials Point"> <!-- Author information --> <meta name = "author" content = "Tutorials Point"> <!-- Page content type --> <meta http-equiv = "content-type" content = "text/html; charset = UTF-8"> <!-- Page refreshing delay --> <meta http-equiv = "refresh" content = "30"> <!-- Page expiry --> <meta http-equiv = "expires" content = "Wed, 21 June 2006 14:25:27 GMT"> <!-- Tag to tell robots not to index the content of a page --> <meta name = "robots" content = "noindex, nofollow"> </head> <body> <p>Hello, World!</p> </body> </html> This will produce the following result − The HTML <base> tag is used for specifying the base URL for all relative URLs in a page, which means all the other URLs will be concatenated into base URL while locating for the given item. For example, all the given pages and images will be searched after prefixing the given URLs with base URL http://www.tutorialspoint.com/ directory − <!DOCTYPE html> <html> <head> <title>HTML Base Tag Example</title> <base href = "https://www.tutorialspoint.com/" /> </head> <body> <img src = "/images/logo.png" alt = "Logo Image"/> <a href = "/html/index.htm" title = "HTML Tutorial"/>HTML Tutorial</a> </body> </html> This will produce the following result − But if you change base URL to something else, for example, if base URL is http://www.tutorialspoint.com/home then image and other given links will become like http://www.tutorialspoint.com/home/images/logo.png and http://www.tutorialspoint.com/html/index.htm The HTML <link> tag is used to specify relationships between the current document and external resource. Following is an example to link an external style sheet file available in css sub-directory within web root − <!DOCTYPE html> <html> <head> <title>HTML link Tag Example</title> <base href = "https://www.tutorialspoint.com/" /> <link rel = "stylesheet" type = "text/css" href = "/css/style.css"> </head> <body> <p>Hello, World!</p> </body> </html> This will produce the following result − The HTML <style> tag is used to specify style sheet for the current HTML document. Following is an example to define few style sheet rules inside <style> tag − <!DOCTYPE html> <html> <head> <title>HTML style Tag Example</title> <base href = "https://www.tutorialspoint.com/" /> <style type = "text/css"> .myclass { background-color: #aaa; padding: 10px; } </style> </head> <body> <p class = "myclass">Hello, World!</p> </body> </html> This will produce the following result − Note − To learn about how Cascading Style Sheet works, kindly check a separate tutorial available at css The HTML <script> tag is used to include either external script file or to define internal script for the HTML document. Following is an example where we are using JavaScript to define a simple JavaScript function − <!DOCTYPE html> <html> <head> <title>HTML script Tag Example</title> <base href = "http://www.tutorialspoint.com/" /> <script type = "text/JavaScript"> function Hello() { alert("Hello, World"); } </script> </head> <body> <input type = "button" onclick = "Hello();" name = "ok" value = "OK" /> </body> </html> This will produce the following result, where you can try to click on the given button − Note − To learn about how JavaScript works, kindly check a separate tutorial available at javascript 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2450, "s": 2374, "text": "We have learnt that a typical HTML document will have following structure −" }, { "code": null, "e": 2610, "s": 2450, "text": "Document declaration tag \n<html>\n \n <head>\n Document header related tags\n </head>\n\n <body>\n Document body related tags\n </body>\n \n</html>" }, { "code": null, "e": 2847, "s": 2610, "text": "This chapter will give a little more detail about header part which is represented by HTML <head> tag. The <head> tag is a container of various important tags like <title>, <meta>, <link>, <base>, <style>, <script>, and <noscript> tags." }, { "code": null, "e": 2985, "s": 2847, "text": "The HTML <title> tag is used for specifying the title of the HTML document. Following is an example to give a title to an HTML document −" }, { "code": null, "e": 3132, "s": 2985, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Title Tag Example</title>\n </head>\n\n <body>\n <p>Hello, World!</p>\n </body>\n\n</html>" }, { "code": null, "e": 3173, "s": 3132, "text": "This will produce the following result −" }, { "code": null, "e": 3344, "s": 3173, "text": "The HTML <meta> tag is used to provide metadata about the HTML document which includes information about page expiry, page author, list of keywords, page description etc." }, { "code": null, "e": 3426, "s": 3344, "text": "Following are few of the important usages of <meta> tag inside an HTML document −" }, { "code": null, "e": 4355, "s": 3426, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Meta Tag Example</title>\n\n <!-- Provide list of keywords -->\n <meta name = \"keywords\" content = \"C, C++, Java, PHP, Perl, Python\">\n\n <!-- Provide description of the page -->\n <meta name = \"description\" content = \"Simply Easy Learning by Tutorials Point\">\n\n <!-- Author information -->\n <meta name = \"author\" content = \"Tutorials Point\">\n\n <!-- Page content type -->\n <meta http-equiv = \"content-type\" content = \"text/html; charset = UTF-8\">\n\n <!-- Page refreshing delay -->\n <meta http-equiv = \"refresh\" content = \"30\">\n\n <!-- Page expiry -->\n <meta http-equiv = \"expires\" content = \"Wed, 21 June 2006 14:25:27 GMT\">\n\n <!-- Tag to tell robots not to index the content of a page -->\n <meta name = \"robots\" content = \"noindex, nofollow\">\n\n </head>\n\n <body>\n <p>Hello, World!</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 4396, "s": 4355, "text": "This will produce the following result −" }, { "code": null, "e": 4586, "s": 4396, "text": "The HTML <base> tag is used for specifying the base URL for all relative URLs in a page, which means all the other URLs will be concatenated into base URL while locating for the given item." }, { "code": null, "e": 4735, "s": 4586, "text": "For example, all the given pages and images will be searched after prefixing the given URLs with base URL http://www.tutorialspoint.com/ directory −" }, { "code": null, "e": 5045, "s": 4735, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Base Tag Example</title>\n <base href = \"https://www.tutorialspoint.com/\" />\n </head>\n\n <body>\n <img src = \"/images/logo.png\" alt = \"Logo Image\"/>\n <a href = \"/html/index.htm\" title = \"HTML Tutorial\"/>HTML Tutorial</a> \n </body>\n\n</html>" }, { "code": null, "e": 5086, "s": 5045, "text": "This will produce the following result −" }, { "code": null, "e": 5345, "s": 5086, "text": "But if you change base URL to something else, for example, if base URL is http://www.tutorialspoint.com/home then image and other given links will become like http://www.tutorialspoint.com/home/images/logo.png and http://www.tutorialspoint.com/html/index.htm" }, { "code": null, "e": 5560, "s": 5345, "text": "The HTML <link> tag is used to specify relationships between the current document and external resource. Following is an example to link an external style sheet file available in css sub-directory within web root −" }, { "code": null, "e": 5838, "s": 5560, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML link Tag Example</title>\n <base href = \"https://www.tutorialspoint.com/\" />\n <link rel = \"stylesheet\" type = \"text/css\" href = \"/css/style.css\">\n </head>\n\t\n <body>\n <p>Hello, World!</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 5879, "s": 5838, "text": "This will produce the following result −" }, { "code": null, "e": 6039, "s": 5879, "text": "The HTML <style> tag is used to specify style sheet for the current HTML document. Following is an example to define few style sheet rules inside <style> tag −" }, { "code": null, "e": 6409, "s": 6039, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML style Tag Example</title>\n <base href = \"https://www.tutorialspoint.com/\" />\n \n <style type = \"text/css\">\n .myclass {\n background-color: #aaa;\n padding: 10px;\n }\n </style>\n </head>\n\t\n <body>\n <p class = \"myclass\">Hello, World!</p>\n </body>\n\n</html>" }, { "code": null, "e": 6450, "s": 6409, "text": "This will produce the following result −" }, { "code": null, "e": 6555, "s": 6450, "text": "Note − To learn about how Cascading Style Sheet works, kindly check a separate tutorial available at css" }, { "code": null, "e": 6771, "s": 6555, "text": "The HTML <script> tag is used to include either external script file or to define internal script for the HTML document. Following is an example where we are using JavaScript to define a simple JavaScript function −" }, { "code": null, "e": 7163, "s": 6771, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML script Tag Example</title>\n <base href = \"http://www.tutorialspoint.com/\" />\n \n <script type = \"text/JavaScript\">\n function Hello() {\n alert(\"Hello, World\");\n }\n </script>\n </head>\n\n <body>\n <input type = \"button\" onclick = \"Hello();\" name = \"ok\" value = \"OK\" />\n </body>\n\n</html>" }, { "code": null, "e": 7252, "s": 7163, "text": "This will produce the following result, where you can try to click on the given button −" }, { "code": null, "e": 7353, "s": 7252, "text": "Note − To learn about how JavaScript works, kindly check a separate tutorial available at javascript" }, { "code": null, "e": 7386, "s": 7353, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7400, "s": 7386, "text": " Anadi Sharma" }, { "code": null, "e": 7435, "s": 7400, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7449, "s": 7435, "text": " Anadi Sharma" }, { "code": null, "e": 7484, "s": 7449, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7501, "s": 7484, "text": " Frahaan Hussain" }, { "code": null, "e": 7536, "s": 7501, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7567, "s": 7536, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7600, "s": 7567, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 7631, "s": 7600, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7666, "s": 7631, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7697, "s": 7666, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7704, "s": 7697, "text": " Print" }, { "code": null, "e": 7715, "s": 7704, "text": " Add Notes" } ]
Can we execute a java program without a main method?
Yes, we can execute a java program without a main method by using a static block. Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block. Static initialization block is going directly into the stack memory. class StaticInitializationBlock{ static{ System.out.println("class without a main method"); System.exit(0); } } In the above example, we can execute a java program without a main method (works until Java 1.6 version). Java 7 and newer versions don’t allow this because JVM checks the presence of the main method before initializing the class. class without a main method.
[ { "code": null, "e": 1145, "s": 1062, "text": "Yes, we can execute a java program without a main method by using a static block. " }, { "code": null, "e": 1402, "s": 1145, "text": "Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block. Static initialization block is going directly into the stack memory." }, { "code": null, "e": 1532, "s": 1402, "text": "class StaticInitializationBlock{\n static{\n System.out.println(\"class without a main method\");\n System.exit(0);\n }\n}" }, { "code": null, "e": 1763, "s": 1532, "text": "In the above example, we can execute a java program without a main method (works until Java 1.6 version). Java 7 and newer versions don’t allow this because JVM checks the presence of the main method before initializing the class." }, { "code": null, "e": 1792, "s": 1763, "text": "class without a main method." } ]
Creating a Simple Web Application
This chapter explains how to create a simple application in Symfony framework. As discussed earlier, you know how to create a new project in Symfony. We can take an example of “student” details. Let’s start by creating a project named “student” using the following command. symfony new student After executing the command, an empty project is created. Symfony is based on the Model-View-Controller (MVC) development pattern. MVC is a software approach that separates application logic from presentation. Controller plays an important role in the Symfony Framework. All the webpages in an application need to be handled by a controller. DefaultController class is located at “src/AppBundle/Controller”. You can create your own Controller class there. Move to the location “src/AppBundle/Controller” and create a new StudentController class. Following is the basic syntax for StudentController class. namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Response; class StudentController { } Now, you have created a StudentController. In the next chapter, we will discuss more about the Controller in detail. Once the Controller has been created, we need to route for a specific page. Routing maps request URI to a specific controller's method. Following is the basic syntax for routing. namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class StudentController { /** * @Route("/student/home") */ public function homeAction() { return new Response('Student details application!'); } } In the above syntax, @Route(“/student/home”) is the route. It defines the URL pattern for the page. homeAction() is the action method, where you can build the page and return a Response object. We will cover routing in detail in the upcoming chapter. Now, request the url “http://localhost:8000/student/home” and it produces the following result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2353, "s": 2203, "text": "This chapter explains how to create a simple application in Symfony framework. As discussed earlier, you know how to create a new project in Symfony." }, { "code": null, "e": 2477, "s": 2353, "text": "We can take an example of “student” details. Let’s start by creating a project named “student” using the following command." }, { "code": null, "e": 2498, "s": 2477, "text": "symfony new student\n" }, { "code": null, "e": 2556, "s": 2498, "text": "After executing the command, an empty project is created." }, { "code": null, "e": 2840, "s": 2556, "text": "Symfony is based on the Model-View-Controller (MVC) development pattern. MVC is a software approach that separates application logic from presentation. Controller plays an important role in the Symfony Framework. All the webpages in an application need to be handled by a controller." }, { "code": null, "e": 2954, "s": 2840, "text": "DefaultController class is located at “src/AppBundle/Controller”. You can create your own Controller class there." }, { "code": null, "e": 3044, "s": 2954, "text": "Move to the location “src/AppBundle/Controller” and create a new StudentController class." }, { "code": null, "e": 3103, "s": 3044, "text": "Following is the basic syntax for StudentController class." }, { "code": null, "e": 3216, "s": 3103, "text": "namespace AppBundle\\Controller; \nuse Symfony\\Component\\HttpFoundation\\Response; \nclass StudentController { \n} \n" }, { "code": null, "e": 3333, "s": 3216, "text": "Now, you have created a StudentController. In the next chapter, we will discuss more about the Controller in detail." }, { "code": null, "e": 3469, "s": 3333, "text": "Once the Controller has been created, we need to route for a specific page. Routing maps request URI to a specific controller's method." }, { "code": null, "e": 3512, "s": 3469, "text": "Following is the basic syntax for routing." }, { "code": null, "e": 3894, "s": 3512, "text": "namespace AppBundle\\Controller; \nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Route; \nuse Symfony\\Component\\HttpFoundation\\Response; \nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller; \n\nclass StudentController { \n /** \n * @Route(\"/student/home\") \n */ \n public function homeAction() { \n return new Response('Student details application!'); \n } \n}" }, { "code": null, "e": 3994, "s": 3894, "text": "In the above syntax, @Route(“/student/home”) is the route. It defines the URL pattern for the page." }, { "code": null, "e": 4088, "s": 3994, "text": "homeAction() is the action method, where you can build the page and return a Response object." }, { "code": null, "e": 4241, "s": 4088, "text": "We will cover routing in detail in the upcoming chapter. Now, request the url “http://localhost:8000/student/home” and it produces the following result." }, { "code": null, "e": 4248, "s": 4241, "text": " Print" }, { "code": null, "e": 4259, "s": 4248, "text": " Add Notes" } ]
How to use CardMedia Component in ReactJS? - GeeksforGeeks
05 Mar, 2021 The CardMedia Component allows users to use the media for that particular card like attaching photos, videos, etc. Material UI for React has this component available for us, and it is very easy to integrate. We can use the CardMedia 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: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import CardMedia from "@material-ui/core/CardMedia";import Typography from "@material-ui/core/Typography";import CardContent from "@material-ui/core/CardContent";import Card from "@material-ui/core/Card";import CardActionArea from "@material-ui/core/CardActionArea";import Button from "@material-ui/core/Button";import CardActions from "@material-ui/core/CardActions"; export default function App() { return ( <div stlye={{}}> <h4>How to use CardMedia Component in ReactJS?</h4> <Card style={{ width: 400 }}> <CardActionArea> <CardMedia alt="GeeksforGeeks" component="img" title="GeeksforGeeks" height="150" image="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> GeeksforGeeks </Typography> <Typography variant="body2" color="textSecondary" component="p"> Best Computer Science Portal #Best #CS #ComputerScience #website </Typography> </CardContent> </CardActionArea> <CardActions> <Button size="small" color="primary"> Comment </Button> <Button size="small" color="primary"> Share </Button> </CardActions> </Card> </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/cards/#media Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? ReactJS useNavigate() Hook React-Router Hooks Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 24826, "s": 24798, "text": "\n05 Mar, 2021" }, { "code": null, "e": 25110, "s": 24826, "text": "The CardMedia Component allows users to use the media for that particular card like attaching photos, videos, etc. Material UI for React has this component available for us, and it is very easy to integrate. We can use the CardMedia component in ReactJS using the following approach." }, { "code": null, "e": 25160, "s": 25110, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25224, "s": 25160, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 25256, "s": 25224, "text": "npx create-react-app foldername" }, { "code": null, "e": 25356, "s": 25256, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 25370, "s": 25356, "text": "cd foldername" }, { "code": null, "e": 25479, "s": 25370, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 25509, "s": 25479, "text": "npm install @material-ui/core" }, { "code": null, "e": 25561, "s": 25509, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25579, "s": 25561, "text": "Project Structure" }, { "code": null, "e": 25709, "s": 25579, "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": 25716, "s": 25709, "text": "App.js" }, { "code": "import React from \"react\";import CardMedia from \"@material-ui/core/CardMedia\";import Typography from \"@material-ui/core/Typography\";import CardContent from \"@material-ui/core/CardContent\";import Card from \"@material-ui/core/Card\";import CardActionArea from \"@material-ui/core/CardActionArea\";import Button from \"@material-ui/core/Button\";import CardActions from \"@material-ui/core/CardActions\"; export default function App() { return ( <div stlye={{}}> <h4>How to use CardMedia Component in ReactJS?</h4> <Card style={{ width: 400 }}> <CardActionArea> <CardMedia alt=\"GeeksforGeeks\" component=\"img\" title=\"GeeksforGeeks\" height=\"150\" image=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" /> <CardContent> <Typography gutterBottom variant=\"h5\" component=\"h2\"> GeeksforGeeks </Typography> <Typography variant=\"body2\" color=\"textSecondary\" component=\"p\"> Best Computer Science Portal #Best #CS #ComputerScience #website </Typography> </CardContent> </CardActionArea> <CardActions> <Button size=\"small\" color=\"primary\"> Comment </Button> <Button size=\"small\" color=\"primary\"> Share </Button> </CardActions> </Card> </div> );}", "e": 27194, "s": 25716, "text": null }, { "code": null, "e": 27307, "s": 27194, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 27317, "s": 27307, "text": "npm start" }, { "code": null, "e": 27416, "s": 27317, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27475, "s": 27416, "text": "Reference: https://material-ui.com/components/cards/#media" }, { "code": null, "e": 27487, "s": 27475, "text": "Material-UI" }, { "code": null, "e": 27503, "s": 27487, "text": "React-Questions" }, { "code": null, "e": 27511, "s": 27503, "text": "ReactJS" }, { "code": null, "e": 27528, "s": 27511, "text": "Web Technologies" }, { "code": null, "e": 27626, "s": 27528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27668, "s": 27626, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27703, "s": 27668, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27761, "s": 27703, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27788, "s": 27761, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 27807, "s": 27788, "text": "React-Router Hooks" }, { "code": null, "e": 27849, "s": 27807, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27882, "s": 27849, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27932, "s": 27882, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27994, "s": 27932, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Converting Roman Numerals to Decimal lying between 1 to 3999
04 Jul, 2022 Given a Roman numeral, the task is to find its corresponding decimal value. Example : Input: IX Output: 9 IX is a Roman symbol which represents 9 Input: XL Output: 40 XL is a Roman symbol which represents 40 Input: MCMIV Output: 1904 M is a thousand, CM is nine hundred and IV is four Roman numerals are based on the following symbols. SYMBOL VALUE I 1 IV 4 V 5 IX 9 X 10 XL 40 L 50 XC 90 C 100 CD 400 D 500 CM 900 M 1000 Approach: A number in Roman Numerals is a string of these symbols written in descending order(e.g. M’s first, followed by D’s, etc.). However, in a few specific cases, to avoid four characters being repeated in succession(such as IIII or XXXX), subtractive notation is often used as follows: I placed before V or X indicates one less, so four is IV (one less than 5) and 9 is IX (one less than 10). X placed before L or C indicates ten less, so forty is XL (10 less than 50) and 90 is XC (ten less than a hundred). C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand). Algorithm to convert Roman Numerals to Integer Number: Split the Roman Numeral string into Roman Symbols (character).Convert each symbol of Roman Numerals into the value it represents.Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total. Split the Roman Numeral string into Roman Symbols (character). Convert each symbol of Roman Numerals into the value it represents. Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total. If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total. If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total. else subtract this value by adding the value of next symbol to the running total. Following is the implementation of the above algorithm: C++ C Java Python C# PHP Javascript // Program to convert Roman// Numerals to Numbers#include <bits/stdc++.h>using namespace std; // This function returns value// of a Roman symbolint value(char r){ if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1;} // Returns decimal value of// roman numaralint romanToDecimal(string& str){ // Initialize result int res = 0; // Traverse given input for (int i = 0; i < str.length(); i++) { // Getting value of symbol s[i] int s1 = value(str[i]); if (i + 1 < str.length()) { // Getting value of symbol s[i+1] int s2 = value(str[i + 1]); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equal to // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res;} // Driver Codeint main(){ // Considering inputs given are valid string str = "MCMIV"; cout << "Integer form of Roman Numeral is " << romanToDecimal(str) << endl; return 0;} // Program to convert Roman// Numerals to Numbers#include <stdio.h>#include <string.h> // This function returns value// of a Roman symbolint value(char r){ if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1;} // Returns decimal value of// roman numaralint romanToDecimal(char str[]){ // Initialize result int res = 0; // Traverse given input for (int i = 0; i < strlen(str); i++) { // Getting value of symbol s[i] int s1 = value(str[i]); if (i + 1 < strlen(str)) { // Getting value of symbol s[i+1] int s2 = value(str[i + 1]); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equal to // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res;} // Driver Codeint main(){ // Considering inputs given are valid char str[10] = "MCMIV"; printf("Integer form of Roman Numeral is %d",romanToDecimal(str)); return 0;} // Program to convert Roman// Numerals to Numbersimport java.util.*; public class RomanToNumber { // This function returns // value of a Roman symbol int value(char r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given roman numeral int romanToDecimal(String str) { // Initialize result int res = 0; for (int i = 0; i < str.length(); i++) { // Getting value of symbol s[i] int s1 = value(str.charAt(i)); // Getting value of symbol s[i+1] if (i + 1 < str.length()) { int s2 = value(str.charAt(i + 1)); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res; } // Driver Code public static void main(String args[]) { RomanToNumber ob = new RomanToNumber(); // Considering inputs given are valid String str = "MCMIV"; System.out.println("Integer form of Roman Numeral" + " is " + ob.romanToDecimal(str)); }} # Python program to convert Roman Numerals# to Numbers # This function returns value of each Roman symbol def value(r): if (r == 'I'): return 1 if (r == 'V'): return 5 if (r == 'X'): return 10 if (r == 'L'): return 50 if (r == 'C'): return 100 if (r == 'D'): return 500 if (r == 'M'): return 1000 return -1 def romanToDecimal(str): res = 0 i = 0 while (i < len(str)): # Getting value of symbol s[i] s1 = value(str[i]) if (i + 1 < len(str)): # Getting value of symbol s[i + 1] s2 = value(str[i + 1]) # Comparing both values if (s1 >= s2): # Value of current symbol is greater # or equal to the next symbol res = res + s1 i = i + 1 else: # Value of current symbol is greater # or equal to the next symbol res = res + s2 - s1 i = i + 2 else: res = res + s1 i = i + 1 return res # Driver codeprint("Integer form of Roman Numeral is"),print(romanToDecimal("MCMIV")) // C# Program to convert Roman// Numerals to Numbersusing System; class GFG { // This function returns value // of a Roman symbol public virtual int value(char r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given roman numeral public virtual int romanToDecimal(string str) { // Initialize result int res = 0; for (int i = 0; i < str.Length; i++) { // Getting value of symbol s[i] int s1 = value(str[i]); // Getting value of symbol s[i+1] if (i + 1 < str.Length) { int s2 = value(str[i + 1]); // Comparing both values if (s1 >= s2) { // Value of current symbol is greater // or equalto the next symbol res = res + s1; } else { res = res + s2 - s1; i++; // Value of current symbol is // less than the next symbol } } else { res = res + s1; i++; } } return res; } // Driver Code public static void Main(string[] args) { GFG ob = new GFG(); // Considering inputs given are valid string str = "MCMIV"; Console.WriteLine("Integer form of Roman Numeral" + " is " + ob.romanToDecimal(str)); }} // This code is contributed by Shrikant13 <?php// Program to convert Roman// Numerals to Numbers // This function returns// value of a Roman symbolfunction value($r){ if ($r == 'I') return 1; if ($r == 'V') return 5; if ($r == 'X') return 10; if ($r == 'L') return 50; if ($r == 'C') return 100; if ($r == 'D') return 500; if ($r == 'M') return 1000; return -1;} // Returns decimal value// of roman numeralfunction romanToDecimal(&$str){ // Initialize result $res = 0; // Traverse given input for ($i = 0; $i < strlen($str); $i++) { // Getting value of // symbol s[i] $s1 = value($str[$i]); if ($i+1 < strlen($str)) { // Getting value of // symbol s[i+1] $s2 = value($str[$i + 1]); // Comparing both values if ($s1 >= $s2) { // Value of current symbol // is greater or equal to // the next symbol $res = $res + $s1; } else { $res = $res + $s2 - $s1; $i++; // Value of current symbol is // less than the next symbol } } else { $res = $res + $s1; $i++; } } return $res;} // Driver Code // Considering inputs// given are valid$str ="MCMIV";echo "Integer form of Roman Numeral is ", romanToDecimal($str), "\n"; // This code is contributed by ajit?> <script>// Program to convert Roman// Numerals to Numberspublic // This function returns // value of a Roman symbol function value(r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given roman numeral function romanToDecimal( str) { // Initialize result var res = 0; for (i = 0; i < str.length; i++) { // Getting value of symbol s[i] var s1 = value(str.charAt(i)); // Getting value of symbol s[i+1] if (i + 1 < str.length) { var s2 = value(str.charAt(i + 1)); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res; } // Driver Code // Considering inputs given are valid var str = "MCMIV"; document.write("Integer form of Roman Numeral" + " is " + romanToDecimal(str)); // This code is contributed by umadevi9616</script> Integer form of Roman Numeral is 1904 Complexity Analysis: Time Complexity: O(n), where n is the length of the string. Only one traversal of the string is required. Space Complexity: O(1). As no extra space is required. Another solution – C++ Java Python3 C# Javascript // Program to convert Roman// Numerals to Numbers#include <bits/stdc++.h>using namespace std; // This function returns value// of a Roman symbolint romanToDecimal(string& str){ map<char, int> m; m.insert({ 'I', 1 }); m.insert({ 'V', 5 }); m.insert({ 'X', 10 }); m.insert({ 'L', 50 }); m.insert({ 'C', 100 }); m.insert({ 'D', 500 }); m.insert({ 'M', 1000 }); int sum = 0; for (int i = 0; i < str.length(); i++) { /*If present value is less than next value, subtract present from next value and add the resultant to the sum variable.*/ if (m[str[i]] < m[str[i + 1]]) { sum+=m[str[i+1]]-m[str[i]]; i++; continue; } sum += m[str[i]]; } return sum;} // Driver Codeint main(){ // Considering inputs given are valid string str = "MCMIV"; cout << "Integer form of Roman Numeral is " << romanToDecimal(str) << endl; return 0;} // Program to convert Roman// Numerals to Numbersimport java.util.Map;import java.util.HashMap; class GFG{ private static final Map<Character, Integer> roman = new HashMap<Character, Integer>(){{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000);}}; // This function returns value// of a Roman symbolprivate static int romanToInt(String s){ int sum = 0; int n = s.length(); for(int i = 0; i < n; i++) { // If present value is less than next value, // subtract present from next value and add the // resultant to the sum variable. if (i != n - 1 && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) { sum += roman.get(s.charAt(i + 1)) - roman.get(s.charAt(i)); i++; } else { sum += roman.get(s.charAt(i)); } } return sum;} // Driver Codepublic static void main(String[] args){ // Considering inputs given are valid String input = "MCMIV"; System.out.print("Integer form of Roman Numeral is " + romanToInt(input));}} // This code is contributed by rahuldevgarg # Program to convert Roman# Numerals to Numbersroman = {}roman['I'] = 1roman['V'] = 5roman['X'] = 10roman['L'] = 50roman['C'] = 100roman['D'] = 500roman['M'] = 1000 # This function returns value# of a Roman symboldef romanToInt(s): sum = 0 n = len(s) i = 0 while i < n : # If present value is less than next value, # subtract present from next value and add the # resultant to the sum variable. # print(roman[s[i]],roman[s[i+1]]) if (i != n - 1 and roman[s[i]] < roman[s[i + 1]]): sum += roman[s[i + 1]] - roman[s[i]] i += 2 continue else: sum += roman[s[i]] i += 1 return sum # Driver Code # Considering inputs given are validinput = "MCMIV" print(f"Integer form of Roman Numeral is {romanToInt(input)}") # This code is contributed by shinjanpatra // Program to convert Roman// Numerals to Numbersusing System;using System.Collections.Generic; public class GFG { static Dictionary<char, int> roman = new Dictionary<char, int>(); // This function returns value // of a Roman symbol public static int romanToInt(String s) { int sum = 0; int n = s.Length; for (int i = 0; i < n; i++) { // If present value is less than next value, // subtract present from next value and add the // resultant to the sum variable. if (i != n - 1 && roman[s[i]] < roman[s[i + 1]]) { sum += roman[s[i + 1]] - roman[s[i]]; i++; } else { sum += roman[s[i]]; } } return sum; } // Driver Code public static void Main(String[] args) { roman['I'] = 1; roman['V'] =5; roman['X'] =10; roman['L'] =50; roman['C'] =100; roman['D'] =500; roman['M'] =1000; // Considering inputs given are valid String input = "MCMIV"; Console.Write("int form of Roman Numeral is " + romanToInt(input)); }} // This code is contributed by Rajput-Ji <script>// Program to convert Roman// Numerals to Numbers var roman = new Map() ; roman.set('I', 1); roman.set('V', 5); roman.set('X', 10); roman.set('L', 50); roman.set('C', 100); roman.set('D', 500); roman.set('M', 1000); // This function returns value // of a Roman symbol function romanToInt( s) { var sum = 0; var n = s.length; for (i = 0; i < n; i++) { // If present value is less than next value, // subtract present from next value and add the // resultant to the sum variable. if (i != n - 1 && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) { sum += roman.get(s.charAt(i + 1)) - roman.get(s.charAt(i)); i++; } else { sum += roman.get(s.charAt(i)); } } return sum; } // Driver Code // Considering inputs given are valid var input = "MCMIV"; document.write("Integer form of Roman Numeral is " + romanToInt(input)); // This code is contributed by Rajput-Ji</script> Integer form of Roman Numeral is 1904 Time complexity – O(N)Auxiliary Space – O(1) Another Solution: Shorter code using python Java C# Python3 Javascript // Java Program to convert Roman// Numerals to Numbersimport java.io.*;import java.util.*; class GFG{ public static void romanToInt(String s) { Map<Character,Integer> translations=new HashMap<Character,Integer>(); //Adding elements to map translations.put('I',1); translations.put('V',5); translations.put('X',10); translations.put('L',50); translations.put('C',100); translations.put('D',500); translations.put('M',1000); s = s.replace("IV","IIII"); s = s.replace("IX","VIIII"); s = s.replace("XL","XXXX"); s = s.replace("XC","LXXXX"); s = s.replace("CD","CCCC"); s = s.replace("CM","DCCCC"); int number = 0; for (int i = 0; i < s.length(); i++) { number = number + (translations.get(s.charAt(i))); } System.out.println(number); } public static void main (String[] args) { romanToInt("MCMIV"); }} // This code is contributed by kothavvsaakash // C# Program to convert Roman// Numerals to Numbersusing System;using System.Collections.Generic; using System.Collections; public class GFG { public static void romanToInt(String s) { var translations = new Dictionary<char, int>(); // Adding elements to map translations['I'] = 1; translations['V'] = 5; translations['X'] = 10; translations['L'] = 50; translations['C'] = 100; translations['D'] = 500; translations['M'] = 1000; s = s.Replace("IV", "IIII"); s = s.Replace("IX", "VIIII"); s = s.Replace("XL", "XXXX"); s = s.Replace("XC", "LXXXX"); s = s.Replace("CD", "CCCC"); s = s.Replace("CM", "DCCCC"); var number = 0; for (int i = 0; i < s.Length; i++) { number = number + (translations[s[i]]); } Console.WriteLine(number); } public static void Main(String[] args) { romanToInt("MCMIV"); }} // This code is contributed by Aarti_Rathi def romanToInt(s): translations = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } number = 0 s = s.replace("IV", "IIII").replace("IX", "VIIII") s = s.replace("XL", "XXXX").replace("XC", "LXXXX") s = s.replace("CD", "CCCC").replace("CM", "DCCCC") for char in s: number += translations[char] print(number) romanToInt('MCMIV') <script> function romanToInt(s){ let translations = new Map() translations.set("I",1) translations.set("V",5) translations.set("X",10) translations.set("L",50) translations.set("C",100) translations.set("D",500) translations.set("M",1000) let number = 0 s = s.replace("IV", "IIII").replace("IX", "VIIII") s = s.replace("XL", "XXXX").replace("XC", "LXXXX") s = s.replace("CD", "CCCC").replace("CM", "DCCCC") for(let char of s) number += translations.get(char) document.write(number)} romanToInt('MCMIV') // code is contributed by shinjanpatra </script> 1904 Time complexity – O(N)Auxiliary Space – O(1) This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. jit_t shrikanth13 yashjaiswal10 RajaKumar17 andrew1234 cyrus18 rachitsharma19962000 rahuldevgarg umadevi9616 shradhaagarwal kumarabhinav3125 Rajput-Ji surinderdawra388 shinjanpatra pariveshsrivastava1093 kothavvsaakash codewithshinchan hardikkoriintern Amazon base-conversion Facebook Microsoft Twitter Zoho Algorithms Strings Zoho Amazon Microsoft Facebook Twitter Strings Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews What is Hashing | A Complete Tutorial Difference between BFS and DFS Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 130, "s": 54, "text": "Given a Roman numeral, the task is to find its corresponding decimal value." }, { "code": null, "e": 141, "s": 130, "text": "Example : " }, { "code": null, "e": 345, "s": 141, "text": "Input: IX\nOutput: 9\nIX is a Roman symbol which represents 9 \n\nInput: XL\nOutput: 40\nXL is a Roman symbol which represents 40\n\nInput: MCMIV\nOutput: 1904\nM is a thousand, \nCM is nine hundred and \nIV is four" }, { "code": null, "e": 398, "s": 345, "text": "Roman numerals are based on the following symbols. " }, { "code": null, "e": 654, "s": 398, "text": "SYMBOL VALUE\n I 1\n IV 4\n V 5\n IX 9\n X 10\n XL 40\n L 50\n XC 90\n C 100\n CD 400\n D 500\n CM 900 \n M 1000" }, { "code": null, "e": 947, "s": 654, "text": "Approach: A number in Roman Numerals is a string of these symbols written in descending order(e.g. M’s first, followed by D’s, etc.). However, in a few specific cases, to avoid four characters being repeated in succession(such as IIII or XXXX), subtractive notation is often used as follows: " }, { "code": null, "e": 1054, "s": 947, "text": "I placed before V or X indicates one less, so four is IV (one less than 5) and 9 is IX (one less than 10)." }, { "code": null, "e": 1170, "s": 1054, "text": "X placed before L or C indicates ten less, so forty is XL (10 less than 50) and 90 is XC (ten less than a hundred)." }, { "code": null, "e": 1333, "s": 1170, "text": "C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)." }, { "code": null, "e": 1390, "s": 1333, "text": "Algorithm to convert Roman Numerals to Integer Number: " }, { "code": null, "e": 1774, "s": 1390, "text": "Split the Roman Numeral string into Roman Symbols (character).Convert each symbol of Roman Numerals into the value it represents.Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total." }, { "code": null, "e": 1837, "s": 1774, "text": "Split the Roman Numeral string into Roman Symbols (character)." }, { "code": null, "e": 1905, "s": 1837, "text": "Convert each symbol of Roman Numerals into the value it represents." }, { "code": null, "e": 2160, "s": 1905, "text": "Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total." }, { "code": null, "e": 2364, "s": 2160, "text": "If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total." }, { "code": null, "e": 2487, "s": 2364, "text": "If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total." }, { "code": null, "e": 2569, "s": 2487, "text": "else subtract this value by adding the value of next symbol to the running total." }, { "code": null, "e": 2626, "s": 2569, "text": "Following is the implementation of the above algorithm: " }, { "code": null, "e": 2630, "s": 2626, "text": "C++" }, { "code": null, "e": 2632, "s": 2630, "text": "C" }, { "code": null, "e": 2637, "s": 2632, "text": "Java" }, { "code": null, "e": 2644, "s": 2637, "text": "Python" }, { "code": null, "e": 2647, "s": 2644, "text": "C#" }, { "code": null, "e": 2651, "s": 2647, "text": "PHP" }, { "code": null, "e": 2662, "s": 2651, "text": "Javascript" }, { "code": "// Program to convert Roman// Numerals to Numbers#include <bits/stdc++.h>using namespace std; // This function returns value// of a Roman symbolint value(char r){ if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1;} // Returns decimal value of// roman numaralint romanToDecimal(string& str){ // Initialize result int res = 0; // Traverse given input for (int i = 0; i < str.length(); i++) { // Getting value of symbol s[i] int s1 = value(str[i]); if (i + 1 < str.length()) { // Getting value of symbol s[i+1] int s2 = value(str[i + 1]); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equal to // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res;} // Driver Codeint main(){ // Considering inputs given are valid string str = \"MCMIV\"; cout << \"Integer form of Roman Numeral is \" << romanToDecimal(str) << endl; return 0;}", "e": 4141, "s": 2662, "text": null }, { "code": "// Program to convert Roman// Numerals to Numbers#include <stdio.h>#include <string.h> // This function returns value// of a Roman symbolint value(char r){ if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1;} // Returns decimal value of// roman numaralint romanToDecimal(char str[]){ // Initialize result int res = 0; // Traverse given input for (int i = 0; i < strlen(str); i++) { // Getting value of symbol s[i] int s1 = value(str[i]); if (i + 1 < strlen(str)) { // Getting value of symbol s[i+1] int s2 = value(str[i + 1]); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equal to // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res;} // Driver Codeint main(){ // Considering inputs given are valid char str[10] = \"MCMIV\"; printf(\"Integer form of Roman Numeral is %d\",romanToDecimal(str)); return 0;}", "e": 5628, "s": 4141, "text": null }, { "code": "// Program to convert Roman// Numerals to Numbersimport java.util.*; public class RomanToNumber { // This function returns // value of a Roman symbol int value(char r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given roman numeral int romanToDecimal(String str) { // Initialize result int res = 0; for (int i = 0; i < str.length(); i++) { // Getting value of symbol s[i] int s1 = value(str.charAt(i)); // Getting value of symbol s[i+1] if (i + 1 < str.length()) { int s2 = value(str.charAt(i + 1)); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res; } // Driver Code public static void main(String args[]) { RomanToNumber ob = new RomanToNumber(); // Considering inputs given are valid String str = \"MCMIV\"; System.out.println(\"Integer form of Roman Numeral\" + \" is \" + ob.romanToDecimal(str)); }}", "e": 7451, "s": 5628, "text": null }, { "code": "# Python program to convert Roman Numerals# to Numbers # This function returns value of each Roman symbol def value(r): if (r == 'I'): return 1 if (r == 'V'): return 5 if (r == 'X'): return 10 if (r == 'L'): return 50 if (r == 'C'): return 100 if (r == 'D'): return 500 if (r == 'M'): return 1000 return -1 def romanToDecimal(str): res = 0 i = 0 while (i < len(str)): # Getting value of symbol s[i] s1 = value(str[i]) if (i + 1 < len(str)): # Getting value of symbol s[i + 1] s2 = value(str[i + 1]) # Comparing both values if (s1 >= s2): # Value of current symbol is greater # or equal to the next symbol res = res + s1 i = i + 1 else: # Value of current symbol is greater # or equal to the next symbol res = res + s2 - s1 i = i + 2 else: res = res + s1 i = i + 1 return res # Driver codeprint(\"Integer form of Roman Numeral is\"),print(romanToDecimal(\"MCMIV\"))", "e": 8633, "s": 7451, "text": null }, { "code": "// C# Program to convert Roman// Numerals to Numbersusing System; class GFG { // This function returns value // of a Roman symbol public virtual int value(char r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given roman numeral public virtual int romanToDecimal(string str) { // Initialize result int res = 0; for (int i = 0; i < str.Length; i++) { // Getting value of symbol s[i] int s1 = value(str[i]); // Getting value of symbol s[i+1] if (i + 1 < str.Length) { int s2 = value(str[i + 1]); // Comparing both values if (s1 >= s2) { // Value of current symbol is greater // or equalto the next symbol res = res + s1; } else { res = res + s2 - s1; i++; // Value of current symbol is // less than the next symbol } } else { res = res + s1; i++; } } return res; } // Driver Code public static void Main(string[] args) { GFG ob = new GFG(); // Considering inputs given are valid string str = \"MCMIV\"; Console.WriteLine(\"Integer form of Roman Numeral\" + \" is \" + ob.romanToDecimal(str)); }} // This code is contributed by Shrikant13", "e": 10446, "s": 8633, "text": null }, { "code": "<?php// Program to convert Roman// Numerals to Numbers // This function returns// value of a Roman symbolfunction value($r){ if ($r == 'I') return 1; if ($r == 'V') return 5; if ($r == 'X') return 10; if ($r == 'L') return 50; if ($r == 'C') return 100; if ($r == 'D') return 500; if ($r == 'M') return 1000; return -1;} // Returns decimal value// of roman numeralfunction romanToDecimal(&$str){ // Initialize result $res = 0; // Traverse given input for ($i = 0; $i < strlen($str); $i++) { // Getting value of // symbol s[i] $s1 = value($str[$i]); if ($i+1 < strlen($str)) { // Getting value of // symbol s[i+1] $s2 = value($str[$i + 1]); // Comparing both values if ($s1 >= $s2) { // Value of current symbol // is greater or equal to // the next symbol $res = $res + $s1; } else { $res = $res + $s2 - $s1; $i++; // Value of current symbol is // less than the next symbol } } else { $res = $res + $s1; $i++; } } return $res;} // Driver Code // Considering inputs// given are valid$str =\"MCMIV\";echo \"Integer form of Roman Numeral is \", romanToDecimal($str), \"\\n\"; // This code is contributed by ajit?>", "e": 11966, "s": 10446, "text": null }, { "code": "<script>// Program to convert Roman// Numerals to Numberspublic // This function returns // value of a Roman symbol function value(r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given roman numeral function romanToDecimal( str) { // Initialize result var res = 0; for (i = 0; i < str.length; i++) { // Getting value of symbol s[i] var s1 = value(str.charAt(i)); // Getting value of symbol s[i+1] if (i + 1 < str.length) { var s2 = value(str.charAt(i + 1)); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res; } // Driver Code // Considering inputs given are valid var str = \"MCMIV\"; document.write(\"Integer form of Roman Numeral\" + \" is \" + romanToDecimal(str)); // This code is contributed by umadevi9616</script>", "e": 13686, "s": 11966, "text": null }, { "code": null, "e": 13724, "s": 13686, "text": "Integer form of Roman Numeral is 1904" }, { "code": null, "e": 13746, "s": 13724, "text": "Complexity Analysis: " }, { "code": null, "e": 13852, "s": 13746, "text": "Time Complexity: O(n), where n is the length of the string. Only one traversal of the string is required." }, { "code": null, "e": 13907, "s": 13852, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 13926, "s": 13907, "text": "Another solution –" }, { "code": null, "e": 13930, "s": 13926, "text": "C++" }, { "code": null, "e": 13935, "s": 13930, "text": "Java" }, { "code": null, "e": 13943, "s": 13935, "text": "Python3" }, { "code": null, "e": 13946, "s": 13943, "text": "C#" }, { "code": null, "e": 13957, "s": 13946, "text": "Javascript" }, { "code": "// Program to convert Roman// Numerals to Numbers#include <bits/stdc++.h>using namespace std; // This function returns value// of a Roman symbolint romanToDecimal(string& str){ map<char, int> m; m.insert({ 'I', 1 }); m.insert({ 'V', 5 }); m.insert({ 'X', 10 }); m.insert({ 'L', 50 }); m.insert({ 'C', 100 }); m.insert({ 'D', 500 }); m.insert({ 'M', 1000 }); int sum = 0; for (int i = 0; i < str.length(); i++) { /*If present value is less than next value, subtract present from next value and add the resultant to the sum variable.*/ if (m[str[i]] < m[str[i + 1]]) { sum+=m[str[i+1]]-m[str[i]]; i++; continue; } sum += m[str[i]]; } return sum;} // Driver Codeint main(){ // Considering inputs given are valid string str = \"MCMIV\"; cout << \"Integer form of Roman Numeral is \" << romanToDecimal(str) << endl; return 0;}", "e": 14921, "s": 13957, "text": null }, { "code": "// Program to convert Roman// Numerals to Numbersimport java.util.Map;import java.util.HashMap; class GFG{ private static final Map<Character, Integer> roman = new HashMap<Character, Integer>(){{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000);}}; // This function returns value// of a Roman symbolprivate static int romanToInt(String s){ int sum = 0; int n = s.length(); for(int i = 0; i < n; i++) { // If present value is less than next value, // subtract present from next value and add the // resultant to the sum variable. if (i != n - 1 && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) { sum += roman.get(s.charAt(i + 1)) - roman.get(s.charAt(i)); i++; } else { sum += roman.get(s.charAt(i)); } } return sum;} // Driver Codepublic static void main(String[] args){ // Considering inputs given are valid String input = \"MCMIV\"; System.out.print(\"Integer form of Roman Numeral is \" + romanToInt(input));}} // This code is contributed by rahuldevgarg", "e": 16246, "s": 14921, "text": null }, { "code": "# Program to convert Roman# Numerals to Numbersroman = {}roman['I'] = 1roman['V'] = 5roman['X'] = 10roman['L'] = 50roman['C'] = 100roman['D'] = 500roman['M'] = 1000 # This function returns value# of a Roman symboldef romanToInt(s): sum = 0 n = len(s) i = 0 while i < n : # If present value is less than next value, # subtract present from next value and add the # resultant to the sum variable. # print(roman[s[i]],roman[s[i+1]]) if (i != n - 1 and roman[s[i]] < roman[s[i + 1]]): sum += roman[s[i + 1]] - roman[s[i]] i += 2 continue else: sum += roman[s[i]] i += 1 return sum # Driver Code # Considering inputs given are validinput = \"MCMIV\" print(f\"Integer form of Roman Numeral is {romanToInt(input)}\") # This code is contributed by shinjanpatra", "e": 17082, "s": 16246, "text": null }, { "code": "// Program to convert Roman// Numerals to Numbersusing System;using System.Collections.Generic; public class GFG { static Dictionary<char, int> roman = new Dictionary<char, int>(); // This function returns value // of a Roman symbol public static int romanToInt(String s) { int sum = 0; int n = s.Length; for (int i = 0; i < n; i++) { // If present value is less than next value, // subtract present from next value and add the // resultant to the sum variable. if (i != n - 1 && roman[s[i]] < roman[s[i + 1]]) { sum += roman[s[i + 1]] - roman[s[i]]; i++; } else { sum += roman[s[i]]; } } return sum; } // Driver Code public static void Main(String[] args) { roman['I'] = 1; roman['V'] =5; roman['X'] =10; roman['L'] =50; roman['C'] =100; roman['D'] =500; roman['M'] =1000; // Considering inputs given are valid String input = \"MCMIV\"; Console.Write(\"int form of Roman Numeral is \" + romanToInt(input)); }} // This code is contributed by Rajput-Ji", "e": 18143, "s": 17082, "text": null }, { "code": "<script>// Program to convert Roman// Numerals to Numbers var roman = new Map() ; roman.set('I', 1); roman.set('V', 5); roman.set('X', 10); roman.set('L', 50); roman.set('C', 100); roman.set('D', 500); roman.set('M', 1000); // This function returns value // of a Roman symbol function romanToInt( s) { var sum = 0; var n = s.length; for (i = 0; i < n; i++) { // If present value is less than next value, // subtract present from next value and add the // resultant to the sum variable. if (i != n - 1 && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) { sum += roman.get(s.charAt(i + 1)) - roman.get(s.charAt(i)); i++; } else { sum += roman.get(s.charAt(i)); } } return sum; } // Driver Code // Considering inputs given are valid var input = \"MCMIV\"; document.write(\"Integer form of Roman Numeral is \" + romanToInt(input)); // This code is contributed by Rajput-Ji</script>", "e": 19300, "s": 18143, "text": null }, { "code": null, "e": 19338, "s": 19300, "text": "Integer form of Roman Numeral is 1904" }, { "code": null, "e": 19383, "s": 19338, "text": "Time complexity – O(N)Auxiliary Space – O(1)" }, { "code": null, "e": 19427, "s": 19383, "text": "Another Solution: Shorter code using python" }, { "code": null, "e": 19432, "s": 19427, "text": "Java" }, { "code": null, "e": 19435, "s": 19432, "text": "C#" }, { "code": null, "e": 19443, "s": 19435, "text": "Python3" }, { "code": null, "e": 19454, "s": 19443, "text": "Javascript" }, { "code": "// Java Program to convert Roman// Numerals to Numbersimport java.io.*;import java.util.*; class GFG{ public static void romanToInt(String s) { Map<Character,Integer> translations=new HashMap<Character,Integer>(); //Adding elements to map translations.put('I',1); translations.put('V',5); translations.put('X',10); translations.put('L',50); translations.put('C',100); translations.put('D',500); translations.put('M',1000); s = s.replace(\"IV\",\"IIII\"); s = s.replace(\"IX\",\"VIIII\"); s = s.replace(\"XL\",\"XXXX\"); s = s.replace(\"XC\",\"LXXXX\"); s = s.replace(\"CD\",\"CCCC\"); s = s.replace(\"CM\",\"DCCCC\"); int number = 0; for (int i = 0; i < s.length(); i++) { number = number + (translations.get(s.charAt(i))); } System.out.println(number); } public static void main (String[] args) { romanToInt(\"MCMIV\"); }} // This code is contributed by kothavvsaakash", "e": 20499, "s": 19454, "text": null }, { "code": "// C# Program to convert Roman// Numerals to Numbersusing System;using System.Collections.Generic; using System.Collections; public class GFG { public static void romanToInt(String s) { var translations = new Dictionary<char, int>(); // Adding elements to map translations['I'] = 1; translations['V'] = 5; translations['X'] = 10; translations['L'] = 50; translations['C'] = 100; translations['D'] = 500; translations['M'] = 1000; s = s.Replace(\"IV\", \"IIII\"); s = s.Replace(\"IX\", \"VIIII\"); s = s.Replace(\"XL\", \"XXXX\"); s = s.Replace(\"XC\", \"LXXXX\"); s = s.Replace(\"CD\", \"CCCC\"); s = s.Replace(\"CM\", \"DCCCC\"); var number = 0; for (int i = 0; i < s.Length; i++) { number = number + (translations[s[i]]); } Console.WriteLine(number); } public static void Main(String[] args) { romanToInt(\"MCMIV\"); }} // This code is contributed by Aarti_Rathi", "e": 21507, "s": 20499, "text": null }, { "code": "def romanToInt(s): translations = { \"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000 } number = 0 s = s.replace(\"IV\", \"IIII\").replace(\"IX\", \"VIIII\") s = s.replace(\"XL\", \"XXXX\").replace(\"XC\", \"LXXXX\") s = s.replace(\"CD\", \"CCCC\").replace(\"CM\", \"DCCCC\") for char in s: number += translations[char] print(number) romanToInt('MCMIV')", "e": 22003, "s": 21507, "text": null }, { "code": "<script> function romanToInt(s){ let translations = new Map() translations.set(\"I\",1) translations.set(\"V\",5) translations.set(\"X\",10) translations.set(\"L\",50) translations.set(\"C\",100) translations.set(\"D\",500) translations.set(\"M\",1000) let number = 0 s = s.replace(\"IV\", \"IIII\").replace(\"IX\", \"VIIII\") s = s.replace(\"XL\", \"XXXX\").replace(\"XC\", \"LXXXX\") s = s.replace(\"CD\", \"CCCC\").replace(\"CM\", \"DCCCC\") for(let char of s) number += translations.get(char) document.write(number)} romanToInt('MCMIV') // code is contributed by shinjanpatra </script>", "e": 22624, "s": 22003, "text": null }, { "code": null, "e": 22629, "s": 22624, "text": "1904" }, { "code": null, "e": 22674, "s": 22629, "text": "Time complexity – O(N)Auxiliary Space – O(1)" }, { "code": null, "e": 22972, "s": 22674, "text": "This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 22978, "s": 22972, "text": "jit_t" }, { "code": null, "e": 22990, "s": 22978, "text": "shrikanth13" }, { "code": null, "e": 23004, "s": 22990, "text": "yashjaiswal10" }, { "code": null, "e": 23016, "s": 23004, "text": "RajaKumar17" }, { "code": null, "e": 23027, "s": 23016, "text": "andrew1234" }, { "code": null, "e": 23035, "s": 23027, "text": "cyrus18" }, { "code": null, "e": 23056, "s": 23035, "text": "rachitsharma19962000" }, { "code": null, "e": 23069, "s": 23056, "text": "rahuldevgarg" }, { "code": null, "e": 23081, "s": 23069, "text": "umadevi9616" }, { "code": null, "e": 23096, "s": 23081, "text": "shradhaagarwal" }, { "code": null, "e": 23113, "s": 23096, "text": "kumarabhinav3125" }, { "code": null, "e": 23123, "s": 23113, "text": "Rajput-Ji" }, { "code": null, "e": 23140, "s": 23123, "text": "surinderdawra388" }, { "code": null, "e": 23153, "s": 23140, "text": "shinjanpatra" }, { "code": null, "e": 23176, "s": 23153, "text": "pariveshsrivastava1093" }, { "code": null, "e": 23191, "s": 23176, "text": "kothavvsaakash" }, { "code": null, "e": 23208, "s": 23191, "text": "codewithshinchan" }, { "code": null, "e": 23225, "s": 23208, "text": "hardikkoriintern" }, { "code": null, "e": 23232, "s": 23225, "text": "Amazon" }, { "code": null, "e": 23248, "s": 23232, "text": "base-conversion" }, { "code": null, "e": 23257, "s": 23248, "text": "Facebook" }, { "code": null, "e": 23267, "s": 23257, "text": "Microsoft" }, { "code": null, "e": 23275, "s": 23267, "text": "Twitter" }, { "code": null, "e": 23280, "s": 23275, "text": "Zoho" }, { "code": null, "e": 23291, "s": 23280, "text": "Algorithms" }, { "code": null, "e": 23299, "s": 23291, "text": "Strings" }, { "code": null, "e": 23304, "s": 23299, "text": "Zoho" }, { "code": null, "e": 23311, "s": 23304, "text": "Amazon" }, { "code": null, "e": 23321, "s": 23311, "text": "Microsoft" }, { "code": null, "e": 23330, "s": 23321, "text": "Facebook" }, { "code": null, "e": 23338, "s": 23330, "text": "Twitter" }, { "code": null, "e": 23346, "s": 23338, "text": "Strings" }, { "code": null, "e": 23357, "s": 23346, "text": "Algorithms" }, { "code": null, "e": 23455, "s": 23357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23480, "s": 23455, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 23529, "s": 23480, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 23573, "s": 23529, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 23611, "s": 23573, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 23642, "s": 23611, "text": "Difference between BFS and DFS" }, { "code": null, "e": 23688, "s": 23642, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 23713, "s": 23688, "text": "Reverse a string in Java" }, { "code": null, "e": 23773, "s": 23713, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 23788, "s": 23773, "text": "C++ Data Types" } ]
Tutorial on Binary Tree - GeeksforGeeks
08 Apr, 2021 The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that is on the right is called “Right sub-tree”. Below are the various operations that can be performed on a Binary Tree: The idea is to first create the root node of the given tree, then recursively create the left and the right child for each parent node. Below is the program to illustrate the same: C++ // C++ program to illustrate how to// create a tree#include <iostream>using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the inorder// traversal of the given Treevoid inorder(struct treenode* root){ // If root is NULL if (root == NULL) return; // Recursively call for the left // and the right subtree inorder(root->left); cout << root->info << " "; inorder(root->right);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal inorder(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) In this traversal, the root is visited first followed by the left and the right subtree. Below is the program to illustrate the same: C++ // C++ program to demonstrate the// pre-order traversal#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the pre-order// traversal for the given treevoid preorder(struct treenode* root){ // If the root is NULL if (root == NULL) return; // Using tree-node type stack STL stack<treenode*> s; while ((root != NULL) || (!s.empty())) { if (root != NULL) { // Print the root cout << root->info << " "; // Push the node in the stack s.push(root); // Move to left subtree root = root->left; } else { // Remove the top of stack root = s.top(); s.pop(); root = root->right; } } cout << endl;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal preorder(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) In this traversal, the left subtree is visited first followed by the root and the right subtree. Below is the program to illustrate the same: C++ // C++ program to illustrate how to// create a tree#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the inorder// traversal of the given Treevoid inorder(struct treenode* root){ // If root is NULL if (root == NULL) return; // Recursively call for the left // and the right subtree inorder(root->left); cout << root->info << " "; inorder(root->right);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal inorder(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) In this traversal, the left subtree is visited first, followed by the right subtree and root node. Below is the program to illustrate the same: C++ // C++ program to implement the// post-order traversal#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the post-order// traversal of the given treevoid postorder(struct treenode* root){ // If the root is NULL return; stack<treenode*> s3; struct treenode* previous = NULL; do { // Iterate until root is present while (root != NULL) { s3.push(root); root = root->left; } while (root == NULL && (!s3.empty())) { root = s3.top(); // If the right subtree is NULL if (root->right == NULL || root->right == previous) { // Print the root information cout << root->info << " "; s3.pop(); // Update the previous previous = root; root = NULL; } // Otherwise else root = root->right; } } while (!s3.empty()); cout << endl;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal postorder(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) In this traversal, the given tree is traversal level-wise. Below is the program to illustrate the same: C++ // C++ program to illustrate the// level order traversal#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the level-order// traversalvoid levelorder(struct treenode* root){ // If the root is NULL if (root == NULL) return; // Use queue for traversal queue<treenode*> q; // Print the root's value and // push it into the queue cout << root->info << " "; q.push(root); // Iterate until queue is non-empty while (!q.empty()) { // Get the front node root = q.front(); q.pop(); // If the root has the left child if (root->left) { cout << root->left->info << " "; q.push(root->left); } // If the root has the right child if (root->right) { cout << root->right->info << " "; q.push(root->right); } } cout << endl;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal levelorder(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) The element which is largest among all the elements of the binary tree is called the maximum element. Below is the program to illustrate the same: C++ // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to find the maximum element// in the given Binary Treeint FindMax(struct treenode* root){ // If the tree is empty if (root == NULL) return 0; queue<treenode*> q; int max; struct treenode* temp; max = root->info; // Push the root in the queue q.push(root); // Iterate until queue is non-empty while (!q.empty()) { // Get the front node of // the tree root = q.front(); temp = root; q.pop(); // Update the maximum value // of the Tree if (max < temp->info) max = temp->info; if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } // Return the maximum value return max;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal FindMax(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) The approach to search for any particular element in the tree node is to perform any tree traversal on the given tree and check if there exists any node with the given searched value or not. If found to be true, then print “Element is Found”. Otherwise, print “Element Not Found”. Below is the program to illustrate the same: C++ // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to search an element in the// given Binary Treeint FindElement(struct treenode* root, int data){ // If the root is NULL if (root == NULL) return 0; queue<treenode*> q; struct treenode* temp; if (!root) return 0; else { // Push the root q.push(root); // Perform the level-order traversal while (!q.empty()) { // Get the root root = q.front(); temp = root; q.pop(); // If the node with value data // exists then return 1 if (data == temp->info) return 1; // Recursively push the left and // the right child of the node if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } // Otherwise, not found return 0; }} // Driver Codeint main(){ int data; // Root of the tree struct treenode* root = NULL; // Create the Tree root = create(); cout << "\nEnter element to searched : "; cin >> data; // Function Call if (FindElement(root, data) == 1) cout << "\nElement is found"; else cout << "Element is not found"; return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(log N)Auxiliary Space: O(N) Below is the program to illustrate the same: C++ // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to print the reverse level// order traversal of the given treevoid reversetree(struct treenode* root){ // If the root is NULL if (root == NULL) return; queue<treenode*> q; stack<int> s; struct treenode* temp; q.push(root); // Until queue is empty while (!q.empty()) { // Get the front node temp = q.front(); q.pop(); // Push every countered node // data into stack s.push(temp->info); // Check for the left subtree if (temp->left) q.push(temp->left); // Check for the right subtree if (temp->right) q.push(temp->right); } // While S is non-empty, print // all the nodes while (!s.empty()) { cout << s.top() << " "; s.pop(); }} // Driver Codeint main(){ // Create root node struct treenode* root = NULL; // Create a tree root = create(); cout << "\nReversed tree is : "; reversetree(root); return 0;}/* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9*/ Output: Time Complexity: O(N)Auxiliary Space: O(N) The height of the binary tree is the longest path from the root node to any leaf node in the tree. Below is the program to illustrate the same: C++ // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into // the tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to find the height of// the given Binary treeint height(struct treenode* root){ int x, y; // If root is NOT NULL if (root != NULL) { // x will contain the height // of left subtree x = height(root->left); // y will contain the height // of right subtree y = height(root->right); if (x > y) // Leaf node has one height // so x or y + 1 return x + 1; else return y + 1; } return 0;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nHeight of the tree is : " << height(root); return 0;}/* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) The node which is present at the maximum or the last level is called the deepest node. Below is the program to implement the above approach: C++ // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Function to find the deepest node// of the given Binary Treeint deepest(struct treenode* root){ // If the root is NULL if (root == NULL) return 0; queue<treenode*> q; q.push(root); // While queue is non-empty while (!q.empty()) { // Get the front node of queue root = q.front(); q.pop(); // Check for the left and // the right subtree if (root->left) q.push(root->left); if (root->right) q.push(root->right); } // Return the value for the // deepest node return (root->info);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nDeepest node of the tree is : " << deepest(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) Below is the program to implement the same: C++ // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Stores the maximum left sizeint maxlevelleft = 0; // Function to print the left view of// the treevoid leftview(struct treenode* root, int level){ if (root == NULL) return; // If current level is at least // the maximum left level if (level >= maxlevelleft) { // Print the data cout << root->info << " "; maxlevelleft++; } // Left and Right Subtree // recursive calls leftview(root->left, level + 1); leftview(root->right, level + 1);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nLeft view of the tree is : "; // Function Call leftview(root, 0); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) Below is the program to illustrate the same: C++ // C++ program to demonstrate the// above concepts#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Stores the maximum right levelint maxlevelright = 0; // Function to print the right view of// the given Binary treevoid rightview(struct treenode* root, int level){ // If the root is NULL if (root == NULL) return; // If the current level is greater // than the maximum right level if (level >= maxlevelright) { // Print the data cout << root->info << " "; maxlevelright++; } // Recursively call for the right // and the left subtree rightview(root->right, level + 1); rightview(root->left, level + 1);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << "\nRight view of the tree is : "; rightview(root, 0); return 0;}/* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9*/ Output: Time Complexity: O(N)Auxiliary Space: O(1) Below is the program to illustrate the same: C++ // C++ program to demonstrate the// above concepts#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Initialize an ordered mapmap<int, int> HashMap; // Iterator for the mapmap<int, int>::iterator it; // Function to print the top view// of the given Binary Treevoid topview(struct treenode* root, int level){ // If the root is NULL if (root == NULL) return; // Get the level int i = HashMap.count(level); // Update the root information if (i == 0) HashMap[level] = root->info; // Left and Right recursive calls topview(root->left, level - 1); topview(root->right, level + 1); // Update the current level // with the root's value HashMap[level] = root->info; return;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create a tree root = create(); topview(root, 0); cout << "\nTop view of the tree is : "; for (it = HashMap.begin(); it != HashMap.end(); it++) { cout << it->second << " "; } return 0;}/* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9*/ Output: Time Complexity: O(N)Auxiliary Space: O(N) Below is the program to illustrate the same: C++ // C++ program to demonstrate the// above concepts#include "bits/stdc++.h"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << "\nEnter data to be inserted " << "or type -1 for no insertion : "; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // Return the created Tree return tree;}; // Initialize an ordered Mapmap<int, pair<int, int> > HashMap; // Iterator for the mapmap<int, pair<int, int> >::iterator it; // Function to print the bottom view// of the given binary treevoid bottomview(struct treenode* root, int level, int height){ // If root is NULL if (root == NULL) return; // If the height of the level is // greater than the current // stored height of the level if (height >= HashMap[level].second) { HashMap[level] = { root->info, height }; } // Left and right recursive calls bottomview(root->left, level - 1, height + 1); bottomview(root->right, level + 1, height + 1); return;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); bottomview(root, 0, 0); cout << "\nBottom view of the tree is : "; for (it = HashMap.begin(); it != HashMap.end(); it++) { cout << it->second.first << " "; } return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) Below is the program to illustrate the same: C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // structure of the binary treestruct treenode { // data part int info; // left and right node struct treenode *left, *right;}; // create function for binary// tree creationstruct treenode* create(){ int data; // variable of the structure struct treenode* tree; // dynamically allocating // memory for tree-node tree = new treenode; cout << "\nEnter data to be inserted or type -1 for no insertion : "; // input from the user cin >> data; // condition for termination if (data == -1) return 0; // assigning value from user // into tree. tree->info = data; // recursively calling create function // for left and right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // returning the created tree return tree;}; /*With the simple logic of recursion and swapping, we can create mirror tree.We will swap the the left-node and right-node of root node. We will use recursion and start swapping from the bottom of the tree.*/ // function to form mirror image a treevoid mirrortree(struct treenode* root){ if (root != NULL) { mirrortree(root->left); mirrortree(root->right); struct treenode* temp; temp = root->left; root->left = root->right; root->right = temp; } return;} // function for the inorder traversalvoid inorder(struct treenode* root){ if (root == NULL) return; inorder(root->left); cout << root->info << " "; inorder(root->right);} // Driver codeint main(){ // creating variable of the // structure struct treenode* root = NULL; // calling create function to // create tree root = create(); mirrortree(root); cout << "\nInorder of the mirror tree is = "; inorder(root); return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(1) Serialization of a tree is defined as the conversion of the given tree into a data-format that can be later restored and the structure of the tree must be maintained. Below is the program to implement the above approach: C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // structure of the binary treestruct treenode { // data part int info; // left and right node struct treenode *left, *right;}; // create function for binary// tree creationstruct treenode* create(){ int data; // variable of the structure struct treenode* tree; // dynamically allocating // memory for tree-node tree = new treenode; cout << "\nEnter data to be inserted or type -1 for no insertion : "; // input from the user cin >> data; // condition for termination if (data == -1) return 0; // assigning value from user // into tree. tree->info = data; // recursively calling create function // for left and right sub tree cout << "Enter left child of : " << data; tree->left = create(); cout << "Enter right child of : " << data; tree->right = create(); // returning the created tree return tree;}; // Function to serialize the given// Binary Treevoid serialize(struct treenode* root, vector<int>& v){ // If the root is NULL, then // push -1 and return if (root == NULL) { v.push_back(-1); return; } // Otherwise, push the data part v.push_back(root->info); // Recursively Call for the left // and the right Subtree serialize(root->left, v); serialize(root->right, v);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create a tree root = create(); vector<int> v; serialize(root, v); cout << "\nSerialize form of the tree is = "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; return 0;} /* Will be creating tree: 2 / \ 7 5 / \ \ 2 6 9 */ Output: Time Complexity: O(N)Auxiliary Space: O(N) Complexity Analysis: Time Complexity: O(n).Auxiliary Space: O(1). Time Complexity: O(n). Auxiliary Space: O(1). Binary Tree Inorder Traversal PostOrder Traversal Preorder Traversal Technical Scripter 2020 tree-level-order tree-traversal Recursion Technical Scripter Tree Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Recursive Insertion Sort Program to calculate Height and Depth of a node in a Binary Tree Sum of natural numbers using recursion Decimal to binary number using recursion Recursively Reversing a linked list (A simple implementation) Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24611, "s": 24583, "text": "\n08 Apr, 2021" }, { "code": null, "e": 24988, "s": 24611, "text": "The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that is on the right is called “Right sub-tree”." }, { "code": null, "e": 25061, "s": 24988, "text": "Below are the various operations that can be performed on a Binary Tree:" }, { "code": null, "e": 25242, "s": 25061, "text": "The idea is to first create the root node of the given tree, then recursively create the left and the right child for each parent node. Below is the program to illustrate the same:" }, { "code": null, "e": 25246, "s": 25242, "text": "C++" }, { "code": "// C++ program to illustrate how to// create a tree#include <iostream>using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the inorder// traversal of the given Treevoid inorder(struct treenode* root){ // If root is NULL if (root == NULL) return; // Recursively call for the left // and the right subtree inorder(root->left); cout << root->info << \" \"; inorder(root->right);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal inorder(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 26808, "s": 25246, "text": null }, { "code": null, "e": 26816, "s": 26808, "text": "Output:" }, { "code": null, "e": 26859, "s": 26816, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 26993, "s": 26859, "text": "In this traversal, the root is visited first followed by the left and the right subtree. Below is the program to illustrate the same:" }, { "code": null, "e": 26997, "s": 26993, "text": "C++" }, { "code": "// C++ program to demonstrate the// pre-order traversal#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the pre-order// traversal for the given treevoid preorder(struct treenode* root){ // If the root is NULL if (root == NULL) return; // Using tree-node type stack STL stack<treenode*> s; while ((root != NULL) || (!s.empty())) { if (root != NULL) { // Print the root cout << root->info << \" \"; // Push the node in the stack s.push(root); // Move to left subtree root = root->left; } else { // Remove the top of stack root = s.top(); s.pop(); root = root->right; } } cout << endl;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal preorder(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 28940, "s": 26997, "text": null }, { "code": null, "e": 28948, "s": 28940, "text": "Output:" }, { "code": null, "e": 28991, "s": 28948, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 29133, "s": 28991, "text": "In this traversal, the left subtree is visited first followed by the root and the right subtree. Below is the program to illustrate the same:" }, { "code": null, "e": 29137, "s": 29133, "text": "C++" }, { "code": "// C++ program to illustrate how to// create a tree#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the inorder// traversal of the given Treevoid inorder(struct treenode* root){ // If root is NULL if (root == NULL) return; // Recursively call for the left // and the right subtree inorder(root->left); cout << root->info << \" \"; inorder(root->right);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal inorder(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 30704, "s": 29137, "text": null }, { "code": null, "e": 30712, "s": 30704, "text": "Output:" }, { "code": null, "e": 30755, "s": 30712, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 30899, "s": 30755, "text": "In this traversal, the left subtree is visited first, followed by the right subtree and root node. Below is the program to illustrate the same:" }, { "code": null, "e": 30903, "s": 30899, "text": "C++" }, { "code": "// C++ program to implement the// post-order traversal#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the post-order// traversal of the given treevoid postorder(struct treenode* root){ // If the root is NULL return; stack<treenode*> s3; struct treenode* previous = NULL; do { // Iterate until root is present while (root != NULL) { s3.push(root); root = root->left; } while (root == NULL && (!s3.empty())) { root = s3.top(); // If the right subtree is NULL if (root->right == NULL || root->right == previous) { // Print the root information cout << root->info << \" \"; s3.pop(); // Update the previous previous = root; root = NULL; } // Otherwise else root = root->right; } } while (!s3.empty()); cout << endl;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal postorder(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 33079, "s": 30903, "text": null }, { "code": null, "e": 33087, "s": 33079, "text": "Output:" }, { "code": null, "e": 33130, "s": 33087, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 33234, "s": 33130, "text": "In this traversal, the given tree is traversal level-wise. Below is the program to illustrate the same:" }, { "code": null, "e": 33238, "s": 33234, "text": "C++" }, { "code": "// C++ program to illustrate the// level order traversal#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to perform the level-order// traversalvoid levelorder(struct treenode* root){ // If the root is NULL if (root == NULL) return; // Use queue for traversal queue<treenode*> q; // Print the root's value and // push it into the queue cout << root->info << \" \"; q.push(root); // Iterate until queue is non-empty while (!q.empty()) { // Get the front node root = q.front(); q.pop(); // If the root has the left child if (root->left) { cout << root->left->info << \" \"; q.push(root->left); } // If the root has the right child if (root->right) { cout << root->right->info << \" \"; q.push(root->right); } } cout << endl;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal levelorder(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 35323, "s": 33238, "text": null }, { "code": null, "e": 35331, "s": 35323, "text": "Output:" }, { "code": null, "e": 35374, "s": 35331, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 35522, "s": 35374, "text": " The element which is largest among all the elements of the binary tree is called the maximum element. Below is the program to illustrate the same:" }, { "code": null, "e": 35526, "s": 35522, "text": "C++" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to find the maximum element// in the given Binary Treeint FindMax(struct treenode* root){ // If the tree is empty if (root == NULL) return 0; queue<treenode*> q; int max; struct treenode* temp; max = root->info; // Push the root in the queue q.push(root); // Iterate until queue is non-empty while (!q.empty()) { // Get the front node of // the tree root = q.front(); temp = root; q.pop(); // Update the maximum value // of the Tree if (max < temp->info) max = temp->info; if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } // Return the maximum value return max;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Function Call root = create(); // Perform Inorder Traversal FindMax(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 37539, "s": 35526, "text": null }, { "code": null, "e": 37547, "s": 37539, "text": "Output:" }, { "code": null, "e": 37590, "s": 37547, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 37874, "s": 37590, "text": "The approach to search for any particular element in the tree node is to perform any tree traversal on the given tree and check if there exists any node with the given searched value or not. If found to be true, then print “Element is Found”. Otherwise, print “Element Not Found”. " }, { "code": null, "e": 37919, "s": 37874, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 37923, "s": 37919, "text": "C++" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to search an element in the// given Binary Treeint FindElement(struct treenode* root, int data){ // If the root is NULL if (root == NULL) return 0; queue<treenode*> q; struct treenode* temp; if (!root) return 0; else { // Push the root q.push(root); // Perform the level-order traversal while (!q.empty()) { // Get the root root = q.front(); temp = root; q.pop(); // If the node with value data // exists then return 1 if (data == temp->info) return 1; // Recursively push the left and // the right child of the node if (root->left) { q.push(root->left); } if (root->right) { q.push(root->right); } } // Otherwise, not found return 0; }} // Driver Codeint main(){ int data; // Root of the tree struct treenode* root = NULL; // Create the Tree root = create(); cout << \"\\nEnter element to searched : \"; cin >> data; // Function Call if (FindElement(root, data) == 1) cout << \"\\nElement is found\"; else cout << \"Element is not found\"; return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 40264, "s": 37923, "text": null }, { "code": null, "e": 40272, "s": 40264, "text": "Output:" }, { "code": null, "e": 40319, "s": 40272, "text": "Time Complexity: O(log N)Auxiliary Space: O(N)" }, { "code": null, "e": 40364, "s": 40319, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 40368, "s": 40364, "text": "C++" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to print the reverse level// order traversal of the given treevoid reversetree(struct treenode* root){ // If the root is NULL if (root == NULL) return; queue<treenode*> q; stack<int> s; struct treenode* temp; q.push(root); // Until queue is empty while (!q.empty()) { // Get the front node temp = q.front(); q.pop(); // Push every countered node // data into stack s.push(temp->info); // Check for the left subtree if (temp->left) q.push(temp->left); // Check for the right subtree if (temp->right) q.push(temp->right); } // While S is non-empty, print // all the nodes while (!s.empty()) { cout << s.top() << \" \"; s.pop(); }} // Driver Codeint main(){ // Create root node struct treenode* root = NULL; // Create a tree root = create(); cout << \"\\nReversed tree is : \"; reversetree(root); return 0;}/* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9*/", "e": 42398, "s": 40368, "text": null }, { "code": null, "e": 42406, "s": 42398, "text": "Output:" }, { "code": null, "e": 42449, "s": 42406, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 42593, "s": 42449, "text": "The height of the binary tree is the longest path from the root node to any leaf node in the tree. Below is the program to illustrate the same:" }, { "code": null, "e": 42597, "s": 42593, "text": "C++" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into // the tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to find the height of// the given Binary treeint height(struct treenode* root){ int x, y; // If root is NOT NULL if (root != NULL) { // x will contain the height // of left subtree x = height(root->left); // y will contain the height // of right subtree y = height(root->right); if (x > y) // Leaf node has one height // so x or y + 1 return x + 1; else return y + 1; } return 0;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << \"\\nHeight of the tree is : \" << height(root); return 0;}/* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 44371, "s": 42597, "text": null }, { "code": null, "e": 44379, "s": 44371, "text": "Output:" }, { "code": null, "e": 44422, "s": 44379, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 44563, "s": 44422, "text": "The node which is present at the maximum or the last level is called the deepest node. Below is the program to implement the above approach:" }, { "code": null, "e": 44567, "s": 44563, "text": "C++" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Function to find the deepest node// of the given Binary Treeint deepest(struct treenode* root){ // If the root is NULL if (root == NULL) return 0; queue<treenode*> q; q.push(root); // While queue is non-empty while (!q.empty()) { // Get the front node of queue root = q.front(); q.pop(); // Check for the left and // the right subtree if (root->left) q.push(root->left); if (root->right) q.push(root->right); } // Return the value for the // deepest node return (root->info);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << \"\\nDeepest node of the tree is : \" << deepest(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 46398, "s": 44567, "text": null }, { "code": null, "e": 46406, "s": 46398, "text": "Output:" }, { "code": null, "e": 46449, "s": 46406, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 46493, "s": 46449, "text": "Below is the program to implement the same:" }, { "code": null, "e": 46497, "s": 46493, "text": "C++" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Stores the maximum left sizeint maxlevelleft = 0; // Function to print the left view of// the treevoid leftview(struct treenode* root, int level){ if (root == NULL) return; // If current level is at least // the maximum left level if (level >= maxlevelleft) { // Print the data cout << root->info << \" \"; maxlevelleft++; } // Left and Right Subtree // recursive calls leftview(root->left, level + 1); leftview(root->right, level + 1);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << \"\\nLeft view of the tree is : \"; // Function Call leftview(root, 0); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 48266, "s": 46497, "text": null }, { "code": null, "e": 48274, "s": 48266, "text": "Output:" }, { "code": null, "e": 48317, "s": 48274, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 48362, "s": 48317, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 48366, "s": 48362, "text": "C++" }, { "code": "// C++ program to demonstrate the// above concepts#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Stores the maximum right levelint maxlevelright = 0; // Function to print the right view of// the given Binary treevoid rightview(struct treenode* root, int level){ // If the root is NULL if (root == NULL) return; // If the current level is greater // than the maximum right level if (level >= maxlevelright) { // Print the data cout << root->info << \" \"; maxlevelright++; } // Recursively call for the right // and the left subtree rightview(root->right, level + 1); rightview(root->left, level + 1);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); cout << \"\\nRight view of the tree is : \"; rightview(root, 0); return 0;}/* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9*/", "e": 50221, "s": 48366, "text": null }, { "code": null, "e": 50229, "s": 50221, "text": "Output:" }, { "code": null, "e": 50272, "s": 50229, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 50317, "s": 50272, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 50321, "s": 50317, "text": "C++" }, { "code": "// C++ program to demonstrate the// above concepts#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Initialize an ordered mapmap<int, int> HashMap; // Iterator for the mapmap<int, int>::iterator it; // Function to print the top view// of the given Binary Treevoid topview(struct treenode* root, int level){ // If the root is NULL if (root == NULL) return; // Get the level int i = HashMap.count(level); // Update the root information if (i == 0) HashMap[level] = root->info; // Left and Right recursive calls topview(root->left, level - 1); topview(root->right, level + 1); // Update the current level // with the root's value HashMap[level] = root->info; return;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create a tree root = create(); topview(root, 0); cout << \"\\nTop view of the tree is : \"; for (it = HashMap.begin(); it != HashMap.end(); it++) { cout << it->second << \" \"; } return 0;}/* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9*/", "e": 52337, "s": 50321, "text": null }, { "code": null, "e": 52345, "s": 52337, "text": "Output:" }, { "code": null, "e": 52388, "s": 52345, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 52433, "s": 52388, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 52437, "s": 52433, "text": "C++" }, { "code": "// C++ program to demonstrate the// above concepts#include \"bits/stdc++.h\"using namespace std; // Structure of the Binary Treestruct treenode { int info; struct treenode *left, *right;}; // Function to create the Binary Treestruct treenode* create(){ int data; struct treenode* tree; // Dynamically allocating memory // for the tree-node tree = new treenode; cout << \"\\nEnter data to be inserted \" << \"or type -1 for no insertion : \"; // Input from the user cin >> data; // Termination Condition if (data == -1) return 0; // Assign value from user into tree tree->info = data; // Recursively Call to create the // left and the right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // Return the created Tree return tree;}; // Initialize an ordered Mapmap<int, pair<int, int> > HashMap; // Iterator for the mapmap<int, pair<int, int> >::iterator it; // Function to print the bottom view// of the given binary treevoid bottomview(struct treenode* root, int level, int height){ // If root is NULL if (root == NULL) return; // If the height of the level is // greater than the current // stored height of the level if (height >= HashMap[level].second) { HashMap[level] = { root->info, height }; } // Left and right recursive calls bottomview(root->left, level - 1, height + 1); bottomview(root->right, level + 1, height + 1); return;} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create the tree root = create(); bottomview(root, 0, 0); cout << \"\\nBottom view of the tree is : \"; for (it = HashMap.begin(); it != HashMap.end(); it++) { cout << it->second.first << \" \"; } return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 54562, "s": 52437, "text": null }, { "code": null, "e": 54570, "s": 54562, "text": "Output:" }, { "code": null, "e": 54613, "s": 54570, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 54658, "s": 54613, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 54662, "s": 54658, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // structure of the binary treestruct treenode { // data part int info; // left and right node struct treenode *left, *right;}; // create function for binary// tree creationstruct treenode* create(){ int data; // variable of the structure struct treenode* tree; // dynamically allocating // memory for tree-node tree = new treenode; cout << \"\\nEnter data to be inserted or type -1 for no insertion : \"; // input from the user cin >> data; // condition for termination if (data == -1) return 0; // assigning value from user // into tree. tree->info = data; // recursively calling create function // for left and right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // returning the created tree return tree;}; /*With the simple logic of recursion and swapping, we can create mirror tree.We will swap the the left-node and right-node of root node. We will use recursion and start swapping from the bottom of the tree.*/ // function to form mirror image a treevoid mirrortree(struct treenode* root){ if (root != NULL) { mirrortree(root->left); mirrortree(root->right); struct treenode* temp; temp = root->left; root->left = root->right; root->right = temp; } return;} // function for the inorder traversalvoid inorder(struct treenode* root){ if (root == NULL) return; inorder(root->left); cout << root->info << \" \"; inorder(root->right);} // Driver codeint main(){ // creating variable of the // structure struct treenode* root = NULL; // calling create function to // create tree root = create(); mirrortree(root); cout << \"\\nInorder of the mirror tree is = \"; inorder(root); return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 56780, "s": 54662, "text": null }, { "code": null, "e": 56788, "s": 56780, "text": "Output:" }, { "code": null, "e": 56831, "s": 56788, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 57052, "s": 56831, "text": "Serialization of a tree is defined as the conversion of the given tree into a data-format that can be later restored and the structure of the tree must be maintained. Below is the program to implement the above approach:" }, { "code": null, "e": 57056, "s": 57052, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // structure of the binary treestruct treenode { // data part int info; // left and right node struct treenode *left, *right;}; // create function for binary// tree creationstruct treenode* create(){ int data; // variable of the structure struct treenode* tree; // dynamically allocating // memory for tree-node tree = new treenode; cout << \"\\nEnter data to be inserted or type -1 for no insertion : \"; // input from the user cin >> data; // condition for termination if (data == -1) return 0; // assigning value from user // into tree. tree->info = data; // recursively calling create function // for left and right sub tree cout << \"Enter left child of : \" << data; tree->left = create(); cout << \"Enter right child of : \" << data; tree->right = create(); // returning the created tree return tree;}; // Function to serialize the given// Binary Treevoid serialize(struct treenode* root, vector<int>& v){ // If the root is NULL, then // push -1 and return if (root == NULL) { v.push_back(-1); return; } // Otherwise, push the data part v.push_back(root->info); // Recursively Call for the left // and the right Subtree serialize(root->left, v); serialize(root->right, v);} // Driver Codeint main(){ // Root Node struct treenode* root = NULL; // Create a tree root = create(); vector<int> v; serialize(root, v); cout << \"\\nSerialize form of the tree is = \"; for (int i = 0; i < v.size(); i++) cout << v[i] << \" \"; return 0;} /* Will be creating tree: 2 / \\ 7 5 / \\ \\ 2 6 9 */", "e": 58910, "s": 57056, "text": null }, { "code": null, "e": 58918, "s": 58910, "text": "Output:" }, { "code": null, "e": 58961, "s": 58918, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 58982, "s": 58961, "text": "Complexity Analysis:" }, { "code": null, "e": 59027, "s": 58982, "text": "Time Complexity: O(n).Auxiliary Space: O(1)." }, { "code": null, "e": 59050, "s": 59027, "text": "Time Complexity: O(n)." }, { "code": null, "e": 59073, "s": 59050, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 59085, "s": 59073, "text": "Binary Tree" }, { "code": null, "e": 59103, "s": 59085, "text": "Inorder Traversal" }, { "code": null, "e": 59123, "s": 59103, "text": "PostOrder Traversal" }, { "code": null, "e": 59142, "s": 59123, "text": "Preorder Traversal" }, { "code": null, "e": 59166, "s": 59142, "text": "Technical Scripter 2020" }, { "code": null, "e": 59183, "s": 59166, "text": "tree-level-order" }, { "code": null, "e": 59198, "s": 59183, "text": "tree-traversal" }, { "code": null, "e": 59208, "s": 59198, "text": "Recursion" }, { "code": null, "e": 59227, "s": 59208, "text": "Technical Scripter" }, { "code": null, "e": 59232, "s": 59227, "text": "Tree" }, { "code": null, "e": 59242, "s": 59232, "text": "Recursion" }, { "code": null, "e": 59247, "s": 59242, "text": "Tree" }, { "code": null, "e": 59345, "s": 59247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 59354, "s": 59345, "text": "Comments" }, { "code": null, "e": 59367, "s": 59354, "text": "Old Comments" }, { "code": null, "e": 59392, "s": 59367, "text": "Recursive Insertion Sort" }, { "code": null, "e": 59457, "s": 59392, "text": "Program to calculate Height and Depth of a node in a Binary Tree" }, { "code": null, "e": 59496, "s": 59457, "text": "Sum of natural numbers using recursion" }, { "code": null, "e": 59537, "s": 59496, "text": "Decimal to binary number using recursion" }, { "code": null, "e": 59599, "s": 59537, "text": "Recursively Reversing a linked list (A simple implementation)" }, { "code": null, "e": 59649, "s": 59599, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 59684, "s": 59649, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 59718, "s": 59684, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 59747, "s": 59718, "text": "AVL Tree | Set 1 (Insertion)" } ]
Node.js External HTTP call
Theory of Computation It is often necessary for a network application to make external HTTP calls. HTTP servers are also often called upon to perform HTTP services for clients making requests. Node provides an easy interface for making external HTTP calls. For example, the following code will fetch the front page of google.com. var http = require('http'); http.request({ host: 'www.google.com', method: 'GET', path: "/" }, function(response) { response.setEncoding("utf8"); response.on("readable", function() {
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 420, "s": 112, "text": "It is often necessary for a network application to make external HTTP calls. HTTP servers are also often called upon to perform HTTP services for clients making requests. Node provides an easy interface for making external HTTP calls. For example, the following code will fetch the front page of google.com." } ]
Git Staging Environment
One of the core functions of Git is the concepts of the Staging Environment, and the Commit. As you are working, you may be adding, editing and removing files. But whenever you hit a milestone or finish a part of the work, you should add the files to a Staging Environment. Staged files are files that are ready to be committed to the repository you are working on. You will learn more about commit shortly. For now, we are done working with index.html. So we can add it to the Staging Environment: git add index.html The file should be Staged. Let's check the status:: git status On branch master No commits yet Changes to be committed: (use "git rm --cached ..." to unstage) new file: index.html Now the file has been added to the Staging Environment. You can also stage more than one file at a time. Let's add 2 more files to our working folder. Use the text editor again. A README.md file that describes the repository (recommended for all repositories): A basic external style sheet (bluestyle.css): And update index.html to include the stylesheet: Now add all files in the current directory to the Staging Environment: git add --all Using --all instead of individual filenames will stage all changes (new, modified, and deleted) files. git status On branch master No commits yet Changes to be committed: (use "git rm --cached ..." to unstage) new file: README.md new file: bluestyle.css new file: index.html Now all 3 files are added to the Staging Environment, and we are ready to do our first commit. Note: The shorthand command for git add --all is git add -A Add index.html to the Stating Environment: git index.html Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 93, "s": 0, "text": "One of the core functions of Git is the concepts of the Staging Environment, and the Commit." }, { "code": null, "e": 276, "s": 93, "text": "As you are working, you may be adding, editing and removing files. But \nwhenever you hit a milestone or finish a part of the work, you should add the \nfiles to a Staging Environment." }, { "code": null, "e": 413, "s": 276, "text": "Staged files are files that are ready to be \ncommitted to the \nrepository you are working on. You will learn more about \ncommit shortly." }, { "code": null, "e": 505, "s": 413, "text": "For now, we are done working with index.html. \nSo we can add it to the Staging Environment:" }, { "code": null, "e": 524, "s": 505, "text": "git add index.html" }, { "code": null, "e": 576, "s": 524, "text": "The file should be Staged. Let's check the status::" }, { "code": null, "e": 712, "s": 576, "text": "git status\nOn branch master\n\nNo commits yet\n\nChanges to be committed:\n (use \"git rm --cached ...\" to unstage)\n new file: index.html" }, { "code": null, "e": 768, "s": 712, "text": "Now the file has been added to the Staging Environment." }, { "code": null, "e": 890, "s": 768, "text": "You can also stage more than one file at a time. Let's add 2 more files to our working folder. Use the text editor again." }, { "code": null, "e": 974, "s": 890, "text": "A README.md file that describes the repository (recommended for all \nrepositories):" }, { "code": null, "e": 1020, "s": 974, "text": "A basic external style sheet (bluestyle.css):" }, { "code": null, "e": 1069, "s": 1020, "text": "And update index.html to include the stylesheet:" }, { "code": null, "e": 1140, "s": 1069, "text": "Now add all files in the current directory to the Staging Environment:" }, { "code": null, "e": 1154, "s": 1140, "text": "git add --all" }, { "code": null, "e": 1258, "s": 1154, "text": "Using --all instead of individual filenames \nwill stage all changes (new, modified, and deleted) files." }, { "code": null, "e": 1464, "s": 1258, "text": "git status\nOn branch master\n\nNo commits yet\n\nChanges to be committed:\n (use \"git rm --cached ...\" to unstage)\n new file: README.md\n new file: bluestyle.css\n new file: index.html" }, { "code": null, "e": 1560, "s": 1464, "text": "Now all 3 files are added to the Staging Environment, and we are ready to do \nour first commit." }, { "code": null, "e": 1623, "s": 1560, "text": "Note: The shorthand command for \n git add --all is git add -A" }, { "code": null, "e": 1666, "s": 1623, "text": "Add index.html to the Stating Environment:" }, { "code": null, "e": 1683, "s": 1666, "text": "git index.html\n" }, { "code": null, "e": 1703, "s": 1683, "text": "\nStart the Exercise" }, { "code": null, "e": 1736, "s": 1703, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1778, "s": 1736, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1885, "s": 1778, "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": 1904, "s": 1885, "text": "[email protected]" } ]
How to add time in minutes in datetime string PHP?
For this, you can use the strtotime() method. The syntax is as follows − $anyVariableName= strtotime('anyDateValue + X minute'); You can put the integer value in place of X. The PHP code is as follows Live Demo <!DOCTYPE html> <html> <body> <?php $addingFiveMinutes= strtotime('2020-10-30 10:10:20 + 5 minute'); echo date('Y-m-d H:i:s', $addingFiveMinutes); ?> </body> </html> This will produce the following output 2020-10-30 10:15:20
[ { "code": null, "e": 1108, "s": 1062, "text": "For this, you can use the strtotime() method." }, { "code": null, "e": 1135, "s": 1108, "text": "The syntax is as follows −" }, { "code": null, "e": 1191, "s": 1135, "text": "$anyVariableName= strtotime('anyDateValue + X minute');" }, { "code": null, "e": 1236, "s": 1191, "text": "You can put the integer value in place of X." }, { "code": null, "e": 1263, "s": 1236, "text": "The PHP code is as follows" }, { "code": null, "e": 1274, "s": 1263, "text": " Live Demo" }, { "code": null, "e": 1440, "s": 1274, "text": "<!DOCTYPE html>\n<html>\n<body>\n<?php\n$addingFiveMinutes= strtotime('2020-10-30 10:10:20 + 5 minute');\necho date('Y-m-d H:i:s', $addingFiveMinutes);\n?>\n</body>\n</html>" }, { "code": null, "e": 1479, "s": 1440, "text": "This will produce the following output" }, { "code": null, "e": 1499, "s": 1479, "text": "2020-10-30 10:15:20" } ]
Python for Finance: Stock Portfolio Analyses | by Kevin Boller | Towards Data Science
My two most recent blog posts were about Scaling Analytical Insights with Python; part 1 can be found here and part 2 can be found here. It has been several months since I wrote those, largely due to the fact that I relocated my family to Seattle to join Amazon in November; I’ve spent most of the time on my primary project determining our global rollout plan and related business intelligence roadmap. Prior to my departure at my former company, FloSports, we were in the process of overhauling our analytics reporting across the organization (data, marketing, product et al), and part of this overhaul included our financial reporting. While I left early on in that implementation, over the past several months I’ve continued using Python extensively for financial analyses, particularly pandas. In this post, I will share how I leveraged some very helpful online resources, the Yahoo Finance API (requires a work around and may require a future data source replacement), and Jupyter notebook to largely automate the tracking and benchmarking of a stock portfolio’s performance. As a quick background, I have been investing in my own stock portfolio since 2002 and developed a financial model for my portfolio a number of years ago. For years, I would download historical prices and load the data into the financial model — while online brokers calculate realized and unrealized returns, as well as income and dividends, I like to have historical data in the model as I conduct my own analyses to evaluate positions. One view / report which I’ve never found from online brokers and services is a “Public Market Equivalent”-like analysis. In short, the Public Market Equivalent (PME) is a set of analyses used in the private equity industry to compare the performance of a private equity fund relative to an industry benchmark. Much more detail here. Related, the vast majority of equity portfolio managers are unable to select a portfolio of stocks which outperforms the broader market, e.g., S&P 500, over the long-term (~1 in 20 actively managed domestic funds beat index funds). Even when some individual stocks outperform, the underperformance of others often outweighs the better performing stocks, meaning overall an investor is worse off than simply investing in an index fund. During business school I learned about PME, and I incorporated a conceptually similar analysis into the evaluation of my current public equity holdings. To do this properly, you should measure the timing of investment inflows specific to each portfolio position (holding periods) relative to an S&P 500 equivalent dollar investment over the identical holding period. As an example, if you bought a stock on 6/1/2016 and you still own it, you would want to compare the stock’s return over that period to the return of an equal dollar investment on 6/1/2016 in the S&P 500 (our benchmark example). Among other things, you may find that even if a stock has done relatively well it may still trail the S&P 500’s return over the same time period. In the past, I downloaded historical price data from Yahoo Finance and used INDEX and MATCH functions in excel to calculate the relative holding period performance of each position versus the S&P 500. While this is an OK way to accomplish this goal, conducting the same using pandas in Jupyter notebook is more scalable and extensible. Whenever you download new data and load into excel, you inevitably need to modify some formulas and validate for errors. Using pandas, adding new calculations, such as a cumulative ROI multiple (which I’ll cover), takes almost no time to implement. And the visualizations, for which I use Plotly, are highly reproducible and much more useful in generating insights. Disclosure: Nothing in this post should be considered investment advice. Past performance is not necessarily indicative of future returns. These are general examples about how to import data using pandas for a small sample of stocks across different time intervals and to benchmark their individual performance against an index. You should direct all investment related questions that you have to your financial advisor. In addition to contributing this tutorial, I’m continuing to revise and build upon this approach, and I outline some considerations for further development at the end of this post. I believe this post will be helpful for novice to intermediate-level data science oriented finance professionals, especially since this should extend to many other types of financial analyses. This approach is “PME-like” in the sense that’s it’s measuring investment inflows over equal holding periods. As public market investments are much more liquid than private equity, and presuming you follow a trailing stop approach, from my perspective it’s more important to focus on active holdings — it’s generally advisable to divest holdings which underperform a benchmark or which you no longer want to own for various reasons, while I take a long-term view and am happy to own outperforming stocks for as long as they’ll have me. Resources: I am a current DataCamp subscriber (future post forthcoming on DataCamp) and this community tutorial on Python for Finance is great. I have created a repo for this post including the Python notebook here, and the excel file here. If you want to see the full interactive version (because Jupyter <←>> GitHub integration is awesome), you can view using nbviewer here. Outline of what we want to accomplish: Import S&P 500 and sample ticker data, using the Yahoo Finance API Create a merged portfolio ‘master’ file which combines the sample portfolio dataframe with the historical ticker and historical S&P 500 data Determine what the S&P 500 close was on the date of acquisition of each investment, which allows us to calculate the S&P 500 equivalent share position with the same dollars invested Calculate the relative % and dollar value returns for the portfolio positions versus S&P 500 returns over that time Calculate cumulative portfolio returns and ROI multiple, in order to assess how well this example portfolio compared to a market index One of the more important items: dynamically calculate how each position is doing relative to a trailing stop, e.g., if a position closes 25% below its closing high, consider selling the position on the next trading day. Visualizations Total Return Comparisons — % return of each position relative to index benchmark Cumulative Returns Over Time — $ Gain / (Loss) of each position relative to benchmark Cumulative Investments Over Time — given the above, how do the overall investment returns compare to the equal weighting and time period of S&P 500 investments? Adjusted Close % off of High Comparison — what is each position’s most recent close relative to its adjusted closing high since purchased? You will begin by importing the necessary Python libraries, import the Plotly offline module, and read in our sample portfolio dataframe. # Import initial librariesimport pandas as pdimport numpy as npimport datetimeimport matplotlib.pyplot as pltimport plotly.graph_objs as go%matplotlib inline# Imports in order to be able to use Plotly offline.from plotly import __version__from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotprint(__version__) # requires version >= 1.9.0init_notebook_mode(connected=True)# Import the Sample worksheet with acquisition dates and initial cost basis:portfolio_df = pd.read_excel('Sample stocks acquisition dates_costs.xlsx', sheetname='Sample')portfolio_df.head(10) Now that you have read in the sample portfolio file, you’ll create a few variables which capture the date ranges for the S&P 500 and all of the portfolio’s tickers. Note that this is one of the few aspects of this notebook which requires an update each week (adjust the date range to include the most recent trading week — here, we are running this off of prices through 3/9/2018). # Date Ranges for SP 500 and for all tickers# Modify these date ranges each week.# The below will pull back stock prices from the start date until end date specified.start_sp = datetime.datetime(2013, 1, 1)end_sp = datetime.datetime(2018, 3, 9)# This variable is used for YTD performance.end_of_last_year = datetime.datetime(2017, 12, 29)# These are separate if for some reason want different date range than SP.stocks_start = datetime.datetime(2013, 1, 1)stocks_end = datetime.datetime(2018, 3, 9) As mentioned in the Python Finance training post, the pandas-datareader package enables us to read in data from sources like Google, Yahoo! Finance and the World Bank. Here I’ll focus on Yahoo! Finance, although I’ve worked very preliminarily with Quantopian and have also begun looking into quandl as a data source. As also mentioned in the DataCamp post, the Yahoo API endpoint recently changed and this requires the installation of a temporary fix in order for Yahoo! Finance to work. I’ve made this needed slight adjustment in the code below. I have noticed some minor data issues where the data does not always read in as expected, or the last trading day is sometimes missing. While these issues have been relatively infrequent, I’m continuing to monitor whether or not Yahoo! Finance will be the best and most reliable data source going forward. # Leveraged from the helpful Datacamp Python Finance trading blog post.from pandas_datareader import data as pdrimport fix_yahoo_finance as yfyf.pdr_override() # <== that's all it takes :-)sp500 = pdr.get_data_yahoo('^GSPC', start_sp, end_sp) sp500.head() If you’re following along with your own notebook, you should see something like the below once you’ve successfully read in the data from Yahoo’s API: After loading in the S&P 500 data, you’ll see that I inspect the head and tail of the dataframe, as well as condense the dataframe to only include the Adj Close column. The difference between the Adjusted Close and the Close columns is that an adjusted close reflects dividends (see future areas for development below). When a company issues a dividend, the share price is reduced by the size of the dividend per share, as the company is distributing a portion of the company’s earnings. For purposes of this analysis, you will only need to analyze this column. I also create a dataframe which only includes the S&P’s adjusted close on the last day of 2017 (start of 2018); this is in order to run YTD comparisons of individual tickers relative to the S&P 500’s performance. In the below code, you create an array of all of the tickers in our sample portfolio dataframe. You then write a function to read in all of the tickers and their relevant data into a new dataframe, which is essentially the same approach you took for the S&P500 but applied to all of the portfolio’s tickers. # Generate a dynamic list of tickers to pull from Yahoo Finance API based on the imported file with tickers.tickers = portfolio_df['Ticker'].unique()tickers# Stock comparison codedef get(tickers, startdate, enddate): def data(ticker): return (pdr.get_data_yahoo(ticker, start=startdate, end=enddate)) datas = map(data, tickers) return(pd.concat(datas, keys=tickers, names=['Ticker', 'Date'])) all_data = get(tickers, stocks_start, stocks_end) As with the S&P 500 dataframe, you’ll create an adj_close dataframe which only has the Adj Closecolumn for all of your stock tickers. If you look at the notebook in the repo I link to above, this code is chunked out in more code blocks than shown below. For purposes of describing this here, I’ve included below all of the code which leads up to our initial merged_portfolio dataframe. # Also only pulling the ticker, date and adj. close columns for our tickers.adj_close = all_data[['Adj Close']].reset_index()adj_close.head()# Grabbing the ticker close from the end of last yearadj_close_start = adj_close[adj_close['Date']==end_of_last_year]adj_close_start.head()# Grab the latest stock close priceadj_close_latest = adj_close[adj_close['Date']==stocks_end]adj_close_latestadj_close_latest.set_index('Ticker', inplace=True)adj_close_latest.head()# Set portfolio index prior to merging with the adj close latest.portfolio_df.set_index(['Ticker'], inplace=True)portfolio_df.head()# Merge the portfolio dataframe with the adj close dataframe; they are being joined by their indexes.merged_portfolio = pd.merge(portfolio_df, adj_close_latest, left_index=True, right_index=True)merged_portfolio.head()# The below creates a new column which is the ticker return; takes the latest adjusted close for each position# and divides that by the initial share cost.merged_portfolio['ticker return'] = merged_portfolio['Adj Close'] / merged_portfolio['Unit Cost'] - 1merged_portfolio Depending on your level of familiarity with pandas, this will be very straightforward to slightly overwhelming. Below, I’ll unpack what these lines are doing: The overall approach you are taking is an example of split-apply-combine (note this downloads a PDF). The all_data[['Adj Close']] line creates a new dataframe with only the columns provided in the list; here Adj Close is the only item provided in the list. Using this line of code, adj_close[adj_close['Date']==end_of_last_year], you are filtering the adj_close dataframe to only the row where the data’s Date column equals the date which you earlier specified in the end_of_last_year variable (2017, 12, 29). You also set the index of the adj_close_latest and portfolio_df dataframes. I did this because this is how you’ll merge the two dataframes. The merge function, very similar to SQL joins, is an extremely useful function which I use very often. Within the merge function, you specify the left dataframe ( portfolio_df ) and our right dataframe ( adj_close_latest ). By specifying left_index and right_index equal True, you are stating that the two dataframes share a common index and you will join both on this. Last, you create a new column called 'ticker return' . This calculates the percent return for each stock position by dividing the Adj Close by the Unit Cost (initial purchase price for stock) and subtracting 1. This is similar to calculating a formula in excel and carrying it down, but in pandasthis is accomplished with one-line of code. You have taken the individual dataframes for the S&P 500 and individual stocks, and you are beginning to develop a ‘master’ dataframe which we’ll use for calculations, visualizations and any further analysis. Next, you continue to build on this ‘master’ dataframe with further use of pandas merge function. Below, you reset the current dataframe’s index and begin joining your smaller dataframes with the master one. Once again, the below code block is broken out further in the Jupyter notebook; here I take a similar approach to before where I’ll share the code below and then break down the key callouts below the code block. merged_portfolio.reset_index(inplace=True)# Here we are merging the new dataframe with the sp500 adjusted closes since the sp start price based on # each ticker's acquisition date and sp500 close date.merged_portfolio_sp = pd.merge(merged_portfolio, sp_500_adj_close, left_on='Acquisition Date', right_on='Date')# .set_index('Ticker')# We will delete the additional date column which is created from this merge.# We then rename columns to Latest Date and then reflect Ticker Adj Close and SP 500 Initial Close.del merged_portfolio_sp['Date_y']merged_portfolio_sp.rename(columns={'Date_x': 'Latest Date', 'Adj Close_x': 'Ticker Adj Close' , 'Adj Close_y': 'SP 500 Initial Close'}, inplace=True)# This new column determines what SP 500 equivalent purchase would have been at purchase date of stock.merged_portfolio_sp['Equiv SP Shares'] = merged_portfolio_sp['Cost Basis'] / merged_portfolio_sp['SP 500 Initial Close']merged_portfolio_sp.head()# We are joining the developing dataframe with the sp500 closes again, this time with the latest close for SP.merged_portfolio_sp_latest = pd.merge(merged_portfolio_sp, sp_500_adj_close, left_on='Latest Date', right_on='Date')# Once again need to delete the new Date column added as it's redundant to Latest Date. # Modify Adj Close from the sp dataframe to distinguish it by calling it the SP 500 Latest Close.del merged_portfolio_sp_latest['Date']merged_portfolio_sp_latest.rename(columns={'Adj Close': 'SP 500 Latest Close'}, inplace=True)merged_portfolio_sp_latest.head() You use reset_index on the merged_portfolio in order to flatten the master dataframe and join on the smaller dataframes’ relevant columns. In the merged_portfolio_sp line, you merge the current master dataframe (merged_portfolio) with the sp_500_adj_close; you do this in order to have the S&P’s closing price on each position’s purchase date – this allows you to track the S&P performance over the same time period that each position is held (from acquisition date to most recent market close date). The merge here is slightly different than before, in that we join on the left dataframe’s Acquisition Date column and on the right dataframe’s Date column. After completing this merge, you will have extra columns which you do not need — since our master dataframe will eventually have a considerable number of columns for analysis, it is important to prune duplicative and unnecessary columns along the way. There are several ways to remove unnecessary columns and perform various column name cleanups; for simplicity, I use python del and then rename a few columns with pandas rename method, clarifying the ticker’s Adj Close column by renaming to Ticker Adj Close; and you distinguish the S&P’s initial adjusted close with SP 500 Initial Close. When you calculate merged_portfolio_sp['Equiv SP Shares'], you do so in order to be able to calculate the S&P 500’s equivalent value for the close on the date you acquired each ticker position: if you spend $5,000 on a new stock position, you could have spent $5,000 on the S&P 500; continuing the example, if the S&P 500 was trading at $2,500 per share at the time of purchase, you would have been able to purchase 2 shares. Later, if the S&P 500 is trading for $3,000 per share, your stake would be worth $6,000 (2 equivalent shares * $3,000 per share) and you would have $1,000 in paper profits over this comparable time period. In the rest of the code block, you next perform a similar merge, this time joining on the S&P 500’s latest close — this provides the second piece needed to calculate the S&P’s comparable return relative to each position’s holding period: the S&P 500 price on each ticker’s acquisition day and the S&P 500’s latest market close. You have now further developed your ‘master’ dataframe with the following: Each portfolio position’s price, shares and value on the position acquisition day, as well as the latest market’s closing price. An equivalent S&P 500 price, shares and value on the equivalent position acquisition day for each ticker, as well as the latest S&P 500 closing price. Given the above, you will next perform the requisite calculations in order to compare each position’s performance, as well as the overall performance of this strategy / basket of stocks, relative to comparable dollar investment and holding times of the S&P 500. Below is a summary of the new columns which you are adding to the ‘master’ dataframe. In the first column, ['SP Return'], you create a column which calculates the absolute percent return of the S&P 500 over the holding period of each position (note, this is an absolute return and is not an annualized return). In the second column (['Abs. Return Compare']), you compare the ['ticker return'] (each position’s return) relative to the ['SP Return'] over the same time period. In the next three columns, ['Ticker Share Value'], ['SP 500 Value'] and ['Abs Value Compare'], we calculate the dollar value (market value) equivalent based on the shares we hold multiplied by the latest adjusted close price (and subtract the S&P return from the ticker to calculate over / (under) performance). Last, the ['Stock Gain / (Loss)'] and ['SP 500 Gain / (Loss)'] columns calculate our unrealized dollar gain / loss on each position and comparable S&P 500 gain / loss; this allows us to compare the value impact of each position versus simply investing those dollars in the S&P 500. # Percent return of SP from acquisition date of position through latest trading day.merged_portfolio_sp_latest['SP Return'] = merged_portfolio_sp_latest['SP 500 Latest Close'] / merged_portfolio_sp_latest['SP 500 Initial Close'] - 1# This is a new column which takes the tickers return and subtracts the sp 500 equivalent range return.merged_portfolio_sp_latest['Abs. Return Compare'] = merged_portfolio_sp_latest['ticker return'] - merged_portfolio_sp_latest['SP Return']# This is a new column where we calculate the ticker's share value by multiplying the original quantity by the latest close.merged_portfolio_sp_latest['Ticker Share Value'] = merged_portfolio_sp_latest['Quantity'] * merged_portfolio_sp_latest['Ticker Adj Close']# We calculate the equivalent SP 500 Value if we take the original SP shares * the latest SP 500 share price.merged_portfolio_sp_latest['SP 500 Value'] = merged_portfolio_sp_latest['Equiv SP Shares'] * merged_portfolio_sp_latest['SP 500 Latest Close']# This is a new column where we take the current market value for the shares and subtract the SP 500 value.merged_portfolio_sp_latest['Abs Value Compare'] = merged_portfolio_sp_latest['Ticker Share Value'] - merged_portfolio_sp_latest['SP 500 Value']# This column calculates profit / loss for stock position.merged_portfolio_sp_latest['Stock Gain / (Loss)'] = merged_portfolio_sp_latest['Ticker Share Value'] - merged_portfolio_sp_latest['Cost Basis']# This column calculates profit / loss for SP 500.merged_portfolio_sp_latest['SP 500 Gain / (Loss)'] = merged_portfolio_sp_latest['SP 500 Value'] - merged_portfolio_sp_latest['Cost Basis']merged_portfolio_sp_latest.head() You now have what you need in order to compare your portfolio’s performance to a portfolio equally invested in the S&P 500. The next two code block sections allow you to i) compare YTD performance of each position relative to the S&P 500 (a measure of momentum and how your positions are pacing) and ii) compare the most recent closing price for each portfolio position relative to its most recent closing high (this allows you to assess if a position has triggered a trailing stop, e.g., closed 25% below closing high). Below, I’ll start with the YTD performance code block and provide details regarding the code further below. # Merge the overall dataframe with the adj close start of year dataframe for YTD tracking of tickers.merged_portfolio_sp_latest_YTD = pd.merge(merged_portfolio_sp_latest, adj_close_start, on='Ticker')# , how='outer'# Deleting date again as it's an unnecessary column. Explaining that new column is the Ticker Start of Year Close.del merged_portfolio_sp_latest_YTD['Date']merged_portfolio_sp_latest_YTD.rename(columns={'Adj Close': 'Ticker Start Year Close'}, inplace=True)# Join the SP 500 start of year with current dataframe for SP 500 ytd comparisons to tickers.merged_portfolio_sp_latest_YTD_sp = pd.merge(merged_portfolio_sp_latest_YTD, sp_500_adj_close_start , left_on='Start of Year', right_on='Date')# Deleting another unneeded Date column.del merged_portfolio_sp_latest_YTD_sp['Date']# Renaming so that it's clear this column is SP 500 start of year close.merged_portfolio_sp_latest_YTD_sp.rename(columns={'Adj Close': 'SP Start Year Close'}, inplace=True)# YTD return for portfolio position.merged_portfolio_sp_latest_YTD_sp['Share YTD'] = merged_portfolio_sp_latest_YTD_sp['Ticker Adj Close'] / merged_portfolio_sp_latest_YTD_sp['Ticker Start Year Close'] - 1# YTD return for SP to run compares.merged_portfolio_sp_latest_YTD_sp['SP 500 YTD'] = merged_portfolio_sp_latest_YTD_sp['SP 500 Latest Close'] / merged_portfolio_sp_latest_YTD_sp['SP Start Year Close'] - 1 When creating the merged_portfolio_sp_latest_YTD dataframe, you are now merging the ‘master’ dataframe with the adj_close_start dataframe; as a quick reminder, you created this dataframe by filtering on the adj_close dataframe where the 'Date' column equaled the variable end_of_last_year; you do this because it’s how YTD (year-to-date) stock and index performances are measured; last year’s ending close is the following year’s starting price. From here, we once again use del to remove unnecessary columns and the rename method to clarify the ‘master’ dataframe’s newly added columns. Last, we take each Ticker (in the ['Ticker Adj Close'] column) and calculate the YTD return for each (we also have an S&P 500 equivalent value for each value in the 'SP 500 Latest Close'column). In the below code block, you use the sort_values method to re-sort our ‘master’ dataframe and then you calculate cumulative portfolio investments (sum of your position acquisition costs), as well the cumulative value of portfolio positions and the cumulative value of the theoretical S&P 500 investments. This allows you to be able to see how your total portfolio, with investments in positions made at different times across the entire period, compares overall to a strategy where you had simply invested in an index. Later on, you’ll use the ['Cum Ticker ROI Mult'] to help you visualize how much each investment contributed to or decreased your overall return on investment (ROI). merged_portfolio_sp_latest_YTD_sp = merged_portfolio_sp_latest_YTD_sp.sort_values(by='Ticker', ascending=True)# Cumulative sum of original investmentmerged_portfolio_sp_latest_YTD_sp['Cum Invst'] = merged_portfolio_sp_latest_YTD_sp['Cost Basis'].cumsum()# Cumulative sum of Ticker Share Value (latest FMV based on initial quantity purchased).merged_portfolio_sp_latest_YTD_sp['Cum Ticker Returns'] = merged_portfolio_sp_latest_YTD_sp['Ticker Share Value'].cumsum()# Cumulative sum of SP Share Value (latest FMV driven off of initial SP equiv purchase).merged_portfolio_sp_latest_YTD_sp['Cum SP Returns'] = merged_portfolio_sp_latest_YTD_sp['SP 500 Value'].cumsum()# Cumulative CoC multiple return for stock investmentsmerged_portfolio_sp_latest_YTD_sp['Cum Ticker ROI Mult'] = merged_portfolio_sp_latest_YTD_sp['Cum Ticker Returns'] / merged_portfolio_sp_latest_YTD_sp['Cum Invst']merged_portfolio_sp_latest_YTD_sp.head() You are now nearing the home stretch and almost ready to start visualizing your data and assessing the strengths and weaknesses of your portfolio’s individual ticker and overall strategy performance. As before, I’ve included the main code block for determining where positions are trading relative to their recent closing high; I’ll then unpack the code further below. # Need to factor in that some positions were purchased much more recently than others.# Join adj_close dataframe with portfolio in order to have acquisition date.portfolio_df.reset_index(inplace=True)adj_close_acq_date = pd.merge(adj_close, portfolio_df, on='Ticker')# delete_columns = ['Quantity', 'Unit Cost', 'Cost Basis', 'Start of Year']del adj_close_acq_date['Quantity']del adj_close_acq_date['Unit Cost']del adj_close_acq_date['Cost Basis']del adj_close_acq_date['Start of Year']# Sort by these columns in this order in order to make it clearer where compare for each position should begin.adj_close_acq_date.sort_values(by=['Ticker', 'Acquisition Date', 'Date'], ascending=[True, True, True], inplace=True)# Anything less than 0 means that the stock close was prior to acquisition.adj_close_acq_date['Date Delta'] = adj_close_acq_date['Date'] - adj_close_acq_date['Acquisition Date']adj_close_acq_date['Date Delta'] = adj_close_acq_date[['Date Delta']].apply(pd.to_numeric)# Modified the dataframe being evaluated to look at highest close which occurred after Acquisition Date (aka, not prior to purchase).adj_close_acq_date_modified = adj_close_acq_date[adj_close_acq_date['Date Delta']>=0]# This pivot table will index on the Ticker and Acquisition Date, and find the max adjusted close.adj_close_pivot = adj_close_acq_date_modified.pivot_table(index=['Ticker', 'Acquisition Date'], values='Adj Close', aggfunc=np.max)adj_close_pivot.reset_index(inplace=True)# Merge the adj close pivot table with the adj_close table in order to grab the date of the Adj Close High (good to know).adj_close_pivot_merged = pd.merge(adj_close_pivot, adj_close , on=['Ticker', 'Adj Close'])# Merge the Adj Close pivot table with the master dataframe to have the closing high since you have owned the stock.merged_portfolio_sp_latest_YTD_sp_closing_high = pd.merge(merged_portfolio_sp_latest_YTD_sp, adj_close_pivot_merged , on=['Ticker', 'Acquisition Date'])# Renaming so that it's clear that the new columns are closing high and closing high date.merged_portfolio_sp_latest_YTD_sp_closing_high.rename(columns={'Adj Close': 'Closing High Adj Close', 'Date': 'Closing High Adj Close Date'}, inplace=True)merged_portfolio_sp_latest_YTD_sp_closing_high['Pct off High'] = merged_portfolio_sp_latest_YTD_sp_closing_high['Ticker Adj Close'] / merged_portfolio_sp_latest_YTD_sp_closing_high['Closing High Adj Close'] - 1 merged_portfolio_sp_latest_YTD_sp_closing_high To begin, you merge the adj_close dataframe with the portfolio_df dataframe; this is the third time that you’ve leveraged this adj_close dataframe in order to conduct an isolated analysis which you’ll then combine with the overall ‘master’ dataframe. This initial merge is not particularly useful, as you have dates and adjusted close prices which pre-date your acquisition date for each position; as a result, we’ll subset the data post our acquisition date, and then find the max closing price since that time. Once again, I used del to delete the merged dataframe’s unneeded columns; this is code I should refactor, as creating a list, e.g., cols_to_keep, and then filtering the dataframe with this would be a better approach – as an FYI, running the del code block more than once will throw an error and you would need to re-initialize your dataframe then run the del code block again. After removing the unnecessary columns, you then use the sort_values method and sort the values by the 'Ticker', 'Acquisition Date', and 'Date' columns (all ascending); you do this to make sure all of the ticker rows are sorted together, and we sort by Acquisition Date (in case we’ve purchased the same stock more than once) and Date ascending in order to filter out the dates prior to your positions’ acquisition dates. In other words, you are only concerned with the closing high since you’ve held the position. In order to filter our dataframe, you create a new column ['Date Delta'] which is calculated by the difference between the Date and Acquisition Date columns. You then convert this column into a numeric column, and you create a new dataframe called adj_close_acq_date_modified where the ['Date Delta'] is >= 0. This ensures that you are only evaluating closing highs since the date that you purchased each position. Now that you have the adj_close_acq_date_modified dataframe, we’ll use a very powerful pandas function called pivot_table. If you’re familiar with pivot tables in Excel, this function is similar in that you can pivot data based on a single or multi-index, specify values to calculate and columns to pivot on, and also use agg functions (which leverage numpy). Using the pivot_table function, we pivot on Ticker and Acquisition Date and specify that we would like to find the maximum (np.max) Adj Close for each position; this allows you to compare the recent Adjusted Close for each position relative to this High Adjusted Close. Now you have an adj_close_pivot dataframe, and you reset the index and join this once again on the adj_close dataframe. This creates the adj_close_pivot_merged dataframe, which tells you when you purchased each position and the date on which it hit its closing high since acquisition. Finally, we will combine our ‘master’ dataframe with this last smaller dataframe, adj_close_pivot_merged. After doing so, you are now able to calculate the final column needed, ['Pct off High']. You take the ['Ticker Adj Close'] and divide it by the ['Closing High Adj Close'] and subtract 1. Note, that this percentage will always be negative, unless the stock happened to have its highest close (in this case it will be zero) on the most recent trading day evaluated (this is generally a very good sign if it’s the case). This has been a pretty significant lift, and it’s now time for our long-awaited visualizations. If you’ve continued to follow along in your own notebook, you now have a very rich dataframe with a number of calculated portfolio metrics, as shown in the below: For all of these visualizations you’ll use Plotly, which allows you to make D3 charts entirely without code. While I also use Matplotlib and Seaborn, I really value the interactivity of Plotly; and once you are used to it, the syntax becomes fairly straightforward and dynamic charts are easily attainable. Your first chart below compares each individual position’s total return relative to the S&P 500 (same holding periods for the position and hypothetical investment in the S&P 500). In the below, you’ll see that over their distinct holding periods, 6 of the 8 positions outperformed the S&P. The last two, Twitter (which actually has had a negative return) and Walmart underperformed an equal timed investment in the S&P 500. As each of these visualizations are relatively similar, I’ll explain the code required to generate the above Plotly visualization, and for the remaining ones I’ll only summarize observations from each visualization. trace1 = go.Bar( x = merged_portfolio_sp_latest_YTD_sp_closing_high['Ticker'][0:10], y = merged_portfolio_sp_latest_YTD_sp_closing_high['ticker return'][0:10], name = 'Ticker Total Return')trace2 = go.Scatter( x = merged_portfolio_sp_latest_YTD_sp_closing_high['Ticker'][0:10], y = merged_portfolio_sp_latest_YTD_sp_closing_high['SP Return'][0:10], name = 'SP500 Total Return') data = [trace1, trace2]layout = go.Layout(title = 'Total Return vs S&P 500' , barmode = 'group' , yaxis=dict(title='Returns', tickformat=".2%") , xaxis=dict(title='Ticker') , legend=dict(x=.8,y=1) )fig = go.Figure(data=data, layout=layout)iplot(fig) When using Plotly, you create traces which will plot the x and y data you specify. Here, you specify in trace1 that you want to plot a bar chart, with each Ticker on the x-axis and each ticker’s return on the y-axis. In trace2, to break up the data a bit, we’ll use a Scatter line chart for the Ticker on the x-axis and the S&P Return on the y-axis. Where the bar is above the line, the individual ticker (6 of 8 times) has outperformed the S&P 500. You then create a data object with these traces, and then you provide a layout for the chart; in this case you specify a title, barmode, and the position of the legend; you also pass in a title and tick format (percent format to two decimal places) for the y-axis series. You then create a figure object using go.Figure, specifying the data and layout objects, which you previously named data and layout. The next chart below shows the gain / (loss) dollar amount for each position, relative to the S&P 500, as well as shows the Ticker Total Return %. While it is generally recommended that you allocate an equal position size to your positions (or potentially determine positition sizing based on implied volatility), this may not always be the case. For a less volatile investment, you may invest more than in a riskier position (or you may have other position sizing rules). Given this, this visualization shows both each position’s return and the dollar value contribution to your overall portfolio’s return. Here, you can see that although you invested slightly less in Facebook (FB) than other positions, this stock has returned an ~$20k in this mock portfolio, greater than a 4x return relative to an equivalent S&P 500 investment over the same holding period. The next chart below leverages the cumulative columns which you created: 'Cum Invst', 'Cum SP Returns', 'Cum Ticker Returns', and 'Cum Ticker ROI Mult'. Across the x-axis you have sorted the portfolio alphabetically. Each position shows the initial investment and total value (investment plus returns or less losses) for that position, combined with the positions preceding it. To explain further, based on the ~$8k investment in AAPL, this grew to ~$22.5k (>$14k in gains), versus $15k in total value for the S&P. This is a 2.75x return over the initial investment in AAPL ($22.5k value from $8k investment is ~2.75x ROI). Continuing to FB, you have invested ~$16k in aggregate ($8k in both positions), and this has grown to over $50k, a greater than 3x total return — this means that FB expanded your overall portfolio ROI. Further down the x-axis, you see that both TWTR and WMT have reduced the overall portfolio ROI — this is obvious, as both have underperformed the S&P, but I believe that the magnitude of the contribution is clearer with this visualization. As a caveat, this cumulative approach, given the different holding periods, is a bit of an apples and oranges combination for some positions based on when they were acquired. However, you can always isolate this analysis by sub-setting into smaller dataframes and separately compare positions which have more consistent holding periods. For example, you could compare your 2H 2016 and 1H 2017 purchases separate of one another. Your final chart compares how far off each position’s latest close price is from its adjusted closing high since the position was purchased. This is generally an important visualization to consider: When a stock closes at higher prices, it’s generally recommended to adjust your trailing stop up as well. To illustrate, here’s an example: A position is acquired at $10 and doubles to $20 — using a 25% trailing stop, you would want to consider selling this position the next day if it closed at $15 ($15 / $20–1 = (25%)). If the position increased to $25, you would want to consider moving your trailing stop up to $18.75 ($18.75 / $25–1 = (25%)). As mentioned early on, nothing in here is intended to be financial advice; different trading systems have different rules for trailing stops, and this is an illustrative example. Trailing stops are meant to help preserve gains and are generally important in mitigating the emotions of investing; while it’s easy to see your position’s current return, what tends to be manual (or somewhat expensive if you use a trailing stop service) is calculating how close your positions are to your trailing stops. This final visualization makes this easy to evaluate for any date you are reviewing; in the chart, we see that AAPL, MTCH, and NFLX all closed on 3/9/2018 at their closing highs (typically a very good sign). However, TWTR is greater than 25% below its highest close (33% below as of 3/9/2018) and WMT is ~20% below its highest close. In this case, you might want to sell TWTR and continue to keep a close eye on the performance of WMT. Now you have a relatively extensible Jupyter notebook and portfolio dataset, which you are able to use to evaluate your stock portfolio, as well as add in new metrics and visualizations as you see fit. Please note that while this notebook provides a fairly thorough review of a portfolio, the below have not yet been taken into consideration, would have an impact on the overall comparison, and likely present great areas for future development: As noted initially, this notebook focuses on active holdings — ideally, we would evaluate all positions, both exited and active, in order to have a truly holistic view on one’s investment strategy relative to alternatives, such as an index comparison. The approach in here does not factor in dividends; while we evaluate adjusted close prices (which reflect dividends), total shareholder return combines share price appreciation and dividends to show a stock’s total return; while this is more difficult to do, it is something I’m evaluating to include in the future. On a related note, investors can also reinvest dividends in a position, rather than take a cash distribution; this is arguably even more complicated than accounting for dividends, as the acquisition costs are low and spread out, and over several years of holding a position you could have four (or more) acquisition dates each year for stocks where you reinvest dividends. With those future areas in mind, we accomplished a lot here; this includes importing S&P 500 and ticker data using Yahoo! Finance’s API and creating a master dataframe which combines your portfolio with historical ticker and comparative S&P 500 prices. In doing this, you are able to calculate the absolute percent and dollar value returns for each position (and as compared to equally timed S&P 500 investments), as well as the cumulative impact of each position on your overall portfolio’s performance. You can also dynamically monitor your trailing stops, based on your own trading rules. And you have created visualizations which allow you to have much better insight into your master dataframe, focusing on the different metrics and each position’s contribution to each. I hope that you found this tutorial useful, and I welcome any feedback in the comments. Feel free to also reach out to me on twitter, @kevinboller, and my personal blog can be found here.
[ { "code": null, "e": 576, "s": 172, "text": "My two most recent blog posts were about Scaling Analytical Insights with Python; part 1 can be found here and part 2 can be found here. It has been several months since I wrote those, largely due to the fact that I relocated my family to Seattle to join Amazon in November; I’ve spent most of the time on my primary project determining our global rollout plan and related business intelligence roadmap." }, { "code": null, "e": 1254, "s": 576, "text": "Prior to my departure at my former company, FloSports, we were in the process of overhauling our analytics reporting across the organization (data, marketing, product et al), and part of this overhaul included our financial reporting. While I left early on in that implementation, over the past several months I’ve continued using Python extensively for financial analyses, particularly pandas. In this post, I will share how I leveraged some very helpful online resources, the Yahoo Finance API (requires a work around and may require a future data source replacement), and Jupyter notebook to largely automate the tracking and benchmarking of a stock portfolio’s performance." }, { "code": null, "e": 2025, "s": 1254, "text": "As a quick background, I have been investing in my own stock portfolio since 2002 and developed a financial model for my portfolio a number of years ago. For years, I would download historical prices and load the data into the financial model — while online brokers calculate realized and unrealized returns, as well as income and dividends, I like to have historical data in the model as I conduct my own analyses to evaluate positions. One view / report which I’ve never found from online brokers and services is a “Public Market Equivalent”-like analysis. In short, the Public Market Equivalent (PME) is a set of analyses used in the private equity industry to compare the performance of a private equity fund relative to an industry benchmark. Much more detail here." }, { "code": null, "e": 3202, "s": 2025, "text": "Related, the vast majority of equity portfolio managers are unable to select a portfolio of stocks which outperforms the broader market, e.g., S&P 500, over the long-term (~1 in 20 actively managed domestic funds beat index funds). Even when some individual stocks outperform, the underperformance of others often outweighs the better performing stocks, meaning overall an investor is worse off than simply investing in an index fund. During business school I learned about PME, and I incorporated a conceptually similar analysis into the evaluation of my current public equity holdings. To do this properly, you should measure the timing of investment inflows specific to each portfolio position (holding periods) relative to an S&P 500 equivalent dollar investment over the identical holding period. As an example, if you bought a stock on 6/1/2016 and you still own it, you would want to compare the stock’s return over that period to the return of an equal dollar investment on 6/1/2016 in the S&P 500 (our benchmark example). Among other things, you may find that even if a stock has done relatively well it may still trail the S&P 500’s return over the same time period." }, { "code": null, "e": 3904, "s": 3202, "text": "In the past, I downloaded historical price data from Yahoo Finance and used INDEX and MATCH functions in excel to calculate the relative holding period performance of each position versus the S&P 500. While this is an OK way to accomplish this goal, conducting the same using pandas in Jupyter notebook is more scalable and extensible. Whenever you download new data and load into excel, you inevitably need to modify some formulas and validate for errors. Using pandas, adding new calculations, such as a cumulative ROI multiple (which I’ll cover), takes almost no time to implement. And the visualizations, for which I use Plotly, are highly reproducible and much more useful in generating insights." }, { "code": null, "e": 4325, "s": 3904, "text": "Disclosure: Nothing in this post should be considered investment advice. Past performance is not necessarily indicative of future returns. These are general examples about how to import data using pandas for a small sample of stocks across different time intervals and to benchmark their individual performance against an index. You should direct all investment related questions that you have to your financial advisor." }, { "code": null, "e": 5235, "s": 4325, "text": "In addition to contributing this tutorial, I’m continuing to revise and build upon this approach, and I outline some considerations for further development at the end of this post. I believe this post will be helpful for novice to intermediate-level data science oriented finance professionals, especially since this should extend to many other types of financial analyses. This approach is “PME-like” in the sense that’s it’s measuring investment inflows over equal holding periods. As public market investments are much more liquid than private equity, and presuming you follow a trailing stop approach, from my perspective it’s more important to focus on active holdings — it’s generally advisable to divest holdings which underperform a benchmark or which you no longer want to own for various reasons, while I take a long-term view and am happy to own outperforming stocks for as long as they’ll have me." }, { "code": null, "e": 5246, "s": 5235, "text": "Resources:" }, { "code": null, "e": 5379, "s": 5246, "text": "I am a current DataCamp subscriber (future post forthcoming on DataCamp) and this community tutorial on Python for Finance is great." }, { "code": null, "e": 5476, "s": 5379, "text": "I have created a repo for this post including the Python notebook here, and the excel file here." }, { "code": null, "e": 5612, "s": 5476, "text": "If you want to see the full interactive version (because Jupyter <←>> GitHub integration is awesome), you can view using nbviewer here." }, { "code": null, "e": 5651, "s": 5612, "text": "Outline of what we want to accomplish:" }, { "code": null, "e": 5718, "s": 5651, "text": "Import S&P 500 and sample ticker data, using the Yahoo Finance API" }, { "code": null, "e": 5859, "s": 5718, "text": "Create a merged portfolio ‘master’ file which combines the sample portfolio dataframe with the historical ticker and historical S&P 500 data" }, { "code": null, "e": 6041, "s": 5859, "text": "Determine what the S&P 500 close was on the date of acquisition of each investment, which allows us to calculate the S&P 500 equivalent share position with the same dollars invested" }, { "code": null, "e": 6157, "s": 6041, "text": "Calculate the relative % and dollar value returns for the portfolio positions versus S&P 500 returns over that time" }, { "code": null, "e": 6292, "s": 6157, "text": "Calculate cumulative portfolio returns and ROI multiple, in order to assess how well this example portfolio compared to a market index" }, { "code": null, "e": 6513, "s": 6292, "text": "One of the more important items: dynamically calculate how each position is doing relative to a trailing stop, e.g., if a position closes 25% below its closing high, consider selling the position on the next trading day." }, { "code": null, "e": 6528, "s": 6513, "text": "Visualizations" }, { "code": null, "e": 6609, "s": 6528, "text": "Total Return Comparisons — % return of each position relative to index benchmark" }, { "code": null, "e": 6695, "s": 6609, "text": "Cumulative Returns Over Time — $ Gain / (Loss) of each position relative to benchmark" }, { "code": null, "e": 6856, "s": 6695, "text": "Cumulative Investments Over Time — given the above, how do the overall investment returns compare to the equal weighting and time period of S&P 500 investments?" }, { "code": null, "e": 6995, "s": 6856, "text": "Adjusted Close % off of High Comparison — what is each position’s most recent close relative to its adjusted closing high since purchased?" }, { "code": null, "e": 7133, "s": 6995, "text": "You will begin by importing the necessary Python libraries, import the Plotly offline module, and read in our sample portfolio dataframe." }, { "code": null, "e": 7721, "s": 7133, "text": "# Import initial librariesimport pandas as pdimport numpy as npimport datetimeimport matplotlib.pyplot as pltimport plotly.graph_objs as go%matplotlib inline# Imports in order to be able to use Plotly offline.from plotly import __version__from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotprint(__version__) # requires version >= 1.9.0init_notebook_mode(connected=True)# Import the Sample worksheet with acquisition dates and initial cost basis:portfolio_df = pd.read_excel('Sample stocks acquisition dates_costs.xlsx', sheetname='Sample')portfolio_df.head(10)" }, { "code": null, "e": 8103, "s": 7721, "text": "Now that you have read in the sample portfolio file, you’ll create a few variables which capture the date ranges for the S&P 500 and all of the portfolio’s tickers. Note that this is one of the few aspects of this notebook which requires an update each week (adjust the date range to include the most recent trading week — here, we are running this off of prices through 3/9/2018)." }, { "code": null, "e": 8602, "s": 8103, "text": "# Date Ranges for SP 500 and for all tickers# Modify these date ranges each week.# The below will pull back stock prices from the start date until end date specified.start_sp = datetime.datetime(2013, 1, 1)end_sp = datetime.datetime(2018, 3, 9)# This variable is used for YTD performance.end_of_last_year = datetime.datetime(2017, 12, 29)# These are separate if for some reason want different date range than SP.stocks_start = datetime.datetime(2013, 1, 1)stocks_end = datetime.datetime(2018, 3, 9)" }, { "code": null, "e": 9455, "s": 8602, "text": "As mentioned in the Python Finance training post, the pandas-datareader package enables us to read in data from sources like Google, Yahoo! Finance and the World Bank. Here I’ll focus on Yahoo! Finance, although I’ve worked very preliminarily with Quantopian and have also begun looking into quandl as a data source. As also mentioned in the DataCamp post, the Yahoo API endpoint recently changed and this requires the installation of a temporary fix in order for Yahoo! Finance to work. I’ve made this needed slight adjustment in the code below. I have noticed some minor data issues where the data does not always read in as expected, or the last trading day is sometimes missing. While these issues have been relatively infrequent, I’m continuing to monitor whether or not Yahoo! Finance will be the best and most reliable data source going forward." }, { "code": null, "e": 9769, "s": 9455, "text": "# Leveraged from the helpful Datacamp Python Finance trading blog post.from pandas_datareader import data as pdrimport fix_yahoo_finance as yfyf.pdr_override() # <== that's all it takes :-)sp500 = pdr.get_data_yahoo('^GSPC', start_sp, end_sp) sp500.head()" }, { "code": null, "e": 9919, "s": 9769, "text": "If you’re following along with your own notebook, you should see something like the below once you’ve successfully read in the data from Yahoo’s API:" }, { "code": null, "e": 10694, "s": 9919, "text": "After loading in the S&P 500 data, you’ll see that I inspect the head and tail of the dataframe, as well as condense the dataframe to only include the Adj Close column. The difference between the Adjusted Close and the Close columns is that an adjusted close reflects dividends (see future areas for development below). When a company issues a dividend, the share price is reduced by the size of the dividend per share, as the company is distributing a portion of the company’s earnings. For purposes of this analysis, you will only need to analyze this column. I also create a dataframe which only includes the S&P’s adjusted close on the last day of 2017 (start of 2018); this is in order to run YTD comparisons of individual tickers relative to the S&P 500’s performance." }, { "code": null, "e": 11002, "s": 10694, "text": "In the below code, you create an array of all of the tickers in our sample portfolio dataframe. You then write a function to read in all of the tickers and their relevant data into a new dataframe, which is essentially the same approach you took for the S&P500 but applied to all of the portfolio’s tickers." }, { "code": null, "e": 11475, "s": 11002, "text": "# Generate a dynamic list of tickers to pull from Yahoo Finance API based on the imported file with tickers.tickers = portfolio_df['Ticker'].unique()tickers# Stock comparison codedef get(tickers, startdate, enddate): def data(ticker): return (pdr.get_data_yahoo(ticker, start=startdate, end=enddate)) datas = map(data, tickers) return(pd.concat(datas, keys=tickers, names=['Ticker', 'Date'])) all_data = get(tickers, stocks_start, stocks_end)" }, { "code": null, "e": 11861, "s": 11475, "text": "As with the S&P 500 dataframe, you’ll create an adj_close dataframe which only has the Adj Closecolumn for all of your stock tickers. If you look at the notebook in the repo I link to above, this code is chunked out in more code blocks than shown below. For purposes of describing this here, I’ve included below all of the code which leads up to our initial merged_portfolio dataframe." }, { "code": null, "e": 12947, "s": 11861, "text": "# Also only pulling the ticker, date and adj. close columns for our tickers.adj_close = all_data[['Adj Close']].reset_index()adj_close.head()# Grabbing the ticker close from the end of last yearadj_close_start = adj_close[adj_close['Date']==end_of_last_year]adj_close_start.head()# Grab the latest stock close priceadj_close_latest = adj_close[adj_close['Date']==stocks_end]adj_close_latestadj_close_latest.set_index('Ticker', inplace=True)adj_close_latest.head()# Set portfolio index prior to merging with the adj close latest.portfolio_df.set_index(['Ticker'], inplace=True)portfolio_df.head()# Merge the portfolio dataframe with the adj close dataframe; they are being joined by their indexes.merged_portfolio = pd.merge(portfolio_df, adj_close_latest, left_index=True, right_index=True)merged_portfolio.head()# The below creates a new column which is the ticker return; takes the latest adjusted close for each position# and divides that by the initial share cost.merged_portfolio['ticker return'] = merged_portfolio['Adj Close'] / merged_portfolio['Unit Cost'] - 1merged_portfolio" }, { "code": null, "e": 13106, "s": 12947, "text": "Depending on your level of familiarity with pandas, this will be very straightforward to slightly overwhelming. Below, I’ll unpack what these lines are doing:" }, { "code": null, "e": 13208, "s": 13106, "text": "The overall approach you are taking is an example of split-apply-combine (note this downloads a PDF)." }, { "code": null, "e": 13363, "s": 13208, "text": "The all_data[['Adj Close']] line creates a new dataframe with only the columns provided in the list; here Adj Close is the only item provided in the list." }, { "code": null, "e": 13616, "s": 13363, "text": "Using this line of code, adj_close[adj_close['Date']==end_of_last_year], you are filtering the adj_close dataframe to only the row where the data’s Date column equals the date which you earlier specified in the end_of_last_year variable (2017, 12, 29)." }, { "code": null, "e": 13859, "s": 13616, "text": "You also set the index of the adj_close_latest and portfolio_df dataframes. I did this because this is how you’ll merge the two dataframes. The merge function, very similar to SQL joins, is an extremely useful function which I use very often." }, { "code": null, "e": 14126, "s": 13859, "text": "Within the merge function, you specify the left dataframe ( portfolio_df ) and our right dataframe ( adj_close_latest ). By specifying left_index and right_index equal True, you are stating that the two dataframes share a common index and you will join both on this." }, { "code": null, "e": 14466, "s": 14126, "text": "Last, you create a new column called 'ticker return' . This calculates the percent return for each stock position by dividing the Adj Close by the Unit Cost (initial purchase price for stock) and subtracting 1. This is similar to calculating a formula in excel and carrying it down, but in pandasthis is accomplished with one-line of code." }, { "code": null, "e": 15095, "s": 14466, "text": "You have taken the individual dataframes for the S&P 500 and individual stocks, and you are beginning to develop a ‘master’ dataframe which we’ll use for calculations, visualizations and any further analysis. Next, you continue to build on this ‘master’ dataframe with further use of pandas merge function. Below, you reset the current dataframe’s index and begin joining your smaller dataframes with the master one. Once again, the below code block is broken out further in the Jupyter notebook; here I take a similar approach to before where I’ll share the code below and then break down the key callouts below the code block." }, { "code": null, "e": 16649, "s": 15095, "text": "merged_portfolio.reset_index(inplace=True)# Here we are merging the new dataframe with the sp500 adjusted closes since the sp start price based on # each ticker's acquisition date and sp500 close date.merged_portfolio_sp = pd.merge(merged_portfolio, sp_500_adj_close, left_on='Acquisition Date', right_on='Date')# .set_index('Ticker')# We will delete the additional date column which is created from this merge.# We then rename columns to Latest Date and then reflect Ticker Adj Close and SP 500 Initial Close.del merged_portfolio_sp['Date_y']merged_portfolio_sp.rename(columns={'Date_x': 'Latest Date', 'Adj Close_x': 'Ticker Adj Close' , 'Adj Close_y': 'SP 500 Initial Close'}, inplace=True)# This new column determines what SP 500 equivalent purchase would have been at purchase date of stock.merged_portfolio_sp['Equiv SP Shares'] = merged_portfolio_sp['Cost Basis'] / merged_portfolio_sp['SP 500 Initial Close']merged_portfolio_sp.head()# We are joining the developing dataframe with the sp500 closes again, this time with the latest close for SP.merged_portfolio_sp_latest = pd.merge(merged_portfolio_sp, sp_500_adj_close, left_on='Latest Date', right_on='Date')# Once again need to delete the new Date column added as it's redundant to Latest Date. # Modify Adj Close from the sp dataframe to distinguish it by calling it the SP 500 Latest Close.del merged_portfolio_sp_latest['Date']merged_portfolio_sp_latest.rename(columns={'Adj Close': 'SP 500 Latest Close'}, inplace=True)merged_portfolio_sp_latest.head()" }, { "code": null, "e": 16788, "s": 16649, "text": "You use reset_index on the merged_portfolio in order to flatten the master dataframe and join on the smaller dataframes’ relevant columns." }, { "code": null, "e": 17150, "s": 16788, "text": "In the merged_portfolio_sp line, you merge the current master dataframe (merged_portfolio) with the sp_500_adj_close; you do this in order to have the S&P’s closing price on each position’s purchase date – this allows you to track the S&P performance over the same time period that each position is held (from acquisition date to most recent market close date)." }, { "code": null, "e": 17306, "s": 17150, "text": "The merge here is slightly different than before, in that we join on the left dataframe’s Acquisition Date column and on the right dataframe’s Date column." }, { "code": null, "e": 17558, "s": 17306, "text": "After completing this merge, you will have extra columns which you do not need — since our master dataframe will eventually have a considerable number of columns for analysis, it is important to prune duplicative and unnecessary columns along the way." }, { "code": null, "e": 17897, "s": 17558, "text": "There are several ways to remove unnecessary columns and perform various column name cleanups; for simplicity, I use python del and then rename a few columns with pandas rename method, clarifying the ticker’s Adj Close column by renaming to Ticker Adj Close; and you distinguish the S&P’s initial adjusted close with SP 500 Initial Close." }, { "code": null, "e": 18529, "s": 17897, "text": "When you calculate merged_portfolio_sp['Equiv SP Shares'], you do so in order to be able to calculate the S&P 500’s equivalent value for the close on the date you acquired each ticker position: if you spend $5,000 on a new stock position, you could have spent $5,000 on the S&P 500; continuing the example, if the S&P 500 was trading at $2,500 per share at the time of purchase, you would have been able to purchase 2 shares. Later, if the S&P 500 is trading for $3,000 per share, your stake would be worth $6,000 (2 equivalent shares * $3,000 per share) and you would have $1,000 in paper profits over this comparable time period." }, { "code": null, "e": 18857, "s": 18529, "text": "In the rest of the code block, you next perform a similar merge, this time joining on the S&P 500’s latest close — this provides the second piece needed to calculate the S&P’s comparable return relative to each position’s holding period: the S&P 500 price on each ticker’s acquisition day and the S&P 500’s latest market close." }, { "code": null, "e": 18932, "s": 18857, "text": "You have now further developed your ‘master’ dataframe with the following:" }, { "code": null, "e": 19061, "s": 18932, "text": "Each portfolio position’s price, shares and value on the position acquisition day, as well as the latest market’s closing price." }, { "code": null, "e": 19212, "s": 19061, "text": "An equivalent S&P 500 price, shares and value on the equivalent position acquisition day for each ticker, as well as the latest S&P 500 closing price." }, { "code": null, "e": 19474, "s": 19212, "text": "Given the above, you will next perform the requisite calculations in order to compare each position’s performance, as well as the overall performance of this strategy / basket of stocks, relative to comparable dollar investment and holding times of the S&P 500." }, { "code": null, "e": 19560, "s": 19474, "text": "Below is a summary of the new columns which you are adding to the ‘master’ dataframe." }, { "code": null, "e": 19949, "s": 19560, "text": "In the first column, ['SP Return'], you create a column which calculates the absolute percent return of the S&P 500 over the holding period of each position (note, this is an absolute return and is not an annualized return). In the second column (['Abs. Return Compare']), you compare the ['ticker return'] (each position’s return) relative to the ['SP Return'] over the same time period." }, { "code": null, "e": 20261, "s": 19949, "text": "In the next three columns, ['Ticker Share Value'], ['SP 500 Value'] and ['Abs Value Compare'], we calculate the dollar value (market value) equivalent based on the shares we hold multiplied by the latest adjusted close price (and subtract the S&P return from the ticker to calculate over / (under) performance)." }, { "code": null, "e": 20543, "s": 20261, "text": "Last, the ['Stock Gain / (Loss)'] and ['SP 500 Gain / (Loss)'] columns calculate our unrealized dollar gain / loss on each position and comparable S&P 500 gain / loss; this allows us to compare the value impact of each position versus simply investing those dollars in the S&P 500." }, { "code": null, "e": 22201, "s": 20543, "text": "# Percent return of SP from acquisition date of position through latest trading day.merged_portfolio_sp_latest['SP Return'] = merged_portfolio_sp_latest['SP 500 Latest Close'] / merged_portfolio_sp_latest['SP 500 Initial Close'] - 1# This is a new column which takes the tickers return and subtracts the sp 500 equivalent range return.merged_portfolio_sp_latest['Abs. Return Compare'] = merged_portfolio_sp_latest['ticker return'] - merged_portfolio_sp_latest['SP Return']# This is a new column where we calculate the ticker's share value by multiplying the original quantity by the latest close.merged_portfolio_sp_latest['Ticker Share Value'] = merged_portfolio_sp_latest['Quantity'] * merged_portfolio_sp_latest['Ticker Adj Close']# We calculate the equivalent SP 500 Value if we take the original SP shares * the latest SP 500 share price.merged_portfolio_sp_latest['SP 500 Value'] = merged_portfolio_sp_latest['Equiv SP Shares'] * merged_portfolio_sp_latest['SP 500 Latest Close']# This is a new column where we take the current market value for the shares and subtract the SP 500 value.merged_portfolio_sp_latest['Abs Value Compare'] = merged_portfolio_sp_latest['Ticker Share Value'] - merged_portfolio_sp_latest['SP 500 Value']# This column calculates profit / loss for stock position.merged_portfolio_sp_latest['Stock Gain / (Loss)'] = merged_portfolio_sp_latest['Ticker Share Value'] - merged_portfolio_sp_latest['Cost Basis']# This column calculates profit / loss for SP 500.merged_portfolio_sp_latest['SP 500 Gain / (Loss)'] = merged_portfolio_sp_latest['SP 500 Value'] - merged_portfolio_sp_latest['Cost Basis']merged_portfolio_sp_latest.head()" }, { "code": null, "e": 22722, "s": 22201, "text": "You now have what you need in order to compare your portfolio’s performance to a portfolio equally invested in the S&P 500. The next two code block sections allow you to i) compare YTD performance of each position relative to the S&P 500 (a measure of momentum and how your positions are pacing) and ii) compare the most recent closing price for each portfolio position relative to its most recent closing high (this allows you to assess if a position has triggered a trailing stop, e.g., closed 25% below closing high)." }, { "code": null, "e": 22830, "s": 22722, "text": "Below, I’ll start with the YTD performance code block and provide details regarding the code further below." }, { "code": null, "e": 24251, "s": 22830, "text": "# Merge the overall dataframe with the adj close start of year dataframe for YTD tracking of tickers.merged_portfolio_sp_latest_YTD = pd.merge(merged_portfolio_sp_latest, adj_close_start, on='Ticker')# , how='outer'# Deleting date again as it's an unnecessary column. Explaining that new column is the Ticker Start of Year Close.del merged_portfolio_sp_latest_YTD['Date']merged_portfolio_sp_latest_YTD.rename(columns={'Adj Close': 'Ticker Start Year Close'}, inplace=True)# Join the SP 500 start of year with current dataframe for SP 500 ytd comparisons to tickers.merged_portfolio_sp_latest_YTD_sp = pd.merge(merged_portfolio_sp_latest_YTD, sp_500_adj_close_start , left_on='Start of Year', right_on='Date')# Deleting another unneeded Date column.del merged_portfolio_sp_latest_YTD_sp['Date']# Renaming so that it's clear this column is SP 500 start of year close.merged_portfolio_sp_latest_YTD_sp.rename(columns={'Adj Close': 'SP Start Year Close'}, inplace=True)# YTD return for portfolio position.merged_portfolio_sp_latest_YTD_sp['Share YTD'] = merged_portfolio_sp_latest_YTD_sp['Ticker Adj Close'] / merged_portfolio_sp_latest_YTD_sp['Ticker Start Year Close'] - 1# YTD return for SP to run compares.merged_portfolio_sp_latest_YTD_sp['SP 500 YTD'] = merged_portfolio_sp_latest_YTD_sp['SP 500 Latest Close'] / merged_portfolio_sp_latest_YTD_sp['SP Start Year Close'] - 1" }, { "code": null, "e": 24697, "s": 24251, "text": "When creating the merged_portfolio_sp_latest_YTD dataframe, you are now merging the ‘master’ dataframe with the adj_close_start dataframe; as a quick reminder, you created this dataframe by filtering on the adj_close dataframe where the 'Date' column equaled the variable end_of_last_year; you do this because it’s how YTD (year-to-date) stock and index performances are measured; last year’s ending close is the following year’s starting price." }, { "code": null, "e": 24839, "s": 24697, "text": "From here, we once again use del to remove unnecessary columns and the rename method to clarify the ‘master’ dataframe’s newly added columns." }, { "code": null, "e": 25034, "s": 24839, "text": "Last, we take each Ticker (in the ['Ticker Adj Close'] column) and calculate the YTD return for each (we also have an S&P 500 equivalent value for each value in the 'SP 500 Latest Close'column)." }, { "code": null, "e": 25718, "s": 25034, "text": "In the below code block, you use the sort_values method to re-sort our ‘master’ dataframe and then you calculate cumulative portfolio investments (sum of your position acquisition costs), as well the cumulative value of portfolio positions and the cumulative value of the theoretical S&P 500 investments. This allows you to be able to see how your total portfolio, with investments in positions made at different times across the entire period, compares overall to a strategy where you had simply invested in an index. Later on, you’ll use the ['Cum Ticker ROI Mult'] to help you visualize how much each investment contributed to or decreased your overall return on investment (ROI)." }, { "code": null, "e": 26640, "s": 25718, "text": "merged_portfolio_sp_latest_YTD_sp = merged_portfolio_sp_latest_YTD_sp.sort_values(by='Ticker', ascending=True)# Cumulative sum of original investmentmerged_portfolio_sp_latest_YTD_sp['Cum Invst'] = merged_portfolio_sp_latest_YTD_sp['Cost Basis'].cumsum()# Cumulative sum of Ticker Share Value (latest FMV based on initial quantity purchased).merged_portfolio_sp_latest_YTD_sp['Cum Ticker Returns'] = merged_portfolio_sp_latest_YTD_sp['Ticker Share Value'].cumsum()# Cumulative sum of SP Share Value (latest FMV driven off of initial SP equiv purchase).merged_portfolio_sp_latest_YTD_sp['Cum SP Returns'] = merged_portfolio_sp_latest_YTD_sp['SP 500 Value'].cumsum()# Cumulative CoC multiple return for stock investmentsmerged_portfolio_sp_latest_YTD_sp['Cum Ticker ROI Mult'] = merged_portfolio_sp_latest_YTD_sp['Cum Ticker Returns'] / merged_portfolio_sp_latest_YTD_sp['Cum Invst']merged_portfolio_sp_latest_YTD_sp.head()" }, { "code": null, "e": 26840, "s": 26640, "text": "You are now nearing the home stretch and almost ready to start visualizing your data and assessing the strengths and weaknesses of your portfolio’s individual ticker and overall strategy performance." }, { "code": null, "e": 27009, "s": 26840, "text": "As before, I’ve included the main code block for determining where positions are trading relative to their recent closing high; I’ll then unpack the code further below." }, { "code": null, "e": 29549, "s": 27009, "text": "# Need to factor in that some positions were purchased much more recently than others.# Join adj_close dataframe with portfolio in order to have acquisition date.portfolio_df.reset_index(inplace=True)adj_close_acq_date = pd.merge(adj_close, portfolio_df, on='Ticker')# delete_columns = ['Quantity', 'Unit Cost', 'Cost Basis', 'Start of Year']del adj_close_acq_date['Quantity']del adj_close_acq_date['Unit Cost']del adj_close_acq_date['Cost Basis']del adj_close_acq_date['Start of Year']# Sort by these columns in this order in order to make it clearer where compare for each position should begin.adj_close_acq_date.sort_values(by=['Ticker', 'Acquisition Date', 'Date'], ascending=[True, True, True], inplace=True)# Anything less than 0 means that the stock close was prior to acquisition.adj_close_acq_date['Date Delta'] = adj_close_acq_date['Date'] - adj_close_acq_date['Acquisition Date']adj_close_acq_date['Date Delta'] = adj_close_acq_date[['Date Delta']].apply(pd.to_numeric)# Modified the dataframe being evaluated to look at highest close which occurred after Acquisition Date (aka, not prior to purchase).adj_close_acq_date_modified = adj_close_acq_date[adj_close_acq_date['Date Delta']>=0]# This pivot table will index on the Ticker and Acquisition Date, and find the max adjusted close.adj_close_pivot = adj_close_acq_date_modified.pivot_table(index=['Ticker', 'Acquisition Date'], values='Adj Close', aggfunc=np.max)adj_close_pivot.reset_index(inplace=True)# Merge the adj close pivot table with the adj_close table in order to grab the date of the Adj Close High (good to know).adj_close_pivot_merged = pd.merge(adj_close_pivot, adj_close , on=['Ticker', 'Adj Close'])# Merge the Adj Close pivot table with the master dataframe to have the closing high since you have owned the stock.merged_portfolio_sp_latest_YTD_sp_closing_high = pd.merge(merged_portfolio_sp_latest_YTD_sp, adj_close_pivot_merged , on=['Ticker', 'Acquisition Date'])# Renaming so that it's clear that the new columns are closing high and closing high date.merged_portfolio_sp_latest_YTD_sp_closing_high.rename(columns={'Adj Close': 'Closing High Adj Close', 'Date': 'Closing High Adj Close Date'}, inplace=True)merged_portfolio_sp_latest_YTD_sp_closing_high['Pct off High'] = merged_portfolio_sp_latest_YTD_sp_closing_high['Ticker Adj Close'] / merged_portfolio_sp_latest_YTD_sp_closing_high['Closing High Adj Close'] - 1 merged_portfolio_sp_latest_YTD_sp_closing_high" }, { "code": null, "e": 29800, "s": 29549, "text": "To begin, you merge the adj_close dataframe with the portfolio_df dataframe; this is the third time that you’ve leveraged this adj_close dataframe in order to conduct an isolated analysis which you’ll then combine with the overall ‘master’ dataframe." }, { "code": null, "e": 30062, "s": 29800, "text": "This initial merge is not particularly useful, as you have dates and adjusted close prices which pre-date your acquisition date for each position; as a result, we’ll subset the data post our acquisition date, and then find the max closing price since that time." }, { "code": null, "e": 30439, "s": 30062, "text": "Once again, I used del to delete the merged dataframe’s unneeded columns; this is code I should refactor, as creating a list, e.g., cols_to_keep, and then filtering the dataframe with this would be a better approach – as an FYI, running the del code block more than once will throw an error and you would need to re-initialize your dataframe then run the del code block again." }, { "code": null, "e": 30954, "s": 30439, "text": "After removing the unnecessary columns, you then use the sort_values method and sort the values by the 'Ticker', 'Acquisition Date', and 'Date' columns (all ascending); you do this to make sure all of the ticker rows are sorted together, and we sort by Acquisition Date (in case we’ve purchased the same stock more than once) and Date ascending in order to filter out the dates prior to your positions’ acquisition dates. In other words, you are only concerned with the closing high since you’ve held the position." }, { "code": null, "e": 31112, "s": 30954, "text": "In order to filter our dataframe, you create a new column ['Date Delta'] which is calculated by the difference between the Date and Acquisition Date columns." }, { "code": null, "e": 31369, "s": 31112, "text": "You then convert this column into a numeric column, and you create a new dataframe called adj_close_acq_date_modified where the ['Date Delta'] is >= 0. This ensures that you are only evaluating closing highs since the date that you purchased each position." }, { "code": null, "e": 31729, "s": 31369, "text": "Now that you have the adj_close_acq_date_modified dataframe, we’ll use a very powerful pandas function called pivot_table. If you’re familiar with pivot tables in Excel, this function is similar in that you can pivot data based on a single or multi-index, specify values to calculate and columns to pivot on, and also use agg functions (which leverage numpy)." }, { "code": null, "e": 31999, "s": 31729, "text": "Using the pivot_table function, we pivot on Ticker and Acquisition Date and specify that we would like to find the maximum (np.max) Adj Close for each position; this allows you to compare the recent Adjusted Close for each position relative to this High Adjusted Close." }, { "code": null, "e": 32284, "s": 31999, "text": "Now you have an adj_close_pivot dataframe, and you reset the index and join this once again on the adj_close dataframe. This creates the adj_close_pivot_merged dataframe, which tells you when you purchased each position and the date on which it hit its closing high since acquisition." }, { "code": null, "e": 32390, "s": 32284, "text": "Finally, we will combine our ‘master’ dataframe with this last smaller dataframe, adj_close_pivot_merged." }, { "code": null, "e": 32808, "s": 32390, "text": "After doing so, you are now able to calculate the final column needed, ['Pct off High']. You take the ['Ticker Adj Close'] and divide it by the ['Closing High Adj Close'] and subtract 1. Note, that this percentage will always be negative, unless the stock happened to have its highest close (in this case it will be zero) on the most recent trading day evaluated (this is generally a very good sign if it’s the case)." }, { "code": null, "e": 33067, "s": 32808, "text": "This has been a pretty significant lift, and it’s now time for our long-awaited visualizations. If you’ve continued to follow along in your own notebook, you now have a very rich dataframe with a number of calculated portfolio metrics, as shown in the below:" }, { "code": null, "e": 33374, "s": 33067, "text": "For all of these visualizations you’ll use Plotly, which allows you to make D3 charts entirely without code. While I also use Matplotlib and Seaborn, I really value the interactivity of Plotly; and once you are used to it, the syntax becomes fairly straightforward and dynamic charts are easily attainable." }, { "code": null, "e": 33798, "s": 33374, "text": "Your first chart below compares each individual position’s total return relative to the S&P 500 (same holding periods for the position and hypothetical investment in the S&P 500). In the below, you’ll see that over their distinct holding periods, 6 of the 8 positions outperformed the S&P. The last two, Twitter (which actually has had a negative return) and Walmart underperformed an equal timed investment in the S&P 500." }, { "code": null, "e": 34014, "s": 33798, "text": "As each of these visualizations are relatively similar, I’ll explain the code required to generate the above Plotly visualization, and for the remaining ones I’ll only summarize observations from each visualization." }, { "code": null, "e": 34678, "s": 34014, "text": "trace1 = go.Bar( x = merged_portfolio_sp_latest_YTD_sp_closing_high['Ticker'][0:10], y = merged_portfolio_sp_latest_YTD_sp_closing_high['ticker return'][0:10], name = 'Ticker Total Return')trace2 = go.Scatter( x = merged_portfolio_sp_latest_YTD_sp_closing_high['Ticker'][0:10], y = merged_portfolio_sp_latest_YTD_sp_closing_high['SP Return'][0:10], name = 'SP500 Total Return') data = [trace1, trace2]layout = go.Layout(title = 'Total Return vs S&P 500' , barmode = 'group' , yaxis=dict(title='Returns', tickformat=\".2%\") , xaxis=dict(title='Ticker') , legend=dict(x=.8,y=1) )fig = go.Figure(data=data, layout=layout)iplot(fig)" }, { "code": null, "e": 34895, "s": 34678, "text": "When using Plotly, you create traces which will plot the x and y data you specify. Here, you specify in trace1 that you want to plot a bar chart, with each Ticker on the x-axis and each ticker’s return on the y-axis." }, { "code": null, "e": 35028, "s": 34895, "text": "In trace2, to break up the data a bit, we’ll use a Scatter line chart for the Ticker on the x-axis and the S&P Return on the y-axis." }, { "code": null, "e": 35128, "s": 35028, "text": "Where the bar is above the line, the individual ticker (6 of 8 times) has outperformed the S&P 500." }, { "code": null, "e": 35400, "s": 35128, "text": "You then create a data object with these traces, and then you provide a layout for the chart; in this case you specify a title, barmode, and the position of the legend; you also pass in a title and tick format (percent format to two decimal places) for the y-axis series." }, { "code": null, "e": 35533, "s": 35400, "text": "You then create a figure object using go.Figure, specifying the data and layout objects, which you previously named data and layout." }, { "code": null, "e": 36141, "s": 35533, "text": "The next chart below shows the gain / (loss) dollar amount for each position, relative to the S&P 500, as well as shows the Ticker Total Return %. While it is generally recommended that you allocate an equal position size to your positions (or potentially determine positition sizing based on implied volatility), this may not always be the case. For a less volatile investment, you may invest more than in a riskier position (or you may have other position sizing rules). Given this, this visualization shows both each position’s return and the dollar value contribution to your overall portfolio’s return." }, { "code": null, "e": 36396, "s": 36141, "text": "Here, you can see that although you invested slightly less in Facebook (FB) than other positions, this stock has returned an ~$20k in this mock portfolio, greater than a 4x return relative to an equivalent S&P 500 investment over the same holding period." }, { "code": null, "e": 36549, "s": 36396, "text": "The next chart below leverages the cumulative columns which you created: 'Cum Invst', 'Cum SP Returns', 'Cum Ticker Returns', and 'Cum Ticker ROI Mult'." }, { "code": null, "e": 36774, "s": 36549, "text": "Across the x-axis you have sorted the portfolio alphabetically. Each position shows the initial investment and total value (investment plus returns or less losses) for that position, combined with the positions preceding it." }, { "code": null, "e": 37020, "s": 36774, "text": "To explain further, based on the ~$8k investment in AAPL, this grew to ~$22.5k (>$14k in gains), versus $15k in total value for the S&P. This is a 2.75x return over the initial investment in AAPL ($22.5k value from $8k investment is ~2.75x ROI)." }, { "code": null, "e": 37222, "s": 37020, "text": "Continuing to FB, you have invested ~$16k in aggregate ($8k in both positions), and this has grown to over $50k, a greater than 3x total return — this means that FB expanded your overall portfolio ROI." }, { "code": null, "e": 37462, "s": 37222, "text": "Further down the x-axis, you see that both TWTR and WMT have reduced the overall portfolio ROI — this is obvious, as both have underperformed the S&P, but I believe that the magnitude of the contribution is clearer with this visualization." }, { "code": null, "e": 37890, "s": 37462, "text": "As a caveat, this cumulative approach, given the different holding periods, is a bit of an apples and oranges combination for some positions based on when they were acquired. However, you can always isolate this analysis by sub-setting into smaller dataframes and separately compare positions which have more consistent holding periods. For example, you could compare your 2H 2016 and 1H 2017 purchases separate of one another." }, { "code": null, "e": 38089, "s": 37890, "text": "Your final chart compares how far off each position’s latest close price is from its adjusted closing high since the position was purchased. This is generally an important visualization to consider:" }, { "code": null, "e": 38229, "s": 38089, "text": "When a stock closes at higher prices, it’s generally recommended to adjust your trailing stop up as well. To illustrate, here’s an example:" }, { "code": null, "e": 38412, "s": 38229, "text": "A position is acquired at $10 and doubles to $20 — using a 25% trailing stop, you would want to consider selling this position the next day if it closed at $15 ($15 / $20–1 = (25%))." }, { "code": null, "e": 38538, "s": 38412, "text": "If the position increased to $25, you would want to consider moving your trailing stop up to $18.75 ($18.75 / $25–1 = (25%))." }, { "code": null, "e": 38717, "s": 38538, "text": "As mentioned early on, nothing in here is intended to be financial advice; different trading systems have different rules for trailing stops, and this is an illustrative example." }, { "code": null, "e": 39040, "s": 38717, "text": "Trailing stops are meant to help preserve gains and are generally important in mitigating the emotions of investing; while it’s easy to see your position’s current return, what tends to be manual (or somewhat expensive if you use a trailing stop service) is calculating how close your positions are to your trailing stops." }, { "code": null, "e": 39248, "s": 39040, "text": "This final visualization makes this easy to evaluate for any date you are reviewing; in the chart, we see that AAPL, MTCH, and NFLX all closed on 3/9/2018 at their closing highs (typically a very good sign)." }, { "code": null, "e": 39374, "s": 39248, "text": "However, TWTR is greater than 25% below its highest close (33% below as of 3/9/2018) and WMT is ~20% below its highest close." }, { "code": null, "e": 39476, "s": 39374, "text": "In this case, you might want to sell TWTR and continue to keep a close eye on the performance of WMT." }, { "code": null, "e": 39678, "s": 39476, "text": "Now you have a relatively extensible Jupyter notebook and portfolio dataset, which you are able to use to evaluate your stock portfolio, as well as add in new metrics and visualizations as you see fit." }, { "code": null, "e": 39922, "s": 39678, "text": "Please note that while this notebook provides a fairly thorough review of a portfolio, the below have not yet been taken into consideration, would have an impact on the overall comparison, and likely present great areas for future development:" }, { "code": null, "e": 40174, "s": 39922, "text": "As noted initially, this notebook focuses on active holdings — ideally, we would evaluate all positions, both exited and active, in order to have a truly holistic view on one’s investment strategy relative to alternatives, such as an index comparison." }, { "code": null, "e": 40490, "s": 40174, "text": "The approach in here does not factor in dividends; while we evaluate adjusted close prices (which reflect dividends), total shareholder return combines share price appreciation and dividends to show a stock’s total return; while this is more difficult to do, it is something I’m evaluating to include in the future." }, { "code": null, "e": 40863, "s": 40490, "text": "On a related note, investors can also reinvest dividends in a position, rather than take a cash distribution; this is arguably even more complicated than accounting for dividends, as the acquisition costs are low and spread out, and over several years of holding a position you could have four (or more) acquisition dates each year for stocks where you reinvest dividends." }, { "code": null, "e": 41639, "s": 40863, "text": "With those future areas in mind, we accomplished a lot here; this includes importing S&P 500 and ticker data using Yahoo! Finance’s API and creating a master dataframe which combines your portfolio with historical ticker and comparative S&P 500 prices. In doing this, you are able to calculate the absolute percent and dollar value returns for each position (and as compared to equally timed S&P 500 investments), as well as the cumulative impact of each position on your overall portfolio’s performance. You can also dynamically monitor your trailing stops, based on your own trading rules. And you have created visualizations which allow you to have much better insight into your master dataframe, focusing on the different metrics and each position’s contribution to each." } ]
Count consecutive pairs of same elements - GeeksforGeeks
03 Jun, 2021 Given an array arr[], the task is to count the number of pairs formed by consecutive elements in which both of the elements in a pair are same.Examples: Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 5, 5, 5} Output: 5 (1, 2), (4, 5), (6, 7), (7, 8) and (8, 9) are the valid index pairs where consecutive elements are equal.Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 0 No two consecutive elements in the given array are equal. Approach: Initialize count = 0 and traverse the array from arr[0] to arr[n – 2]. If the current element is equal to the next element in the array then increment the count. Print the count in the end.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the count of consecutive// elements in the array which are equalint countCon(int ar[], int n){ int cnt = 0; for (int i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt;} // Driver codeint main(){ int ar[] = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; int n = sizeof(ar) / sizeof(ar[0]); cout << countCon(ar, n); return 0;} // Java implementation of the approachpublic class GfG{ // Function to return the count of consecutive // elements in the array which are equal static int countCon(int ar[], int n) { int cnt = 0; for (int i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt; } // Driver Code public static void main(String []args){ int ar[] = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; int n = ar.length; System.out.println(countCon(ar, n)); }} // This code is contributed by Rituraj Jain # Python3 implementation of the approach # Function to return the count of consecutive# elements in the array which are equaldef countCon(ar, n): cnt = 0 for i in range(n - 1): # If consecutive elements are same if (ar[i] == ar[i + 1]): cnt += 1 return cnt # Driver codear = [1, 2, 2, 3, 4, 4, 5, 5, 5, 5]n = len(ar)print(countCon(ar, n)) # This code is contributed by mohit kumar // C# implementation of the approachusing System; class GfG{ // Function to return the count of consecutive // elements in the array which are equal static int countCon(int[] ar, int n) { int cnt = 0; for (int i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt; } // Driver Code public static void Main() { int[] ar = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; int n = ar.Length; Console.WriteLine(countCon(ar, n)); }} // This code is contributed by Code_Mech. <?php// PHP implementation of the approach // Function to return the count of consecutive// elements in the array which are equalfunction countCon($ar, $n){ $cnt = 0; for ($i = 0; $i < $n - 1; $i++) { // If consecutive elements are same if ($ar[$i] == $ar[$i + 1]) $cnt++; } return $cnt;} // Driver code$ar = array(1, 2, 2, 3, 4, 4, 5, 5, 5, 5);$n = sizeof($ar);echo countCon($ar, $n); // This code is contributed// by Akanksha Rai?> <script>// Javascript implementation of the approach // Function to return the count of consecutive // elements in the array which are equal function countCon(ar,n) { let cnt = 0; for (let i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt; } // Driver Code let ar = [1, 2, 2, 3, 4, 4, 5, 5, 5, 5 ]; let n = ar.length; document.write(countCon(ar, n)); // This code is contributed by unknown2108</script> 5 mohit kumar 29 rituraj_jain Akanksha_Rai Code_Mech unknown2108 Constructive Algorithms Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 24501, "s": 24473, "text": "\n03 Jun, 2021" }, { "code": null, "e": 24656, "s": 24501, "text": "Given an array arr[], the task is to count the number of pairs formed by consecutive elements in which both of the elements in a pair are same.Examples: " }, { "code": null, "e": 24934, "s": 24656, "text": "Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 5, 5, 5} Output: 5 (1, 2), (4, 5), (6, 7), (7, 8) and (8, 9) are the valid index pairs where consecutive elements are equal.Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 0 No two consecutive elements in the given array are equal. " }, { "code": null, "e": 25188, "s": 24936, "text": "Approach: Initialize count = 0 and traverse the array from arr[0] to arr[n – 2]. If the current element is equal to the next element in the array then increment the count. Print the count in the end.Below is the implementation of the above approach: " }, { "code": null, "e": 25192, "s": 25188, "text": "C++" }, { "code": null, "e": 25197, "s": 25192, "text": "Java" }, { "code": null, "e": 25205, "s": 25197, "text": "Python3" }, { "code": null, "e": 25208, "s": 25205, "text": "C#" }, { "code": null, "e": 25212, "s": 25208, "text": "PHP" }, { "code": null, "e": 25223, "s": 25212, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the count of consecutive// elements in the array which are equalint countCon(int ar[], int n){ int cnt = 0; for (int i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt;} // Driver codeint main(){ int ar[] = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; int n = sizeof(ar) / sizeof(ar[0]); cout << countCon(ar, n); return 0;}", "e": 25741, "s": 25223, "text": null }, { "code": "// Java implementation of the approachpublic class GfG{ // Function to return the count of consecutive // elements in the array which are equal static int countCon(int ar[], int n) { int cnt = 0; for (int i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt; } // Driver Code public static void main(String []args){ int ar[] = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; int n = ar.length; System.out.println(countCon(ar, n)); }} // This code is contributed by Rituraj Jain", "e": 26399, "s": 25741, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of consecutive# elements in the array which are equaldef countCon(ar, n): cnt = 0 for i in range(n - 1): # If consecutive elements are same if (ar[i] == ar[i + 1]): cnt += 1 return cnt # Driver codear = [1, 2, 2, 3, 4, 4, 5, 5, 5, 5]n = len(ar)print(countCon(ar, n)) # This code is contributed by mohit kumar", "e": 26826, "s": 26399, "text": null }, { "code": "// C# implementation of the approachusing System; class GfG{ // Function to return the count of consecutive // elements in the array which are equal static int countCon(int[] ar, int n) { int cnt = 0; for (int i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt; } // Driver Code public static void Main() { int[] ar = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 }; int n = ar.Length; Console.WriteLine(countCon(ar, n)); }} // This code is contributed by Code_Mech.", "e": 27477, "s": 26826, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of consecutive// elements in the array which are equalfunction countCon($ar, $n){ $cnt = 0; for ($i = 0; $i < $n - 1; $i++) { // If consecutive elements are same if ($ar[$i] == $ar[$i + 1]) $cnt++; } return $cnt;} // Driver code$ar = array(1, 2, 2, 3, 4, 4, 5, 5, 5, 5);$n = sizeof($ar);echo countCon($ar, $n); // This code is contributed// by Akanksha Rai?>", "e": 27953, "s": 27477, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the count of consecutive // elements in the array which are equal function countCon(ar,n) { let cnt = 0; for (let i = 0; i < n - 1; i++) { // If consecutive elements are same if (ar[i] == ar[i + 1]) cnt++; } return cnt; } // Driver Code let ar = [1, 2, 2, 3, 4, 4, 5, 5, 5, 5 ]; let n = ar.length; document.write(countCon(ar, n)); // This code is contributed by unknown2108</script>", "e": 28530, "s": 27953, "text": null }, { "code": null, "e": 28532, "s": 28530, "text": "5" }, { "code": null, "e": 28549, "s": 28534, "text": "mohit kumar 29" }, { "code": null, "e": 28562, "s": 28549, "text": "rituraj_jain" }, { "code": null, "e": 28575, "s": 28562, "text": "Akanksha_Rai" }, { "code": null, "e": 28585, "s": 28575, "text": "Code_Mech" }, { "code": null, "e": 28597, "s": 28585, "text": "unknown2108" }, { "code": null, "e": 28621, "s": 28597, "text": "Constructive Algorithms" }, { "code": null, "e": 28628, "s": 28621, "text": "Arrays" }, { "code": null, "e": 28641, "s": 28628, "text": "Mathematical" }, { "code": null, "e": 28648, "s": 28641, "text": "Arrays" }, { "code": null, "e": 28661, "s": 28648, "text": "Mathematical" }, { "code": null, "e": 28759, "s": 28661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28768, "s": 28759, "text": "Comments" }, { "code": null, "e": 28781, "s": 28768, "text": "Old Comments" }, { "code": null, "e": 28829, "s": 28781, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 28873, "s": 28829, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 28896, "s": 28873, "text": "Introduction to Arrays" }, { "code": null, "e": 28928, "s": 28896, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28942, "s": 28928, "text": "Linear Search" }, { "code": null, "e": 29002, "s": 28942, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29017, "s": 29002, "text": "C++ Data Types" }, { "code": null, "e": 29060, "s": 29017, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 29084, "s": 29060, "text": "Merge two sorted arrays" } ]
Program to find the Hidden Number
25 May, 2022 Given an array of integers, The task is to find another integer such that, if all the elements of the array are subtracted individually from the number , then the sum of all the differences should add to 0. If any such integer exists, print the value of , else print . Example Input: arr[] = {1, 2, 3} Output: 2 Explanation: Subtracting all the elements of arrays from 2, The sum of difference is: 1 + 0 + (-1) = 0. Solution: The idea is to calculate the total sum of the array and divide it by the size of the array. If the sum of the array is perfectly divisible by its size then the quotient obtained from this division operation will be the required hidden number.Below is the implementation of the above idea: C++ Java Python 3 C# PHP Javascript // C++ Program to find the// hidden number #include <iostream>using namespace std; // Driver Code int main() { // Getting the size of array int n = 3; // Getting the array of size n int a[] = { 1, 2, 3 }; // Solution int i = 0; // Finding sum of the array elements long sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n long x = sum / n; // Print x, if found if (x * n == sum) cout<<x<<endl; else cout<<("-1")<<endl; return 0; // This code is contributed// by shashank} // Java Program to find the// hidden number public class GFG { // Driver Code public static void main(String args[]) { // Getting the size of array int n = 3; // Getting the array of size n int a[] = { 1, 2, 3 }; // Solution int i = 0; // Finding sum of the array elements long sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n long x = sum / n; // Print x, if found if (x * n == sum) System.out.println(x); else System.out.println("-1"); }} # Python 3 Program to find the# hidden number # Driver Codeif __name__ == "__main__": # Getting the size of array n = 3 # Getting the array of size n a = [ 1, 2, 3 ] # Solution i = 0 # Finding sum of the . # array elements sum = 0 for i in range(n): sum += a[i] # Dividing sum by size n x = sum // n # Print x, if found if (x * n == sum): print(x) else: print("-1") # This code is contributed# by ChitraNayal // C# Program to find the// hidden numberusing System; class GFG{ // Driver Codepublic static void Main(){ // Getting the size of array int n = 3; // Getting the array of size n int []a = { 1, 2, 3 }; // Solution int i = 0; // Finding sum of the // array elements long sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n long x = sum / n; // Print x, if found if (x * n == sum) Console.WriteLine(x); else Console.WriteLine("-1");}} // This code is contributed// by inder_verma <?php// PHP Program to find the// hidden number // Driver Code // Getting the size of array$n = 3; // Getting the array of size n$a = array( 1, 2, 3 ); // Solution$i = 0; // Finding sum of the array elements$sum = 0;for ($i = 0; $i < $n; $i++){ $sum += $a[$i];} // Dividing sum by size n$x = $sum / $n; // Print x, if foundif ($x * $n == $sum)echo($x);elseecho("-1"); // This code is contributed// by inder_verma?> <script> // JavaScript Program to find the// hidden number // Driver Code // Getting the size of array let n = 3; // Getting the array of size n let a=[1, 2, 3]; // Solution let i = 0; // Finding sum of the array elements let sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n let x = sum / n; // Print x, if found if (x * n == sum) document.write(x); else document.write("-1"); // This code is contributed by rag2127 </script> 2 Time Complexity: O(n), where n is the length of the given array. Auxiliary space: O(1) inderDuMCA Shashank12 ukasp april14 rag2127 sweetyty shivamanandrj9 Constructive Algorithms Technical Scripter 2018 Arrays Mathematical Technical Scripter Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 331, "s": 52, "text": "Given an array of integers, The task is to find another integer such that, if all the elements of the array are subtracted individually from the number , then the sum of all the differences should add to 0. If any such integer exists, print the value of , else print . Example " }, { "code": null, "e": 471, "s": 331, "text": "Input: arr[] = {1, 2, 3}\nOutput: 2\nExplanation: \nSubtracting all the elements of arrays from 2,\nThe sum of difference is:\n1 + 0 + (-1) = 0." }, { "code": null, "e": 774, "s": 473, "text": "Solution: The idea is to calculate the total sum of the array and divide it by the size of the array. If the sum of the array is perfectly divisible by its size then the quotient obtained from this division operation will be the required hidden number.Below is the implementation of the above idea: " }, { "code": null, "e": 778, "s": 774, "text": "C++" }, { "code": null, "e": 783, "s": 778, "text": "Java" }, { "code": null, "e": 792, "s": 783, "text": "Python 3" }, { "code": null, "e": 795, "s": 792, "text": "C#" }, { "code": null, "e": 799, "s": 795, "text": "PHP" }, { "code": null, "e": 810, "s": 799, "text": "Javascript" }, { "code": "// C++ Program to find the// hidden number #include <iostream>using namespace std; // Driver Code int main() { // Getting the size of array int n = 3; // Getting the array of size n int a[] = { 1, 2, 3 }; // Solution int i = 0; // Finding sum of the array elements long sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n long x = sum / n; // Print x, if found if (x * n == sum) cout<<x<<endl; else cout<<(\"-1\")<<endl; return 0; // This code is contributed// by shashank}", "e": 1465, "s": 810, "text": null }, { "code": "// Java Program to find the// hidden number public class GFG { // Driver Code public static void main(String args[]) { // Getting the size of array int n = 3; // Getting the array of size n int a[] = { 1, 2, 3 }; // Solution int i = 0; // Finding sum of the array elements long sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n long x = sum / n; // Print x, if found if (x * n == sum) System.out.println(x); else System.out.println(\"-1\"); }}", "e": 2090, "s": 1465, "text": null }, { "code": "# Python 3 Program to find the# hidden number # Driver Codeif __name__ == \"__main__\": # Getting the size of array n = 3 # Getting the array of size n a = [ 1, 2, 3 ] # Solution i = 0 # Finding sum of the . # array elements sum = 0 for i in range(n): sum += a[i] # Dividing sum by size n x = sum // n # Print x, if found if (x * n == sum): print(x) else: print(\"-1\") # This code is contributed# by ChitraNayal", "e": 2575, "s": 2090, "text": null }, { "code": "// C# Program to find the// hidden numberusing System; class GFG{ // Driver Codepublic static void Main(){ // Getting the size of array int n = 3; // Getting the array of size n int []a = { 1, 2, 3 }; // Solution int i = 0; // Finding sum of the // array elements long sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n long x = sum / n; // Print x, if found if (x * n == sum) Console.WriteLine(x); else Console.WriteLine(\"-1\");}} // This code is contributed// by inder_verma", "e": 3154, "s": 2575, "text": null }, { "code": "<?php// PHP Program to find the// hidden number // Driver Code // Getting the size of array$n = 3; // Getting the array of size n$a = array( 1, 2, 3 ); // Solution$i = 0; // Finding sum of the array elements$sum = 0;for ($i = 0; $i < $n; $i++){ $sum += $a[$i];} // Dividing sum by size n$x = $sum / $n; // Print x, if foundif ($x * $n == $sum)echo($x);elseecho(\"-1\"); // This code is contributed// by inder_verma?>", "e": 3572, "s": 3154, "text": null }, { "code": "<script> // JavaScript Program to find the// hidden number // Driver Code // Getting the size of array let n = 3; // Getting the array of size n let a=[1, 2, 3]; // Solution let i = 0; // Finding sum of the array elements let sum = 0; for (i = 0; i < n; i++) { sum += a[i]; } // Dividing sum by size n let x = sum / n; // Print x, if found if (x * n == sum) document.write(x); else document.write(\"-1\"); // This code is contributed by rag2127 </script>", "e": 4152, "s": 3572, "text": null }, { "code": null, "e": 4154, "s": 4152, "text": "2" }, { "code": null, "e": 4243, "s": 4156, "text": "Time Complexity: O(n), where n is the length of the given array. Auxiliary space: O(1)" }, { "code": null, "e": 4254, "s": 4243, "text": "inderDuMCA" }, { "code": null, "e": 4265, "s": 4254, "text": "Shashank12" }, { "code": null, "e": 4271, "s": 4265, "text": "ukasp" }, { "code": null, "e": 4279, "s": 4271, "text": "april14" }, { "code": null, "e": 4287, "s": 4279, "text": "rag2127" }, { "code": null, "e": 4296, "s": 4287, "text": "sweetyty" }, { "code": null, "e": 4311, "s": 4296, "text": "shivamanandrj9" }, { "code": null, "e": 4335, "s": 4311, "text": "Constructive Algorithms" }, { "code": null, "e": 4359, "s": 4335, "text": "Technical Scripter 2018" }, { "code": null, "e": 4366, "s": 4359, "text": "Arrays" }, { "code": null, "e": 4379, "s": 4366, "text": "Mathematical" }, { "code": null, "e": 4398, "s": 4379, "text": "Technical Scripter" }, { "code": null, "e": 4405, "s": 4398, "text": "Arrays" }, { "code": null, "e": 4418, "s": 4405, "text": "Mathematical" } ]
Turn an Array into a Column Vector in MATLAB
04 Jul, 2021 Conversion of an Array into a Column Vector. This conversion can be done using a(:) operation. A(:) reshapes all elements of A into a single column vector. This has no effect if A is already a column vector. Example 1 Matlab % MATLAB code for Conversion of an array % into a column vectora = [2 4 6 8] % Initializing an array of some elements % Converting above array into a column % vector using a(:) operationColumn_Vector = a(:) Output: Example 2 Matlab % MATLAB code for Conversion of an % array matrix into a column vector.a = [1 2; 3 4; 5 6] % Initializing an array % Converting above array matrix into a column % vector matrix using a(:) operationColumn_Vector_matrix = a(:) Output: MATLAB MATLAB-programs Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2021" }, { "code": null, "e": 237, "s": 28, "text": " Conversion of an Array into a Column Vector. This conversion can be done using a(:) operation. A(:) reshapes all elements of A into a single column vector. This has no effect if A is already a column vector." }, { "code": null, "e": 248, "s": 237, "text": "Example 1 " }, { "code": null, "e": 255, "s": 248, "text": "Matlab" }, { "code": "% MATLAB code for Conversion of an array % into a column vectora = [2 4 6 8] % Initializing an array of some elements % Converting above array into a column % vector using a(:) operationColumn_Vector = a(:)", "e": 463, "s": 255, "text": null }, { "code": null, "e": 471, "s": 463, "text": "Output:" }, { "code": null, "e": 481, "s": 471, "text": "Example 2" }, { "code": null, "e": 488, "s": 481, "text": "Matlab" }, { "code": "% MATLAB code for Conversion of an % array matrix into a column vector.a = [1 2; 3 4; 5 6] % Initializing an array % Converting above array matrix into a column % vector matrix using a(:) operationColumn_Vector_matrix = a(:)", "e": 714, "s": 488, "text": null }, { "code": null, "e": 722, "s": 714, "text": "Output:" }, { "code": null, "e": 729, "s": 722, "text": "MATLAB" }, { "code": null, "e": 745, "s": 729, "text": "MATLAB-programs" }, { "code": null, "e": 752, "s": 745, "text": "Picked" }, { "code": null, "e": 759, "s": 752, "text": "MATLAB" } ]
Count pairs in array such that one element is reverse of another
03 Jun, 2021 Given an array arr[], the task is to count the pairs in the array such that the elements are the reverse of each other. Examples: Input: arr[] = { 16, 61, 12, 21, 25 } Output: 2 Explanation: The 2 pairs such that one number is the reverse of the other are {16, 61} and {12, 21}. Input: arr[] = {10, 11, 12} Output: 0 Approach: The idea is to use nested loops to get all the possible pairs of numbers in the array. Then, for each pair, check whether an element is a reverse of another. If it is, then increase the required count by one. When all the pairs have been checked, they return or print the count of such pairs. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count the pairs in array// such that one element is reverse of another#include <bits/stdc++.h>using namespace std; // Function to reverse the digits// of the numberint reverse(int num){ int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs from the array// such that one number is reverse of// the otherint countReverse(int arr[], int n){ int res = 0; // Iterate through all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res;} // Driver codeint main(){ int a[] = { 16, 61, 12, 21, 25 }; int n = sizeof(a) / sizeof(a[0]); cout << countReverse(a, n); return 0;} // Java program to count the pairs in array// such that one element is reverse of another class Geeks { // Function to reverse the digits // of the number static int reverse(int num) { int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Function to find the pairs from the // such that one number is reverse of // the other static int countReverse(int arr[], int n) { int res = 0; // Iterate through all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res; } // Driver code public static void main(String[] args) { int a[] = { 16, 61, 12, 21, 25 }; int n = a.length; System.out.print(countReverse(a, n)); }} // This code is contributed by Rajnis09 # Python3 program to count the pairs in array# such that one element is reverse of another # Function to reverse the digits# of the numberdef reverse(num): rev_num = 0 # Loop to iterate till the number is # greater than 0 while (num > 0): # Extract the last digit and keep # multiplying it by 10 to get the # reverse of the number rev_num = rev_num * 10 + num % 10 num = num // 10 return rev_num # Function to find the pairs from the# such that one number is reverse of# the otherdef countReverse(arr,n): res = 0 # Iterate through all pairs for i in range(n): for j in range(i + 1, n): # Increment count if one is # the reverse of other if (reverse(arr[i]) == arr[j]): res += 1 return res # Driver codeif __name__ == '__main__': a = [16, 61, 12, 21, 25] n = len(a) print(countReverse(a, n)) # This code is contributed by Surendra_Gangwar // C# program to count the pairs in array// such that one element is reverse of anotherusing System; class GFG{ // Function to reverse the digits// of the numberstatic int reverse(int num){ int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs from the// such that one number is reverse of// the otherstatic int countReverse(int []arr, int n){ int res = 0; // Iterate through all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res;} // Driver codepublic static void Main(String []arr){ int []a = { 16, 61, 12, 21, 25 }; int n = a.Length; Console.Write(countReverse(a, n));}} // This code is contributed by shivanisinghss2110 <script> // Javascript program to count the pairs in array// such that one element is reverse of another // Function to reverse the digits// of the numberfunction reverse(num){ var rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = parseInt(num / 10); } return rev_num;} // Function to find the pairs from the array// such that one number is reverse of// the otherfunction countReverse(arr, n){ var res = 0; // Iterate through all pairs for (var i = 0; i < n; i++) for (var j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res;} // Driver codevar a = [ 16, 61, 12, 21, 25 ];var n = a.length;document.write( countReverse(a, n)); // This code is contributed by noob2000.</script> 2 Time Complexity: O(N2) Auxiliary Space: O(1) We can observe that the most expensive operation here is searching for the reversed element in the array(which takes O(N)). By using a hash map, this can be reduced to O(1). Approach: The idea is to store all the elements of the array in the hash map(by increasing the frequency of the present element to tackle the problem of duplicates) and check how many times the reversed element is repeated and increase the count by that frequency. To avoid recounting the number when it is a palindrome or when we visit its reverse, we need to delete the present number from the hash map(this is achieved by decreasing the frequency of that number). C++ Java Python3 C# Javascript // C++ program to count the pairs in array// such that one element is reverse of another#include <bits/stdc++.h>using namespace std; // Function to reverse the digits// of the numberint reverse(int num){ int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs from the array// such that one number is reverse of// the otherint countReverse(int arr[], int n){ unordered_map<int, int> freq; // Iterate over every element in the array // and increase the frequency of the element // in hash map for(int i = 0; i < n; ++i) ++freq[arr[i]]; int res = 0; // Iterate over every element in the array for (int i = 0; i < n; i++){ // remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse --freq[arr[i]]; // Increment the count // by the frequency of // reverse of the number res += freq[reverse(arr[i])]; } return res;} // Driver codeint main() { int a[] = { 16, 61, 12, 21, 25 }; int n = sizeof(a) / sizeof(a[0]); cout << countReverse(a, n) << '\n'; return 0;} // Java program to count the// pairs in array such that// one element is reverse of// anotherimport java.util.*;class GFG{ // Function to reverse the digits// of the numberpublic static int reverse(int num){ int rev_num = 0; // Loop to iterate till // the number is greater // than 0 while (num > 0) { // Extract the last digit // and keep multiplying it // by 10 to get the reverse // of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs// from the array such that// one number is reverse of the// otherpublic static int countReverse(int arr[], int n){ HashMap<Integer, Integer> freq = new HashMap<>(); // Iterate over every element // in the array and increase // the frequency of the element // in hash map for(int i = 0; i < n; ++i) { if(freq.containsKey(arr[i])) { freq.replace(arr[i], freq.get(arr[i]) + 1); } else { freq.put(arr[i], 1); } } int res = 0; // Iterate over every element // in the array for (int i = 0; i < n; i++) { // remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse if(freq.containsKey(arr[i])) { freq.replace(arr[i], freq.get(arr[i]) - 1); } else { freq.put(arr[i], -1); } // Increment the count // by the frequency of // reverse of the number if(freq.containsKey(reverse(arr[i]))) { res += freq.get(reverse(arr[i])); } } return res;} // Driver code public static void main(String[] args){ int a[] = {16, 61, 12, 21, 25}; int n = a.length; System.out.println(countReverse(a, n));}} // This code is contributed by divyeshrabadiya07 # Python3 program to count# the pairs in array such# that one element is reverse# of anotherfrom collections import defaultdict # Function to reverse# the digits of the numberdef reverse(num): rev_num = 0 # Loop to iterate till # the number is greater than 0 while (num > 0): # Extract the last digit and keep # multiplying it by 10 to get the # reverse of the number rev_num = rev_num * 10 + num % 10 num = num // 10 return rev_num # Function to find the pairs# from the array such that# one number is reverse of# the otherdef countReverse(arr, n): freq = defaultdict (int) # Iterate over every element # in the array and increase # the frequency of the element # in hash map for i in range (n): freq[arr[i]] += 1 res = 0 # Iterate over every # element in the array for i in range (n): # remove the current element from # the hash map by decreasing the # frequency to avoid counting # when the number is a palindrome # or when we visit its reverse freq[arr[i]] -= 1 # Increment the count # by the frequency of # reverse of the number res += freq[reverse(arr[i])] return res # Driver codeif __name__ == "__main__": a = [16, 61, 12, 21, 25] n = len(a) print (countReverse(a, n)) # This code is contributed by Chitranayal // C# program to count the// pairs in array such that// one element is reverse of// anotherusing System;using System.Collections.Generic; class GFG{ // Function to reverse the digits// of the numberstatic int reverse(int num){ int rev_num = 0; // Loop to iterate till // the number is greater // than 0 while (num > 0) { // Extract the last digit // and keep multiplying it // by 10 to get the reverse // of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs// from the array such that// one number is reverse of the// otherstatic int countReverse(int[] arr, int n){ Dictionary<int, int> freq = new Dictionary<int, int>(); // Iterate over every element // in the array and increase // the frequency of the element // in hash map for(int i = 0; i < n; ++i) { if (freq.ContainsKey(arr[i])) { freq[arr[i]]++; } else { freq.Add(arr[i], 1); } } int res = 0; // Iterate over every element // in the array for(int i = 0; i < n; i++) { // Remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse if (freq.ContainsKey(arr[i])) { freq[arr[i]]--; } else { freq.Add(arr[i], -1); } // Increment the count // by the frequency of // reverse of the number if (freq.ContainsKey(reverse(arr[i]))) { res += freq[reverse(arr[i])]; } } return res;} // Driver code static void Main(){ int[] a = { 16, 61, 12, 21, 25 }; int n = a.Length; Console.WriteLine(countReverse(a, n));}} // This code is contributed by divyesh072019 <script>// Javascript program to count the// pairs in array such that// one element is reverse of// another // Function to reverse the digits// of the numberfunction reverse(num){ let rev_num = 0; // Loop to iterate till // the number is greater // than 0 while (num > 0) { // Extract the last digit // and keep multiplying it // by 10 to get the reverse // of the number rev_num = rev_num * 10 + num % 10; num = Math.floor(num / 10); } return rev_num;} // Function to find the pairs// from the array such that// one number is reverse of the// otherfunction countReverse(arr,n){ let freq = new Map(); // Iterate over every element // in the array and increase // the frequency of the element // in hash map for(let i = 0; i < n; ++i) { if(freq.has(arr[i])) { freq.set(arr[i], freq.get(arr[i]) + 1); } else { freq.set(arr[i], 1); } } let res = 0; // Iterate over every element // in the array for (let i = 0; i < n; i++) { // remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse if(freq.has(arr[i])) { freq.set(arr[i], freq.get(arr[i]) - 1); } else { freq.set(arr[i], -1); } // Increment the count // by the frequency of // reverse of the number if(freq.has(reverse(arr[i]))) { res += freq.get(reverse(arr[i])); } } return res;} // Driver code let a=[16, 61, 12, 21, 25];let n = a.length;document.write(countReverse(a, n)); // This code is contributed by avanitrachhadiya2155</script> 2 Time Complexity: O(N) Auxiliary Space: O(N) SURENDRA_GANGWAR Rajnis09 shivanisinghss2110 abhijeet_ar ukasp divyeshrabadiya07 divyesh072019 noob2000 avanitrachhadiya2155 Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jun, 2021" }, { "code": null, "e": 174, "s": 54, "text": "Given an array arr[], the task is to count the pairs in the array such that the elements are the reverse of each other." }, { "code": null, "e": 185, "s": 174, "text": "Examples: " }, { "code": null, "e": 334, "s": 185, "text": "Input: arr[] = { 16, 61, 12, 21, 25 } Output: 2 Explanation: The 2 pairs such that one number is the reverse of the other are {16, 61} and {12, 21}." }, { "code": null, "e": 374, "s": 334, "text": "Input: arr[] = {10, 11, 12} Output: 0 " }, { "code": null, "e": 678, "s": 374, "text": "Approach: The idea is to use nested loops to get all the possible pairs of numbers in the array. Then, for each pair, check whether an element is a reverse of another. If it is, then increase the required count by one. When all the pairs have been checked, they return or print the count of such pairs. " }, { "code": null, "e": 730, "s": 678, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 734, "s": 730, "text": "C++" }, { "code": null, "e": 739, "s": 734, "text": "Java" }, { "code": null, "e": 747, "s": 739, "text": "Python3" }, { "code": null, "e": 750, "s": 747, "text": "C#" }, { "code": null, "e": 761, "s": 750, "text": "Javascript" }, { "code": "// C++ program to count the pairs in array// such that one element is reverse of another#include <bits/stdc++.h>using namespace std; // Function to reverse the digits// of the numberint reverse(int num){ int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs from the array// such that one number is reverse of// the otherint countReverse(int arr[], int n){ int res = 0; // Iterate through all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res;} // Driver codeint main(){ int a[] = { 16, 61, 12, 21, 25 }; int n = sizeof(a) / sizeof(a[0]); cout << countReverse(a, n); return 0;}", "e": 1841, "s": 761, "text": null }, { "code": "// Java program to count the pairs in array// such that one element is reverse of another class Geeks { // Function to reverse the digits // of the number static int reverse(int num) { int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Function to find the pairs from the // such that one number is reverse of // the other static int countReverse(int arr[], int n) { int res = 0; // Iterate through all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res; } // Driver code public static void main(String[] args) { int a[] = { 16, 61, 12, 21, 25 }; int n = a.length; System.out.print(countReverse(a, n)); }} // This code is contributed by Rajnis09", "e": 3096, "s": 1841, "text": null }, { "code": "# Python3 program to count the pairs in array# such that one element is reverse of another # Function to reverse the digits# of the numberdef reverse(num): rev_num = 0 # Loop to iterate till the number is # greater than 0 while (num > 0): # Extract the last digit and keep # multiplying it by 10 to get the # reverse of the number rev_num = rev_num * 10 + num % 10 num = num // 10 return rev_num # Function to find the pairs from the# such that one number is reverse of# the otherdef countReverse(arr,n): res = 0 # Iterate through all pairs for i in range(n): for j in range(i + 1, n): # Increment count if one is # the reverse of other if (reverse(arr[i]) == arr[j]): res += 1 return res # Driver codeif __name__ == '__main__': a = [16, 61, 12, 21, 25] n = len(a) print(countReverse(a, n)) # This code is contributed by Surendra_Gangwar", "e": 4068, "s": 3096, "text": null }, { "code": "// C# program to count the pairs in array// such that one element is reverse of anotherusing System; class GFG{ // Function to reverse the digits// of the numberstatic int reverse(int num){ int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs from the// such that one number is reverse of// the otherstatic int countReverse(int []arr, int n){ int res = 0; // Iterate through all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res;} // Driver codepublic static void Main(String []arr){ int []a = { 16, 61, 12, 21, 25 }; int n = a.Length; Console.Write(countReverse(a, n));}} // This code is contributed by shivanisinghss2110", "e": 5200, "s": 4068, "text": null }, { "code": "<script> // Javascript program to count the pairs in array// such that one element is reverse of another // Function to reverse the digits// of the numberfunction reverse(num){ var rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = parseInt(num / 10); } return rev_num;} // Function to find the pairs from the array// such that one number is reverse of// the otherfunction countReverse(arr, n){ var res = 0; // Iterate through all pairs for (var i = 0; i < n; i++) for (var j = i + 1; j < n; j++) // Increment count if one is // the reverse of other if (reverse(arr[i]) == arr[j]) { res++; } return res;} // Driver codevar a = [ 16, 61, 12, 21, 25 ];var n = a.length;document.write( countReverse(a, n)); // This code is contributed by noob2000.</script>", "e": 6262, "s": 5200, "text": null }, { "code": null, "e": 6264, "s": 6262, "text": "2" }, { "code": null, "e": 6289, "s": 6266, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 6311, "s": 6289, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6486, "s": 6311, "text": "We can observe that the most expensive operation here is searching for the reversed element in the array(which takes O(N)). By using a hash map, this can be reduced to O(1). " }, { "code": null, "e": 6953, "s": 6486, "text": "Approach: The idea is to store all the elements of the array in the hash map(by increasing the frequency of the present element to tackle the problem of duplicates) and check how many times the reversed element is repeated and increase the count by that frequency. To avoid recounting the number when it is a palindrome or when we visit its reverse, we need to delete the present number from the hash map(this is achieved by decreasing the frequency of that number)." }, { "code": null, "e": 6957, "s": 6953, "text": "C++" }, { "code": null, "e": 6962, "s": 6957, "text": "Java" }, { "code": null, "e": 6970, "s": 6962, "text": "Python3" }, { "code": null, "e": 6973, "s": 6970, "text": "C#" }, { "code": null, "e": 6984, "s": 6973, "text": "Javascript" }, { "code": "// C++ program to count the pairs in array// such that one element is reverse of another#include <bits/stdc++.h>using namespace std; // Function to reverse the digits// of the numberint reverse(int num){ int rev_num = 0; // Loop to iterate till the number is // greater than 0 while (num > 0) { // Extract the last digit and keep // multiplying it by 10 to get the // reverse of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs from the array// such that one number is reverse of// the otherint countReverse(int arr[], int n){ unordered_map<int, int> freq; // Iterate over every element in the array // and increase the frequency of the element // in hash map for(int i = 0; i < n; ++i) ++freq[arr[i]]; int res = 0; // Iterate over every element in the array for (int i = 0; i < n; i++){ // remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse --freq[arr[i]]; // Increment the count // by the frequency of // reverse of the number res += freq[reverse(arr[i])]; } return res;} // Driver codeint main() { int a[] = { 16, 61, 12, 21, 25 }; int n = sizeof(a) / sizeof(a[0]); cout << countReverse(a, n) << '\\n'; return 0;}", "e": 8453, "s": 6984, "text": null }, { "code": "// Java program to count the// pairs in array such that// one element is reverse of// anotherimport java.util.*;class GFG{ // Function to reverse the digits// of the numberpublic static int reverse(int num){ int rev_num = 0; // Loop to iterate till // the number is greater // than 0 while (num > 0) { // Extract the last digit // and keep multiplying it // by 10 to get the reverse // of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs// from the array such that// one number is reverse of the// otherpublic static int countReverse(int arr[], int n){ HashMap<Integer, Integer> freq = new HashMap<>(); // Iterate over every element // in the array and increase // the frequency of the element // in hash map for(int i = 0; i < n; ++i) { if(freq.containsKey(arr[i])) { freq.replace(arr[i], freq.get(arr[i]) + 1); } else { freq.put(arr[i], 1); } } int res = 0; // Iterate over every element // in the array for (int i = 0; i < n; i++) { // remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse if(freq.containsKey(arr[i])) { freq.replace(arr[i], freq.get(arr[i]) - 1); } else { freq.put(arr[i], -1); } // Increment the count // by the frequency of // reverse of the number if(freq.containsKey(reverse(arr[i]))) { res += freq.get(reverse(arr[i])); } } return res;} // Driver code public static void main(String[] args){ int a[] = {16, 61, 12, 21, 25}; int n = a.length; System.out.println(countReverse(a, n));}} // This code is contributed by divyeshrabadiya07", "e": 10311, "s": 8453, "text": null }, { "code": "# Python3 program to count# the pairs in array such# that one element is reverse# of anotherfrom collections import defaultdict # Function to reverse# the digits of the numberdef reverse(num): rev_num = 0 # Loop to iterate till # the number is greater than 0 while (num > 0): # Extract the last digit and keep # multiplying it by 10 to get the # reverse of the number rev_num = rev_num * 10 + num % 10 num = num // 10 return rev_num # Function to find the pairs# from the array such that# one number is reverse of# the otherdef countReverse(arr, n): freq = defaultdict (int) # Iterate over every element # in the array and increase # the frequency of the element # in hash map for i in range (n): freq[arr[i]] += 1 res = 0 # Iterate over every # element in the array for i in range (n): # remove the current element from # the hash map by decreasing the # frequency to avoid counting # when the number is a palindrome # or when we visit its reverse freq[arr[i]] -= 1 # Increment the count # by the frequency of # reverse of the number res += freq[reverse(arr[i])] return res # Driver codeif __name__ == \"__main__\": a = [16, 61, 12, 21, 25] n = len(a) print (countReverse(a, n)) # This code is contributed by Chitranayal", "e": 11726, "s": 10311, "text": null }, { "code": "// C# program to count the// pairs in array such that// one element is reverse of// anotherusing System;using System.Collections.Generic; class GFG{ // Function to reverse the digits// of the numberstatic int reverse(int num){ int rev_num = 0; // Loop to iterate till // the number is greater // than 0 while (num > 0) { // Extract the last digit // and keep multiplying it // by 10 to get the reverse // of the number rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} // Function to find the pairs// from the array such that// one number is reverse of the// otherstatic int countReverse(int[] arr, int n){ Dictionary<int, int> freq = new Dictionary<int, int>(); // Iterate over every element // in the array and increase // the frequency of the element // in hash map for(int i = 0; i < n; ++i) { if (freq.ContainsKey(arr[i])) { freq[arr[i]]++; } else { freq.Add(arr[i], 1); } } int res = 0; // Iterate over every element // in the array for(int i = 0; i < n; i++) { // Remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse if (freq.ContainsKey(arr[i])) { freq[arr[i]]--; } else { freq.Add(arr[i], -1); } // Increment the count // by the frequency of // reverse of the number if (freq.ContainsKey(reverse(arr[i]))) { res += freq[reverse(arr[i])]; } } return res;} // Driver code static void Main(){ int[] a = { 16, 61, 12, 21, 25 }; int n = a.Length; Console.WriteLine(countReverse(a, n));}} // This code is contributed by divyesh072019", "e": 13769, "s": 11726, "text": null }, { "code": "<script>// Javascript program to count the// pairs in array such that// one element is reverse of// another // Function to reverse the digits// of the numberfunction reverse(num){ let rev_num = 0; // Loop to iterate till // the number is greater // than 0 while (num > 0) { // Extract the last digit // and keep multiplying it // by 10 to get the reverse // of the number rev_num = rev_num * 10 + num % 10; num = Math.floor(num / 10); } return rev_num;} // Function to find the pairs// from the array such that// one number is reverse of the// otherfunction countReverse(arr,n){ let freq = new Map(); // Iterate over every element // in the array and increase // the frequency of the element // in hash map for(let i = 0; i < n; ++i) { if(freq.has(arr[i])) { freq.set(arr[i], freq.get(arr[i]) + 1); } else { freq.set(arr[i], 1); } } let res = 0; // Iterate over every element // in the array for (let i = 0; i < n; i++) { // remove the current element from // the hash map by decreasing the // frequency to avoid counting // when the number is a palindrome // or when we visit its reverse if(freq.has(arr[i])) { freq.set(arr[i], freq.get(arr[i]) - 1); } else { freq.set(arr[i], -1); } // Increment the count // by the frequency of // reverse of the number if(freq.has(reverse(arr[i]))) { res += freq.get(reverse(arr[i])); } } return res;} // Driver code let a=[16, 61, 12, 21, 25];let n = a.length;document.write(countReverse(a, n)); // This code is contributed by avanitrachhadiya2155</script>", "e": 15683, "s": 13769, "text": null }, { "code": null, "e": 15685, "s": 15683, "text": "2" }, { "code": null, "e": 15707, "s": 15685, "text": "Time Complexity: O(N)" }, { "code": null, "e": 15729, "s": 15707, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 15746, "s": 15729, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 15755, "s": 15746, "text": "Rajnis09" }, { "code": null, "e": 15774, "s": 15755, "text": "shivanisinghss2110" }, { "code": null, "e": 15786, "s": 15774, "text": "abhijeet_ar" }, { "code": null, "e": 15792, "s": 15786, "text": "ukasp" }, { "code": null, "e": 15810, "s": 15792, "text": "divyeshrabadiya07" }, { "code": null, "e": 15824, "s": 15810, "text": "divyesh072019" }, { "code": null, "e": 15833, "s": 15824, "text": "noob2000" }, { "code": null, "e": 15854, "s": 15833, "text": "avanitrachhadiya2155" }, { "code": null, "e": 15861, "s": 15854, "text": "Arrays" }, { "code": null, "e": 15874, "s": 15861, "text": "Mathematical" }, { "code": null, "e": 15881, "s": 15874, "text": "Arrays" }, { "code": null, "e": 15894, "s": 15881, "text": "Mathematical" } ]
What is data type of FILE in C ?
26 May, 2022 Prerequisite : Basics of File Handling In C language, while file handling is done a word FILE is used. What is FILE? Example FILE *fp1, *fp2; While doing file handling we often use FILE for declaring the pointer in order to point to the file we want to read from or to write on. As we are declaring the pointer of type FILE so we can say it is data type, but what kind of data type? A FILE is a type of structure typedef as FILE. It is considered as opaque data type as its implementation is hidden. We don’t know what constitutes the type, we only use pointer to the type and library knows the internal of the type and can use the data. Definition of FILE is in stdio although it is system specific. Following is the definition of FILE in ubuntu struct _IO_FILE { int _flags; /* High-order word is _IO_MAGIC; rest is flags. */ #define _IO_file_flags _flags /* The following pointers correspond to the C++ streambuf protocol. */ /* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */ char* _IO_read_ptr; /* Current read pointer */ char* _IO_read_end; /* End of get area. */ char* _IO_read_base; /* Start of putback+get area. */ char* _IO_write_base; /* Start of put area. */ char* _IO_write_ptr; /* Current put pointer. */ char* _IO_write_end; /* End of put area. */ char* _IO_buf_base; /* Start of reserve area. */ char* _IO_buf_end; /* End of reserve area. */ /* The following fields are used to support backing up and undo. */ char *_IO_save_base; /* Pointer to start of non-current get area. */ char *_IO_backup_base; /* Pointer to first valid character of backup area */ char *_IO_save_end; /* Pointer to end of non-current get area. */ struct _IO_marker *_markers; struct _IO_FILE *_chain; int _fileno; #if 0 int _blksize; #else int _flags2; #endif _IO_off_t _old_offset; /* This used to be _offset but it's too small. */ #define __HAVE_COLUMN /* temporary */ /* 1+column number of pbase(); 0 is unknown. */ unsigned short _cur_column; signed char _vtable_offset; char _shortbuf[1]; /* char* _save_gptr; char* _save_egptr; */ _IO_lock_t *_lock; #ifdef _IO_USE_OLD_IO_FILE }; struct _IO_FILE_complete { struct _IO_FILE _file; #endif #if defined _G_IO_IO_FILE_VERSION && _G_IO_IO_FILE_VERSION == 0x20001 _IO_off64_t _offset; # if defined _LIBC || defined _GLIBCPP_USE_WCHAR_T /* Wide character stream stuff. */ struct _IO_codecvt *_codecvt; struct _IO_wide_data *_wide_data; struct _IO_FILE *_freeres_list; void *_freeres_buf; size_t _freeres_size; # else void *__pad1; void *__pad2; void *__pad3; void *__pad4; size_t __pad5; # endif int _mode; /* Make sure we don't get into trouble again. */ char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)]; #endif }; Example of C program to showing the use of FILE C // Program based on FILE handling.#include<stdio.h>int main(){ // declaring pointer of FILE type FILE *fp1, *fp2; char c; // pointing fp1 to a file geeky.txt // to read from it. fp1 = fopen("geeky.txt", "r"); // pointing fp2 to a file outgeeky.txt // to write to it. fp2 = fopen("outgeeky.txt", "w"); // reading a character from file. fscanf(fp1, "%c", &c); // writing a character to file. fprintf(fp2, "%c", c); return 0;} NOTE: The files should be in the same directory where program exist or specify the path of files. surinderdawra388 C-File Handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ TCP Server-Client implementation in C 'this' pointer in C++ Smart Pointers in C++ and How to Use Them Ways to copy a vector in C++ Storage Classes in C Understanding "extern" keyword in C
[ { "code": null, "e": 53, "s": 25, "text": "\n26 May, 2022" }, { "code": null, "e": 178, "s": 53, "text": "Prerequisite : Basics of File Handling In C language, while file handling is done a word FILE is used. What is FILE? Example" }, { "code": null, "e": 195, "s": 178, "text": "FILE *fp1, *fp2;" }, { "code": null, "e": 800, "s": 195, "text": "While doing file handling we often use FILE for declaring the pointer in order to point to the file we want to read from or to write on. As we are declaring the pointer of type FILE so we can say it is data type, but what kind of data type? A FILE is a type of structure typedef as FILE. It is considered as opaque data type as its implementation is hidden. We don’t know what constitutes the type, we only use pointer to the type and library knows the internal of the type and can use the data. Definition of FILE is in stdio although it is system specific. Following is the definition of FILE in ubuntu" }, { "code": null, "e": 2871, "s": 800, "text": "struct _IO_FILE {\n int _flags; /* High-order word is _IO_MAGIC; rest is flags. */\n#define _IO_file_flags _flags\n\n /* The following pointers correspond to the C++ streambuf protocol. */\n /* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */\n char* _IO_read_ptr; /* Current read pointer */\n char* _IO_read_end; /* End of get area. */\n char* _IO_read_base; /* Start of putback+get area. */\n char* _IO_write_base; /* Start of put area. */\n char* _IO_write_ptr; /* Current put pointer. */\n char* _IO_write_end; /* End of put area. */\n char* _IO_buf_base; /* Start of reserve area. */\n char* _IO_buf_end; /* End of reserve area. */\n /* The following fields are used to support backing up and undo. */\n char *_IO_save_base; /* Pointer to start of non-current get area. */\n char *_IO_backup_base; /* Pointer to first valid character of backup area */\n char *_IO_save_end; /* Pointer to end of non-current get area. */\n\n struct _IO_marker *_markers;\n\n struct _IO_FILE *_chain;\n\n int _fileno;\n#if 0\n int _blksize;\n#else\n int _flags2;\n#endif\n _IO_off_t _old_offset; /* This used to be _offset but it's too small. */\n\n#define __HAVE_COLUMN /* temporary */\n /* 1+column number of pbase(); 0 is unknown. */\n unsigned short _cur_column;\n signed char _vtable_offset;\n char _shortbuf[1];\n\n /* char* _save_gptr; char* _save_egptr; */\n\n _IO_lock_t *_lock;\n#ifdef _IO_USE_OLD_IO_FILE\n};\n\nstruct _IO_FILE_complete\n{\n struct _IO_FILE _file;\n#endif\n#if defined _G_IO_IO_FILE_VERSION && _G_IO_IO_FILE_VERSION == 0x20001\n _IO_off64_t _offset;\n# if defined _LIBC || defined _GLIBCPP_USE_WCHAR_T\n /* Wide character stream stuff. */\n struct _IO_codecvt *_codecvt;\n struct _IO_wide_data *_wide_data;\n struct _IO_FILE *_freeres_list;\n void *_freeres_buf;\n size_t _freeres_size;\n# else\n void *__pad1;\n void *__pad2;\n void *__pad3;\n void *__pad4;\n size_t __pad5;\n# endif\n int _mode;\n /* Make sure we don't get into trouble again. */\n char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];\n#endif\n};" }, { "code": null, "e": 2920, "s": 2871, "text": "Example of C program to showing the use of FILE " }, { "code": null, "e": 2922, "s": 2920, "text": "C" }, { "code": "// Program based on FILE handling.#include<stdio.h>int main(){ // declaring pointer of FILE type FILE *fp1, *fp2; char c; // pointing fp1 to a file geeky.txt // to read from it. fp1 = fopen(\"geeky.txt\", \"r\"); // pointing fp2 to a file outgeeky.txt // to write to it. fp2 = fopen(\"outgeeky.txt\", \"w\"); // reading a character from file. fscanf(fp1, \"%c\", &c); // writing a character to file. fprintf(fp2, \"%c\", c); return 0;}", "e": 3418, "s": 2922, "text": null }, { "code": null, "e": 3516, "s": 3418, "text": "NOTE: The files should be in the same directory where program exist or specify the path of files." }, { "code": null, "e": 3533, "s": 3516, "text": "surinderdawra388" }, { "code": null, "e": 3549, "s": 3533, "text": "C-File Handling" }, { "code": null, "e": 3560, "s": 3549, "text": "C Language" }, { "code": null, "e": 3658, "s": 3560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3706, "s": 3658, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3751, "s": 3706, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 3772, "s": 3751, "text": "Operators in C / C++" }, { "code": null, "e": 3798, "s": 3772, "text": "Exception Handling in C++" }, { "code": null, "e": 3836, "s": 3798, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3858, "s": 3836, "text": "'this' pointer in C++" }, { "code": null, "e": 3900, "s": 3858, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 3929, "s": 3900, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 3950, "s": 3929, "text": "Storage Classes in C" } ]
How to select and order multiple columns in Pyspark DataFrame ?
06 Jun, 2021 In this article, we will discuss how to select and order multiple columns from a dataframe using pyspark in Python. For this, we are using sort() and orderBy() functions along with select() function. Select(): This method is used to select the part of dataframe columns and return a copy of that newly selected dataframe. Syntax: dataframe.select([‘column1′,’column2′,’column n’].show() sort(): This method is used to sort the data of the dataframe and return a copy of that newly sorted dataframe. This sorts the dataframe in ascending by default. Syntax: dataframe.sort([‘column1′,’column2′,’column n’], ascending=True).show() oderBy(): This method is similar to sort which is also used to sort the dataframe.This sorts the dataframe in ascending by default. Syntax: dataframe.orderBy([‘column1′,’column2′,’column n’], ascending=True).show() Let’s create a sample dataframe Python3 # importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "sravan", "vignan"], ["2", "ojaswi", "vvit"], ["3", "rohith", "vvit"], ["4", "sridevi", "vignan"], ["1", "sravan", "vignan"], ["5", "gnanesh", "iit"]] # specify column namescolumns = ['student ID', 'student NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print("Actual data in dataframe")# show dataframedataframe.show() Output: Selecting multiple columns and order by using sort() method Python3 # show dataframe by sorting the dataframe# based on two columns in ascending# order using sort() functiondataframe.select(['student ID', 'student NAME'] ).sort(['student ID', 'student NAME'], ascending=True).show() Output: Python3 # show dataframe by sorting the dataframe# based on three columns in desc order# using sort() functiondataframe.select(['student ID', 'student NAME', 'college'] ).sort(['student ID', 'student NAME', 'college'], ascending=False).show() Output: Selecting multiple columns and order by using orderBy() method Python3 # show dataframe by sorting the dataframe# based on three columns in desc# order using orderBy() functiondataframe.select(['student ID', 'student NAME', 'college'] ).orderBy(['student ID', 'student NAME', 'college'], ascending=False).show() Output: Python3 # show dataframe by sorting the dataframe# based on two columns in asc# order using orderBy() functiondataframe.select(['student NAME', 'college'] ).orderBy(['student NAME', 'college'], ascending=True).show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 228, "s": 28, "text": "In this article, we will discuss how to select and order multiple columns from a dataframe using pyspark in Python. For this, we are using sort() and orderBy() functions along with select() function." }, { "code": null, "e": 350, "s": 228, "text": "Select(): This method is used to select the part of dataframe columns and return a copy of that newly selected dataframe." }, { "code": null, "e": 415, "s": 350, "text": "Syntax: dataframe.select([‘column1′,’column2′,’column n’].show()" }, { "code": null, "e": 577, "s": 415, "text": "sort(): This method is used to sort the data of the dataframe and return a copy of that newly sorted dataframe. This sorts the dataframe in ascending by default." }, { "code": null, "e": 657, "s": 577, "text": "Syntax: dataframe.sort([‘column1′,’column2′,’column n’], ascending=True).show()" }, { "code": null, "e": 789, "s": 657, "text": "oderBy(): This method is similar to sort which is also used to sort the dataframe.This sorts the dataframe in ascending by default." }, { "code": null, "e": 872, "s": 789, "text": "Syntax: dataframe.orderBy([‘column1′,’column2′,’column n’], ascending=True).show()" }, { "code": null, "e": 904, "s": 872, "text": "Let’s create a sample dataframe" }, { "code": null, "e": 912, "s": 904, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"sravan\", \"vignan\"], [\"2\", \"ojaswi\", \"vvit\"], [\"3\", \"rohith\", \"vvit\"], [\"4\", \"sridevi\", \"vignan\"], [\"1\", \"sravan\", \"vignan\"], [\"5\", \"gnanesh\", \"iit\"]] # specify column namescolumns = ['student ID', 'student NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print(\"Actual data in dataframe\")# show dataframedataframe.show()", "e": 1584, "s": 912, "text": null }, { "code": null, "e": 1592, "s": 1584, "text": "Output:" }, { "code": null, "e": 1652, "s": 1592, "text": "Selecting multiple columns and order by using sort() method" }, { "code": null, "e": 1660, "s": 1652, "text": "Python3" }, { "code": "# show dataframe by sorting the dataframe# based on two columns in ascending# order using sort() functiondataframe.select(['student ID', 'student NAME'] ).sort(['student ID', 'student NAME'], ascending=True).show()", "e": 1913, "s": 1660, "text": null }, { "code": null, "e": 1921, "s": 1913, "text": "Output:" }, { "code": null, "e": 1929, "s": 1921, "text": "Python3" }, { "code": "# show dataframe by sorting the dataframe# based on three columns in desc order# using sort() functiondataframe.select(['student ID', 'student NAME', 'college'] ).sort(['student ID', 'student NAME', 'college'], ascending=False).show()", "e": 2201, "s": 1929, "text": null }, { "code": null, "e": 2209, "s": 2201, "text": "Output:" }, { "code": null, "e": 2272, "s": 2209, "text": "Selecting multiple columns and order by using orderBy() method" }, { "code": null, "e": 2280, "s": 2272, "text": "Python3" }, { "code": "# show dataframe by sorting the dataframe# based on three columns in desc# order using orderBy() functiondataframe.select(['student ID', 'student NAME', 'college'] ).orderBy(['student ID', 'student NAME', 'college'], ascending=False).show()", "e": 2561, "s": 2280, "text": null }, { "code": null, "e": 2569, "s": 2561, "text": "Output:" }, { "code": null, "e": 2577, "s": 2569, "text": "Python3" }, { "code": "# show dataframe by sorting the dataframe# based on two columns in asc# order using orderBy() functiondataframe.select(['student NAME', 'college'] ).orderBy(['student NAME', 'college'], ascending=True).show()", "e": 2826, "s": 2577, "text": null }, { "code": null, "e": 2834, "s": 2826, "text": "Output:" }, { "code": null, "e": 2841, "s": 2834, "text": "Picked" }, { "code": null, "e": 2856, "s": 2841, "text": "Python-Pyspark" }, { "code": null, "e": 2863, "s": 2856, "text": "Python" } ]
Ruby | Random rand() function
17 Dec, 2019 Random#rand() : rand() is a Random class method which generates a random value. Syntax: Random.rand() Parameter: Random values Return: generates a random value. Example #1 : # Ruby code for Random.rand() method # declaring Random valuedate_a = Random.rand() # new arbitrary random valueputs "Random form : #{date_a}\n\n" Output : Random form : 0.19492446216402715 Example #2 : # Ruby code for Random.rand() method # declaring Random valuedate_b = Random.rand() date_a = Random.rand(10) # new arbitrary random valueputs "Random form : #{date_b}\n\n" puts "Random form : #{date_a}\n\n" Output : Random form : 0.175729980681539 Random form : 1 Ruby Random-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby on Rails Introduction Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby | String concat Method Ruby For Beginners Ruby | Array class find_index() operation Ruby | Array shift() function Ruby | Types of Variables Ruby | Exception handling
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2019" }, { "code": null, "e": 108, "s": 28, "text": "Random#rand() : rand() is a Random class method which generates a random value." }, { "code": null, "e": 130, "s": 108, "text": "Syntax: Random.rand()" }, { "code": null, "e": 155, "s": 130, "text": "Parameter: Random values" }, { "code": null, "e": 189, "s": 155, "text": "Return: generates a random value." }, { "code": null, "e": 202, "s": 189, "text": "Example #1 :" }, { "code": "# Ruby code for Random.rand() method # declaring Random valuedate_a = Random.rand() # new arbitrary random valueputs \"Random form : #{date_a}\\n\\n\"", "e": 351, "s": 202, "text": null }, { "code": null, "e": 360, "s": 351, "text": "Output :" }, { "code": null, "e": 396, "s": 360, "text": "Random form : 0.19492446216402715\n\n" }, { "code": null, "e": 409, "s": 396, "text": "Example #2 :" }, { "code": "# Ruby code for Random.rand() method # declaring Random valuedate_b = Random.rand() date_a = Random.rand(10) # new arbitrary random valueputs \"Random form : #{date_b}\\n\\n\" puts \"Random form : #{date_a}\\n\\n\"", "e": 620, "s": 409, "text": null }, { "code": null, "e": 629, "s": 620, "text": "Output :" }, { "code": null, "e": 680, "s": 629, "text": "Random form : 0.175729980681539\n\nRandom form : 1\n\n" }, { "code": null, "e": 698, "s": 680, "text": "Ruby Random-class" }, { "code": null, "e": 711, "s": 698, "text": "Ruby-Methods" }, { "code": null, "e": 716, "s": 711, "text": "Ruby" }, { "code": null, "e": 814, "s": 716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 860, "s": 814, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 887, "s": 860, "text": "Ruby on Rails Introduction" }, { "code": null, "e": 930, "s": 887, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 974, "s": 930, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1002, "s": 974, "text": "Ruby | String concat Method" }, { "code": null, "e": 1021, "s": 1002, "text": "Ruby For Beginners" }, { "code": null, "e": 1063, "s": 1021, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 1093, "s": 1063, "text": "Ruby | Array shift() function" }, { "code": null, "e": 1119, "s": 1093, "text": "Ruby | Types of Variables" } ]
Python Daemon Threads
17 Aug, 2021 The threads which are always going to run in the background that provides supports to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background. This article is based on threading in python, here we discuss daemon thread with examples. There is one of the best examples of a daemon thread is Garbage Collector because we assume that the main thread is executing or running, at that time any memory problem occurs then immediately python virtual machine(PVM) is going to execute Garbage Collector. The Garbage Collector is going to execute in the background and destroy all the useless objects and then free memory by default will be provided, once there is free memory will available then the main thread is going to be executed without any problem. This example simplifies the flow of a non-daemon thread where we have created a thread_1() name function which having some lines of instructions to execute which reveal how the non-daemon thread is executed when the main thread terminates. At the next we have created the thread T of function thread_1() which is currently considered as a non-active thread, now we start the thread T, and we also have temporarily stopped the execution of the main thread for 5secs. Of time, between this 5sec. Thread T continues its execution and when the main thread is going to be executed after 5sec. Where it stops its work but there is a thread T still is in execution because it is a non-daemon thread and executes their instruction until their completion. Below is the implementation: Python3 # import modulefrom threading import *import time # creating a functiondef thread_1(): for i in range(5): print('this is non-daemon thread') time.sleep(2) # creating a thread TT = Thread(target=thread_1) # starting of thread TT.start() # main thread stop execution till 5 sec.time.sleep(5) print('main Thread execution') Output: this is non-daemon thread this is non-daemon thread this is non-daemon thread main Thread execution this is non-daemon thread this is non-daemon thread This is an example to show how daemon threads behave over non-daemon threads during program execution. We already see in the above example that how the non-daemon thread completes its execution after the termination of the main thread but here is something different from that. In this example, we have created a function thread_1() and thread T as same as above example but here after the creation of thread T we use setDaemon() method to change the non-daemon nature of thread T to daemon nature, then we start the thread T and temporary stops the execution of the main thread. Here is the twist when the main thread is complete their execution and terminates then thread T also terminates because this is a daemon thread, where daemon thread terminates it’s execution when the main thread terminates, work of it is to support the main thread if there is no main thread remaining why will daemon thread running there they also terminate still execution of instructions is remaining. Below is the implementation: Python3 # import modulesfrom threading import *import time # creating a functiondef thread_1(): for i in range(5): print('this is thread T') time.sleep(3) # creating a threadT = Thread(target = thread_1) # change T to daemonT.setDaemon(True) # starting of Thread TT.start() time.sleep(5)print('this is Main Thread') Output: this is thread T this is thread T this is Main Thread There are one method and one property to check the nature of the following thread: isDaemon( ) daemon Example 1: Program to explain isDaemon() and daemon methods. This is a simple example to explain how we check the nature or status of the following thread, in this example, we check the nature of the main thread by using isDaemon() and daemon method. Here we use current_thread() method which simplifies which thread is currently executing, and we use it with isDaemon() and daemon method to check the nature or status of the current thread. The output of this code is False and False because current_thread is the main thread is always a non-daemon thread. Python3 # import modulefrom threading import * print(current_thread().isDaemon()) print(current_thread().daemon) Output: False False Example 2: In this example we have created a function to check whether the thread is a daemon or not, then we create a new thread thread_1 which is currently a non-daemon thread and non-active thread then we check the status or nature of the thread, the output becomes False after that we start a thread now thread becomes an active thread again we check it’s status an again output is False this all means that not the main thread is non-daemon but also other created thread is also non-daemon. Python3 # import modulefrom threading import * def fun_daemon(): print("GFG") thread_1 = Thread(target=fun_daemon)print(thread_1.isDaemon())thread_1.start()print(thread_1.daemon) Output: False GFG False As we previously see that how to check whether the following thread is a daemon or non-daemon, here we learn about how the following non-daemon thread can be changed into the daemon. A setDaemon() is the method that is used to change the non-daemon nature of a given thread into the daemon nature. setDaemon() method takes only one parameter that is a Boolean value (True or False). Syntax: Thread_name.setDaemon() # Here Thread_name refers to name of thread that you have used. Parameter: (True or False) if True, marks this thread as a daemon thread if False, marks this thread as a non daemon thread. Example: Python3 # import modulefrom threading import * def fun(): print("Geeks For Geeks") T = Thread(target = fun) print("GFG")print(T.isDaemon()) # set thread as DaemonT.setDaemon(True) # check statusprint(T.isDaemon())T.start() Output: GFG False True Geeks For Geeks Explanation: In the above example first, we import a library threading then we define a new function fun() at the next point we create a new threading variable T. Currently, T is a non-active thread we didn’t execute the start() method yet, here we will check the status of thread T and the output comes to be False at next we use the method setDaemon() to change the nature of thread T after using the method again we will check the status of following thread at this time output will be True. If we want to change the main thread which is always non-daemon in nature to daemon nature then we will get a RuntimeError because when the program is started at a time main thread is also started so the main thread is an active thread and the active thread is not set to the daemon. Example: Python3 # import modulefrom threading import * print(current_thread().setDaemon(True)) Output: RuntimeError: cannot set daemon status of active thread pranavjandu maneesh085 Python-multithreading Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Aug, 2021" }, { "code": null, "e": 430, "s": 54, "text": "The threads which are always going to run in the background that provides supports to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background. This article is based on threading in python, here we discuss daemon thread with examples." }, { "code": null, "e": 944, "s": 430, "text": "There is one of the best examples of a daemon thread is Garbage Collector because we assume that the main thread is executing or running, at that time any memory problem occurs then immediately python virtual machine(PVM) is going to execute Garbage Collector. The Garbage Collector is going to execute in the background and destroy all the useless objects and then free memory by default will be provided, once there is free memory will available then the main thread is going to be executed without any problem." }, { "code": null, "e": 1692, "s": 944, "text": "This example simplifies the flow of a non-daemon thread where we have created a thread_1() name function which having some lines of instructions to execute which reveal how the non-daemon thread is executed when the main thread terminates. At the next we have created the thread T of function thread_1() which is currently considered as a non-active thread, now we start the thread T, and we also have temporarily stopped the execution of the main thread for 5secs. Of time, between this 5sec. Thread T continues its execution and when the main thread is going to be executed after 5sec. Where it stops its work but there is a thread T still is in execution because it is a non-daemon thread and executes their instruction until their completion. " }, { "code": null, "e": 1721, "s": 1692, "text": "Below is the implementation:" }, { "code": null, "e": 1729, "s": 1721, "text": "Python3" }, { "code": "# import modulefrom threading import *import time # creating a functiondef thread_1(): for i in range(5): print('this is non-daemon thread') time.sleep(2) # creating a thread TT = Thread(target=thread_1) # starting of thread TT.start() # main thread stop execution till 5 sec.time.sleep(5) print('main Thread execution')", "e": 2095, "s": 1729, "text": null }, { "code": null, "e": 2104, "s": 2095, "text": "Output: " }, { "code": null, "e": 2256, "s": 2104, "text": "this is non-daemon thread\nthis is non-daemon thread\nthis is non-daemon thread\nmain Thread execution\nthis is non-daemon thread\nthis is non-daemon thread" }, { "code": null, "e": 3241, "s": 2256, "text": "This is an example to show how daemon threads behave over non-daemon threads during program execution. We already see in the above example that how the non-daemon thread completes its execution after the termination of the main thread but here is something different from that. In this example, we have created a function thread_1() and thread T as same as above example but here after the creation of thread T we use setDaemon() method to change the non-daemon nature of thread T to daemon nature, then we start the thread T and temporary stops the execution of the main thread. Here is the twist when the main thread is complete their execution and terminates then thread T also terminates because this is a daemon thread, where daemon thread terminates it’s execution when the main thread terminates, work of it is to support the main thread if there is no main thread remaining why will daemon thread running there they also terminate still execution of instructions is remaining." }, { "code": null, "e": 3271, "s": 3241, "text": "Below is the implementation: " }, { "code": null, "e": 3279, "s": 3271, "text": "Python3" }, { "code": "# import modulesfrom threading import *import time # creating a functiondef thread_1(): for i in range(5): print('this is thread T') time.sleep(3) # creating a threadT = Thread(target = thread_1) # change T to daemonT.setDaemon(True) # starting of Thread TT.start() time.sleep(5)print('this is Main Thread') ", "e": 3659, "s": 3279, "text": null }, { "code": null, "e": 3667, "s": 3659, "text": "Output:" }, { "code": null, "e": 3721, "s": 3667, "text": "this is thread T\nthis is thread T\nthis is Main Thread" }, { "code": null, "e": 3804, "s": 3721, "text": "There are one method and one property to check the nature of the following thread:" }, { "code": null, "e": 3816, "s": 3804, "text": "isDaemon( )" }, { "code": null, "e": 3823, "s": 3816, "text": "daemon" }, { "code": null, "e": 3884, "s": 3823, "text": "Example 1: Program to explain isDaemon() and daemon methods." }, { "code": null, "e": 4381, "s": 3884, "text": "This is a simple example to explain how we check the nature or status of the following thread, in this example, we check the nature of the main thread by using isDaemon() and daemon method. Here we use current_thread() method which simplifies which thread is currently executing, and we use it with isDaemon() and daemon method to check the nature or status of the current thread. The output of this code is False and False because current_thread is the main thread is always a non-daemon thread." }, { "code": null, "e": 4389, "s": 4381, "text": "Python3" }, { "code": "# import modulefrom threading import * print(current_thread().isDaemon()) print(current_thread().daemon)", "e": 4501, "s": 4389, "text": null }, { "code": null, "e": 4509, "s": 4501, "text": "Output:" }, { "code": null, "e": 4521, "s": 4509, "text": "False\nFalse" }, { "code": null, "e": 4533, "s": 4521, "text": "Example 2: " }, { "code": null, "e": 5018, "s": 4533, "text": "In this example we have created a function to check whether the thread is a daemon or not, then we create a new thread thread_1 which is currently a non-daemon thread and non-active thread then we check the status or nature of the thread, the output becomes False after that we start a thread now thread becomes an active thread again we check it’s status an again output is False this all means that not the main thread is non-daemon but also other created thread is also non-daemon." }, { "code": null, "e": 5026, "s": 5018, "text": "Python3" }, { "code": "# import modulefrom threading import * def fun_daemon(): print(\"GFG\") thread_1 = Thread(target=fun_daemon)print(thread_1.isDaemon())thread_1.start()print(thread_1.daemon)", "e": 5200, "s": 5026, "text": null }, { "code": null, "e": 5208, "s": 5200, "text": "Output:" }, { "code": null, "e": 5224, "s": 5208, "text": "False\nGFG\nFalse" }, { "code": null, "e": 5407, "s": 5224, "text": "As we previously see that how to check whether the following thread is a daemon or non-daemon, here we learn about how the following non-daemon thread can be changed into the daemon." }, { "code": null, "e": 5609, "s": 5407, "text": " A setDaemon() is the method that is used to change the non-daemon nature of a given thread into the daemon nature. setDaemon() method takes only one parameter that is a Boolean value (True or False). " }, { "code": null, "e": 5645, "s": 5609, "text": "Syntax: Thread_name.setDaemon() " }, { "code": null, "e": 5715, "s": 5645, "text": "# Here Thread_name refers to name of thread that you have used. " }, { "code": null, "e": 5744, "s": 5715, "text": "Parameter: (True or False) " }, { "code": null, "e": 5790, "s": 5744, "text": "if True, marks this thread as a daemon thread" }, { "code": null, "e": 5842, "s": 5790, "text": "if False, marks this thread as a non daemon thread." }, { "code": null, "e": 5851, "s": 5842, "text": "Example:" }, { "code": null, "e": 5859, "s": 5851, "text": "Python3" }, { "code": "# import modulefrom threading import * def fun(): print(\"Geeks For Geeks\") T = Thread(target = fun) print(\"GFG\")print(T.isDaemon()) # set thread as DaemonT.setDaemon(True) # check statusprint(T.isDaemon())T.start()", "e": 6078, "s": 5859, "text": null }, { "code": null, "e": 6086, "s": 6078, "text": "Output:" }, { "code": null, "e": 6117, "s": 6086, "text": "GFG\nFalse\nTrue\nGeeks For Geeks" }, { "code": null, "e": 6130, "s": 6117, "text": "Explanation:" }, { "code": null, "e": 6614, "s": 6130, "text": "In the above example first, we import a library threading then we define a new function fun() at the next point we create a new threading variable T. Currently, T is a non-active thread we didn’t execute the start() method yet, here we will check the status of thread T and the output comes to be False at next we use the method setDaemon() to change the nature of thread T after using the method again we will check the status of following thread at this time output will be True. " }, { "code": null, "e": 6898, "s": 6614, "text": "If we want to change the main thread which is always non-daemon in nature to daemon nature then we will get a RuntimeError because when the program is started at a time main thread is also started so the main thread is an active thread and the active thread is not set to the daemon." }, { "code": null, "e": 6907, "s": 6898, "text": "Example:" }, { "code": null, "e": 6915, "s": 6907, "text": "Python3" }, { "code": "# import modulefrom threading import * print(current_thread().setDaemon(True))", "e": 6994, "s": 6915, "text": null }, { "code": null, "e": 7003, "s": 6994, "text": "Output: " }, { "code": null, "e": 7059, "s": 7003, "text": "RuntimeError: cannot set daemon status of active thread" }, { "code": null, "e": 7071, "s": 7059, "text": "pranavjandu" }, { "code": null, "e": 7082, "s": 7071, "text": "maneesh085" }, { "code": null, "e": 7104, "s": 7082, "text": "Python-multithreading" }, { "code": null, "e": 7111, "s": 7104, "text": "Python" } ]
When are static objects destroyed?
21 Jun, 2017 Remain Careful from these two personsnew friends and old enemies — Kabir What is static keyword in C++?static keyword can be applied to local variables, functions, class’ data members and objects in C++. static local variable retain their values between function call and initialized only once. static function can be directly called using the scope resolution operator preceded by class name (See this, this and this for more details). C++ also supports static objects. What are static objects in C++?An object become static when static keyword is used in its declaration. See the following two statements for example in C++. Test t; // Stack based object static Test t1; // Static object First statement when executes creates object on stack means storage is allocated on stack. Stack based objects are also called automatic objects or local objects. static object are initialized only once and live until the program terminates. Local object is created each time its declaration is encountered in the execution of program. static objects are allocated storage in static storage area. static object is destroyed at the termination of program. C++ supports both local static object and global static objectFollowing is example that shows use of local static object. #include <iostream>class Test {public: Test() { std::cout << "Constructor is executed\n"; } ~Test() { std::cout << "Destructor is executed\n"; }};void myfunc(){ static Test obj;} // Object obj is still not destroyed because it is static int main(){ std::cout << "main() starts\n"; myfunc(); // Destructor will not be called here std::cout << "main() terminates\n"; return 0;} Output: main() starts Constructor is executed main() terminates Destructor is executed If we observe the output of this program closely, we can see that the destructor for the local object named obj is not called after it’s constructor is executed because the local object is static so it has scope till the lifetime of program so it’s destructor will be called when main() terminates. What happens when we remove static in above program?As an experiment if we remove the static keyword from the global function myfunc(), we get the output as below: main() starts Constructor is called Destructor is called main() terminates This is because the object is now stack based object and it is destroyed when it is goes out of scope and its destructor will be called. How about global static objects?The following program demonstrates use of global static object. #include <iostream>class Test{public: int a; Test() { a = 10; std::cout << "Constructor is executed\n"; } ~Test() { std::cout << "Destructor is executed\n"; }};static Test obj;int main(){ std::cout << "main() starts\n"; std::cout << obj.a; std::cout << "\nmain() terminates\n"; return 0;} Output: Constructor is executed main() starts 10 main() terminates Destructor is executed This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C++-Static Keyword cpp-class cpp-constructor cpp-storage-classes Static Keyword 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 What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ 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) vector erase() and clear() in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2017" }, { "code": null, "e": 127, "s": 54, "text": "Remain Careful from these two personsnew friends and old enemies — Kabir" }, { "code": null, "e": 525, "s": 127, "text": "What is static keyword in C++?static keyword can be applied to local variables, functions, class’ data members and objects in C++. static local variable retain their values between function call and initialized only once. static function can be directly called using the scope resolution operator preceded by class name (See this, this and this for more details). C++ also supports static objects." }, { "code": null, "e": 681, "s": 525, "text": "What are static objects in C++?An object become static when static keyword is used in its declaration. See the following two statements for example in C++." }, { "code": null, "e": 761, "s": 681, "text": "Test t; // Stack based object\nstatic Test t1; // Static object " }, { "code": null, "e": 1097, "s": 761, "text": "First statement when executes creates object on stack means storage is allocated on stack. Stack based objects are also called automatic objects or local objects. static object are initialized only once and live until the program terminates. Local object is created each time its declaration is encountered in the execution of program." }, { "code": null, "e": 1338, "s": 1097, "text": "static objects are allocated storage in static storage area. static object is destroyed at the termination of program. C++ supports both local static object and global static objectFollowing is example that shows use of local static object." }, { "code": "#include <iostream>class Test {public: Test() { std::cout << \"Constructor is executed\\n\"; } ~Test() { std::cout << \"Destructor is executed\\n\"; }};void myfunc(){ static Test obj;} // Object obj is still not destroyed because it is static int main(){ std::cout << \"main() starts\\n\"; myfunc(); // Destructor will not be called here std::cout << \"main() terminates\\n\"; return 0;}", "e": 1765, "s": 1338, "text": null }, { "code": null, "e": 1773, "s": 1765, "text": "Output:" }, { "code": null, "e": 1853, "s": 1773, "text": "main() starts\nConstructor is executed\nmain() terminates\nDestructor is executed " }, { "code": null, "e": 2152, "s": 1853, "text": "If we observe the output of this program closely, we can see that the destructor for the local object named obj is not called after it’s constructor is executed because the local object is static so it has scope till the lifetime of program so it’s destructor will be called when main() terminates." }, { "code": null, "e": 2316, "s": 2152, "text": "What happens when we remove static in above program?As an experiment if we remove the static keyword from the global function myfunc(), we get the output as below:" }, { "code": null, "e": 2391, "s": 2316, "text": "main() starts\nConstructor is called\nDestructor is called\nmain() terminates" }, { "code": null, "e": 2528, "s": 2391, "text": "This is because the object is now stack based object and it is destroyed when it is goes out of scope and its destructor will be called." }, { "code": null, "e": 2624, "s": 2528, "text": "How about global static objects?The following program demonstrates use of global static object." }, { "code": "#include <iostream>class Test{public: int a; Test() { a = 10; std::cout << \"Constructor is executed\\n\"; } ~Test() { std::cout << \"Destructor is executed\\n\"; }};static Test obj;int main(){ std::cout << \"main() starts\\n\"; std::cout << obj.a; std::cout << \"\\nmain() terminates\\n\"; return 0;}", "e": 2967, "s": 2624, "text": null }, { "code": null, "e": 2975, "s": 2967, "text": "Output:" }, { "code": null, "e": 3057, "s": 2975, "text": "Constructor is executed\nmain() starts\n10\nmain() terminates\nDestructor is executed" }, { "code": null, "e": 3226, "s": 3057, "text": "This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 3245, "s": 3226, "text": "C++-Static Keyword" }, { "code": null, "e": 3255, "s": 3245, "text": "cpp-class" }, { "code": null, "e": 3271, "s": 3255, "text": "cpp-constructor" }, { "code": null, "e": 3291, "s": 3271, "text": "cpp-storage-classes" }, { "code": null, "e": 3306, "s": 3291, "text": "Static Keyword" }, { "code": null, "e": 3317, "s": 3306, "text": "C Language" }, { "code": null, "e": 3321, "s": 3317, "text": "C++" }, { "code": null, "e": 3325, "s": 3321, "text": "CPP" }, { "code": null, "e": 3423, "s": 3325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3471, "s": 3423, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3516, "s": 3471, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 3537, "s": 3516, "text": "Operators in C / C++" }, { "code": null, "e": 3563, "s": 3537, "text": "Exception Handling in C++" }, { "code": null, "e": 3601, "s": 3563, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3619, "s": 3601, "text": "Vector in C++ STL" }, { "code": null, "e": 3662, "s": 3619, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 3708, "s": 3662, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3751, "s": 3708, "text": "Set in C++ Standard Template Library (STL)" } ]
HTML | Computer Code Elements
22 Dec, 2021 The computer has a unique formatting and text style for displaying the messages related to codes. The <code> tag is used to display the computer code on the website. There are number of elements available to mark up computer code using HTML.<code> Tag: The <code> tag in HTML is used to define the piece of computer code. During the creation of web pages sometimes there is a need to display computer programming code. It could be done by any basic heading tag of HTML but HTML provides a separate tag which is <code> tag. The code tag is a specific type of text which represent computer output. HTML provides many methods for text-formatting but <code> tag is displayed with fixed letter size, font, and spacing.Syntax: <code> Computer code contents... </code> Example 1: html <pre><code>#include<stdio.h>int main() { printf("Hello Geeks");}</code></pre> Output: Example 2: html <pre><code>class GFG { // Program begins with a call to main() // Print "Hello, World" to the terminal window public static void main(String args[]) { System.out.println("Hello, World"); } } </code></pre> Output: Note: The program which is written inside the <code> tag has some different font size and font type to the basic heading tag and paragraph tag. <pre> tag is used to display code snippet because it always keeps the text formatting as it is.Some points about <code> tag: It is mainly used to display the code snippet into the web browser. This tag styles its element to match computer’s default text format. The web browsers by default use a mono space font family for displaying <code> tags element content. <kbd> Tag: It is a phrase tag and used to define the keyboard input. The text between the <kbd> tag represents similar text should be typed on the keyboard.Syntax: <kbd> Contents... </kbd> Example: html <!DOCTYPE html><html> <head> <title>The kbd tag</title> <style> body { text-align:center; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <kbd>A computer</kbd> <kbd>science</kbd> <kbd>portal</kbd> </body></html> Output: Some points about <kbd> tag: The text enclosed by <kbd> tag is typically displayed in the browser’s default mono-space font. It is possible to achieve richer effect with CSS There is no tag specific attributes. <pre> Tag: The <pre> tag in HTML is used to define the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. Text in the <pre> element is displayed in a fixed-width font, but it can be changed using CSS. The <pre> tag requires a starting and end tag.Syntax: <pre> Contents... </pre> Example 1: html <!DOCTYPE html><html> <head> <title>pre tag</title> </head> <body> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> </body></html> Output: Example 2: html <!DOCTYPE html><html> <head> <title>pre tag with CSS</title> <style> pre { font-family: Arial; color: #009900; margin: 25px; } </style> </head> <body> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> </body></html> Output: <samp> Tag: It is a phrase tag and used to define the sample output text from a computer program. The HTML Sample Element is used to enclose inline text which represents sample (or quoted) output from a computer program.Syntax: <samp> Contents... </samp> Example: html <!DOCTYPE html><html> <head> <title>samp tag</title> </head> <style> body { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:25px; font-weight:bold; } </style> <body> <div class ="gfg">GeeksForGeeks</div> <div class = "geeks"><samp> Tag</div> <samp>A computer science portal for Geeks</samp> </body></html> Output: <var> Tag: It is a phrase tag and used to specify the variable in a mathematical equation or in a computer program. The content of this tag is displayed in the italic format in most of the browsers.Syntax: <var> Contents... </var> Example: html <!DOCTYPE html><html> <head> <title>var tag</title> </head> <style> body { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:25px; font-weight:bold; } </style> <body> <div class ="gfg">GeeksForGeeks</div> <div class = "geeks"><var> Tag</div> <var>GeeksforGeeks Variable</var> </body></html> Output: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 vshylaja HTML-Basics Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Dec, 2021" }, { "code": null, "e": 775, "s": 52, "text": "The computer has a unique formatting and text style for displaying the messages related to codes. The <code> tag is used to display the computer code on the website. There are number of elements available to mark up computer code using HTML.<code> Tag: The <code> tag in HTML is used to define the piece of computer code. During the creation of web pages sometimes there is a need to display computer programming code. It could be done by any basic heading tag of HTML but HTML provides a separate tag which is <code> tag. The code tag is a specific type of text which represent computer output. HTML provides many methods for text-formatting but <code> tag is displayed with fixed letter size, font, and spacing.Syntax: " }, { "code": null, "e": 816, "s": 775, "text": "<code> Computer code contents... </code>" }, { "code": null, "e": 829, "s": 816, "text": "Example 1: " }, { "code": null, "e": 834, "s": 829, "text": "html" }, { "code": "<pre><code>#include<stdio.h>int main() { printf(\"Hello Geeks\");}</code></pre>", "e": 915, "s": 834, "text": null }, { "code": null, "e": 925, "s": 915, "text": "Output: " }, { "code": null, "e": 938, "s": 925, "text": "Example 2: " }, { "code": null, "e": 943, "s": 938, "text": "html" }, { "code": "<pre><code>class GFG { // Program begins with a call to main() // Print \"Hello, World\" to the terminal window public static void main(String args[]) { System.out.println(\"Hello, World\"); } } </code></pre> ", "e": 1176, "s": 943, "text": null }, { "code": null, "e": 1186, "s": 1176, "text": "Output: " }, { "code": null, "e": 1457, "s": 1186, "text": "Note: The program which is written inside the <code> tag has some different font size and font type to the basic heading tag and paragraph tag. <pre> tag is used to display code snippet because it always keeps the text formatting as it is.Some points about <code> tag: " }, { "code": null, "e": 1525, "s": 1457, "text": "It is mainly used to display the code snippet into the web browser." }, { "code": null, "e": 1594, "s": 1525, "text": "This tag styles its element to match computer’s default text format." }, { "code": null, "e": 1695, "s": 1594, "text": "The web browsers by default use a mono space font family for displaying <code> tags element content." }, { "code": null, "e": 1861, "s": 1695, "text": "<kbd> Tag: It is a phrase tag and used to define the keyboard input. The text between the <kbd> tag represents similar text should be typed on the keyboard.Syntax: " }, { "code": null, "e": 1886, "s": 1861, "text": "<kbd> Contents... </kbd>" }, { "code": null, "e": 1897, "s": 1886, "text": "Example: " }, { "code": null, "e": 1902, "s": 1897, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>The kbd tag</title> <style> body { text-align:center; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <kbd>A computer</kbd> <kbd>science</kbd> <kbd>portal</kbd> </body></html> ", "e": 2249, "s": 1902, "text": null }, { "code": null, "e": 2259, "s": 2249, "text": "Output: " }, { "code": null, "e": 2290, "s": 2259, "text": "Some points about <kbd> tag: " }, { "code": null, "e": 2386, "s": 2290, "text": "The text enclosed by <kbd> tag is typically displayed in the browser’s default mono-space font." }, { "code": null, "e": 2435, "s": 2386, "text": "It is possible to achieve richer effect with CSS" }, { "code": null, "e": 2472, "s": 2435, "text": "There is no tag specific attributes." }, { "code": null, "e": 2824, "s": 2472, "text": "<pre> Tag: The <pre> tag in HTML is used to define the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. Text in the <pre> element is displayed in a fixed-width font, but it can be changed using CSS. The <pre> tag requires a starting and end tag.Syntax: " }, { "code": null, "e": 2849, "s": 2824, "text": "<pre> Contents... </pre>" }, { "code": null, "e": 2862, "s": 2849, "text": "Example 1: " }, { "code": null, "e": 2867, "s": 2862, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>pre tag</title> </head> <body> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> </body></html> ", "e": 3108, "s": 2867, "text": null }, { "code": null, "e": 3118, "s": 3108, "text": "Output: " }, { "code": null, "e": 3131, "s": 3118, "text": "Example 2: " }, { "code": null, "e": 3136, "s": 3131, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>pre tag with CSS</title> <style> pre { font-family: Arial; color: #009900; margin: 25px; } </style> </head> <body> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> </body></html>", "e": 3503, "s": 3136, "text": null }, { "code": null, "e": 3513, "s": 3503, "text": "Output: " }, { "code": null, "e": 3743, "s": 3513, "text": "<samp> Tag: It is a phrase tag and used to define the sample output text from a computer program. The HTML Sample Element is used to enclose inline text which represents sample (or quoted) output from a computer program.Syntax: " }, { "code": null, "e": 3770, "s": 3743, "text": "<samp> Contents... </samp>" }, { "code": null, "e": 3781, "s": 3770, "text": "Example: " }, { "code": null, "e": 3786, "s": 3781, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>samp tag</title> </head> <style> body { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:25px; font-weight:bold; } </style> <body> <div class =\"gfg\">GeeksForGeeks</div> <div class = \"geeks\"><samp> Tag</div> <samp>A computer science portal for Geeks</samp> </body></html> ", "e": 4314, "s": 3786, "text": null }, { "code": null, "e": 4324, "s": 4314, "text": "Output: " }, { "code": null, "e": 4532, "s": 4324, "text": "<var> Tag: It is a phrase tag and used to specify the variable in a mathematical equation or in a computer program. The content of this tag is displayed in the italic format in most of the browsers.Syntax: " }, { "code": null, "e": 4557, "s": 4532, "text": "<var> Contents... </var>" }, { "code": null, "e": 4568, "s": 4557, "text": "Example: " }, { "code": null, "e": 4573, "s": 4568, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>var tag</title> </head> <style> body { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:25px; font-weight:bold; } </style> <body> <div class =\"gfg\">GeeksForGeeks</div> <div class = \"geeks\"><var> Tag</div> <var>GeeksforGeeks Variable</var> </body></html> ", "e": 5084, "s": 4573, "text": null }, { "code": null, "e": 5094, "s": 5084, "text": "Output: " }, { "code": null, "e": 5113, "s": 5094, "text": "Supported Browser:" }, { "code": null, "e": 5127, "s": 5113, "text": "Google Chrome" }, { "code": null, "e": 5142, "s": 5127, "text": "Microsoft Edge" }, { "code": null, "e": 5150, "s": 5142, "text": "Firefox" }, { "code": null, "e": 5156, "s": 5150, "text": "Opera" }, { "code": null, "e": 5163, "s": 5156, "text": "Safari" }, { "code": null, "e": 5175, "s": 5163, "text": "ysachin2314" }, { "code": null, "e": 5184, "s": 5175, "text": "vshylaja" }, { "code": null, "e": 5196, "s": 5184, "text": "HTML-Basics" }, { "code": null, "e": 5203, "s": 5196, "text": "Picked" }, { "code": null, "e": 5208, "s": 5203, "text": "HTML" }, { "code": null, "e": 5225, "s": 5208, "text": "Web Technologies" }, { "code": null, "e": 5230, "s": 5225, "text": "HTML" } ]
How to check an array is multidimensional or not in PHP ?
12 Jul, 2019 Given an array (single-dimensional or multi-dimensional) and the task is to check the given array is multi-dimensional or not. There are few methods to check an array is multi-dimensional or not. The function count() and count_recursive() will give wrong result if the array containing a sub-array which is empty, and the other one is using the rsort() function. This function sorts all the sub-arrays towards the beginning of the parent array and re-indexes the array. This ensures that if there are one or more sub-arrays inside the parent array, the first element of the parent array (at index 0) will always be an array. Checking for the element at index 0, we can tell whether the array is multidimensional or not. Syntax: rsort( $array ) Parameters: The rsort() function accepts one parameter. $array: This is the object you want to pass to the function. Example 1: PHP program to check an array is multidimensional or not using rsort function. <?php$myarray = array( // Default key for each will // start from 0 array("Geeks", "For", "Geeks"), array("Hello", "World") ); // Function to check array is// multi-dimensional or notfunction is_multi_array( $arr ) { rsort( $arr ); return isset( $arr[0] ) && is_array( $arr[0] );} // Display resultvar_dump( is_multi_array( $myarray ) );?> bool(true) Example 2: Another PHP program to check an array is multidimensional or not using count function. <?php// Declare an array$geeks = array(1 => 'a', 2 => 'b', 3 => array("Learn", "Contribute", "Explore"));$gfg = array(1 => 'a', 2 => 'b'); // Function to check array is// multi-dimensional or notfunction is_multi($geeks) { $rv = array_filter($geeks, 'is_array'); if(count($rv)>0) return true; return false;} // Display resultvar_dump(is_multi($geeks));var_dump(is_multi($gfg));?> bool(true) bool(false) Note: Try to avoid use count and count_recursive to check that the array is multi-dimension or not cause you may don’t know to weather the array containing a sub-array or not which is empty. PHP-array Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jul, 2019" }, { "code": null, "e": 748, "s": 28, "text": "Given an array (single-dimensional or multi-dimensional) and the task is to check the given array is multi-dimensional or not. There are few methods to check an array is multi-dimensional or not. The function count() and count_recursive() will give wrong result if the array containing a sub-array which is empty, and the other one is using the rsort() function. This function sorts all the sub-arrays towards the beginning of the parent array and re-indexes the array. This ensures that if there are one or more sub-arrays inside the parent array, the first element of the parent array (at index 0) will always be an array. Checking for the element at index 0, we can tell whether the array is multidimensional or not." }, { "code": null, "e": 756, "s": 748, "text": "Syntax:" }, { "code": null, "e": 772, "s": 756, "text": "rsort( $array )" }, { "code": null, "e": 828, "s": 772, "text": "Parameters: The rsort() function accepts one parameter." }, { "code": null, "e": 889, "s": 828, "text": "$array: This is the object you want to pass to the function." }, { "code": null, "e": 979, "s": 889, "text": "Example 1: PHP program to check an array is multidimensional or not using rsort function." }, { "code": "<?php$myarray = array( // Default key for each will // start from 0 array(\"Geeks\", \"For\", \"Geeks\"), array(\"Hello\", \"World\") ); // Function to check array is// multi-dimensional or notfunction is_multi_array( $arr ) { rsort( $arr ); return isset( $arr[0] ) && is_array( $arr[0] );} // Display resultvar_dump( is_multi_array( $myarray ) );?>", "e": 1350, "s": 979, "text": null }, { "code": null, "e": 1362, "s": 1350, "text": "bool(true)\n" }, { "code": null, "e": 1460, "s": 1362, "text": "Example 2: Another PHP program to check an array is multidimensional or not using count function." }, { "code": "<?php// Declare an array$geeks = array(1 => 'a', 2 => 'b', 3 => array(\"Learn\", \"Contribute\", \"Explore\"));$gfg = array(1 => 'a', 2 => 'b'); // Function to check array is// multi-dimensional or notfunction is_multi($geeks) { $rv = array_filter($geeks, 'is_array'); if(count($rv)>0) return true; return false;} // Display resultvar_dump(is_multi($geeks));var_dump(is_multi($gfg));?>", "e": 1869, "s": 1460, "text": null }, { "code": null, "e": 1893, "s": 1869, "text": "bool(true)\nbool(false)\n" }, { "code": null, "e": 2084, "s": 1893, "text": "Note: Try to avoid use count and count_recursive to check that the array is multi-dimension or not cause you may don’t know to weather the array containing a sub-array or not which is empty." }, { "code": null, "e": 2094, "s": 2084, "text": "PHP-array" }, { "code": null, "e": 2101, "s": 2094, "text": "Picked" }, { "code": null, "e": 2105, "s": 2101, "text": "PHP" }, { "code": null, "e": 2118, "s": 2105, "text": "PHP Programs" }, { "code": null, "e": 2135, "s": 2118, "text": "Web Technologies" }, { "code": null, "e": 2139, "s": 2135, "text": "PHP" } ]
How to use Array Reverse Sort Functions for Integer and Strings in Golang?
17 May, 2020 Go language provides inbuilt support implementation of basic constants and run-time reflection to operate sort package. Golang is the ability for functions to run independently of each other. With the help of this function we can easily sort integer and string by importing “sort” package. Basically, this will sort the Integer and Strings in Reverse order. Syntax: func Reverse(data Interface) Interface Return Value: This function returns the value of IntSlice and StringSlice value. Below examples illustrate the use of the above method in Golang: Example 1: // Golang program to show the uses of// Integer Reverse Sort Function package main import ( "fmt" "sort") func main() { fmt.Println("Example For Integer Reverse Sort") num := []int{70, 80, 20, 50, 10} // using the function sort.Sort(sort.Reverse(sort.IntSlice(num))) fmt.Println(num) } Output: Example For Integer Reverse Sort [80 70 50 20 10] Example 2: // Golang program to show the uses of// String Reverse Sort Function package main import ( "fmt" "sort") func main() { fmt.Println("Example For String Reverse Sort") str:= []string{"GFG","Rank","India","Amid","Covid19"} // using the function sort.Sort(sort.Reverse(sort.StringSlice(str))) fmt.Println(str) } Output: Example For String Reverse Sort [Rank India GFG Covid19 Amid] Golang-Program Golang-String Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? Constants- Go Language Go Variables Loops in Go Language Time Durations in Golang Structures in Golang Strings in Golang How to iterate over an Array using for loop in Golang? time.Parse() Function in Golang With Examples Golang | Goroutine vs Thread
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2020" }, { "code": null, "e": 386, "s": 28, "text": "Go language provides inbuilt support implementation of basic constants and run-time reflection to operate sort package. Golang is the ability for functions to run independently of each other. With the help of this function we can easily sort integer and string by importing “sort” package. Basically, this will sort the Integer and Strings in Reverse order." }, { "code": null, "e": 394, "s": 386, "text": "Syntax:" }, { "code": null, "e": 433, "s": 394, "text": "func Reverse(data Interface) Interface" }, { "code": null, "e": 514, "s": 433, "text": "Return Value: This function returns the value of IntSlice and StringSlice value." }, { "code": null, "e": 579, "s": 514, "text": "Below examples illustrate the use of the above method in Golang:" }, { "code": null, "e": 590, "s": 579, "text": "Example 1:" }, { "code": "// Golang program to show the uses of// Integer Reverse Sort Function package main import ( \"fmt\" \"sort\") func main() { fmt.Println(\"Example For Integer Reverse Sort\") num := []int{70, 80, 20, 50, 10} // using the function sort.Sort(sort.Reverse(sort.IntSlice(num))) fmt.Println(num) }", "e": 907, "s": 590, "text": null }, { "code": null, "e": 915, "s": 907, "text": "Output:" }, { "code": null, "e": 966, "s": 915, "text": "Example For Integer Reverse Sort\n[80 70 50 20 10]\n" }, { "code": null, "e": 977, "s": 966, "text": "Example 2:" }, { "code": "// Golang program to show the uses of// String Reverse Sort Function package main import ( \"fmt\" \"sort\") func main() { fmt.Println(\"Example For String Reverse Sort\") str:= []string{\"GFG\",\"Rank\",\"India\",\"Amid\",\"Covid19\"} // using the function sort.Sort(sort.Reverse(sort.StringSlice(str))) fmt.Println(str) }", "e": 1316, "s": 977, "text": null }, { "code": null, "e": 1324, "s": 1316, "text": "Output:" }, { "code": null, "e": 1387, "s": 1324, "text": "Example For String Reverse Sort\n[Rank India GFG Covid19 Amid]\n" }, { "code": null, "e": 1402, "s": 1387, "text": "Golang-Program" }, { "code": null, "e": 1416, "s": 1402, "text": "Golang-String" }, { "code": null, "e": 1423, "s": 1416, "text": "Picked" }, { "code": null, "e": 1435, "s": 1423, "text": "Go Language" }, { "code": null, "e": 1533, "s": 1435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1562, "s": 1533, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 1585, "s": 1562, "text": "Constants- Go Language" }, { "code": null, "e": 1598, "s": 1585, "text": "Go Variables" }, { "code": null, "e": 1619, "s": 1598, "text": "Loops in Go Language" }, { "code": null, "e": 1644, "s": 1619, "text": "Time Durations in Golang" }, { "code": null, "e": 1665, "s": 1644, "text": "Structures in Golang" }, { "code": null, "e": 1683, "s": 1665, "text": "Strings in Golang" }, { "code": null, "e": 1738, "s": 1683, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 1784, "s": 1738, "text": "time.Parse() Function in Golang With Examples" } ]
React Native Tab Navigation Component
14 Jun, 2021 In this article, we are going to see how to implement Tab Navigation in react-native. For this, we are going to use createBottomTabNavigator component. It is basically used for navigation from one page to another. These days mobile apps are made up of a single screen, so create various navigation components in React Native. We want to use React Navigation. Syntax: const Tab = createBottomTabNavigator(); <Tab.Navigator > <Tab.Screen/> </Tab.Navigator> Props in Tab Navigation: initialRouteName: It is the initial route that opens when the application loads. order: It basically sets the order of the tabs. paths: It controls the mapping of the route screen to path config. lazy: If its value is true, then the tab is rendered when it becomes active for the first time. Its default value is true. tabBarComponent: It is an optional prop. It overrides the component which is used as a tab bar. tabBarOptions: It is an object of many properties like tabStyle , showLabel, showIcon, style, etc... Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init myapp Step 2: Now create a project by the following command. expo init myapp Step 3: Now go into your project folder i.e. myappcd myapp Step 3: Now go into your project folder i.e. myapp cd myapp Step 4: Now install react-navigation into your project. React Navigation is used to navigate between one page to another. Install it by using the following command.npm install @react-navigation/native Step 4: Now install react-navigation into your project. React Navigation is used to navigate between one page to another. Install it by using the following command. npm install @react-navigation/native Step 5: Now install dependencies into your react-native project by using the following command.npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view Step 5: Now install dependencies into your react-native project by using the following command. npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view Step 6: Now install bottom-tabs from react-navigation.npm install @react-navigation/bottom-tabs Step 6: Now install bottom-tabs from react-navigation. npm install @react-navigation/bottom-tabs For React Tab Navigation: This can be used in React Native as well https://reactnavigation.org/docs/tab-based-navigation/ Project Structure: Example: Now let’s implement Tab Navigation. App.js import * as React from 'react';import { Text, View } from 'react-native';import { NavigationContainer } from '@react-navigation/native';import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; function Home() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Home!</Text> </View> );} function Setting() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Settings!</Text> </View> );} function Notification() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Text>Notifications!</Text> </View> );} const Tab = createBottomTabNavigator(); export default function App() { return ( <NavigationContainer > <Tab.Navigator initialRouteName={Home} > <Tab.Screen name="Home" component={Home} /> <Tab.Screen name="Notifications" component={Notification} /> <Tab.Screen name="Settings" component={Setting} /> </Tab.Navigator> </NavigationContainer> );} Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Reference: https://reactnative.dev/docs/navigation#react-navigation Picked React-Native React-Native Component JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jun, 2021" }, { "code": null, "e": 387, "s": 28, "text": "In this article, we are going to see how to implement Tab Navigation in react-native. For this, we are going to use createBottomTabNavigator component. It is basically used for navigation from one page to another. These days mobile apps are made up of a single screen, so create various navigation components in React Native. We want to use React Navigation." }, { "code": null, "e": 395, "s": 387, "text": "Syntax:" }, { "code": null, "e": 486, "s": 395, "text": "const Tab = createBottomTabNavigator();\n<Tab.Navigator >\n <Tab.Screen/>\n</Tab.Navigator>" }, { "code": null, "e": 511, "s": 486, "text": "Props in Tab Navigation:" }, { "code": null, "e": 592, "s": 511, "text": "initialRouteName: It is the initial route that opens when the application loads." }, { "code": null, "e": 640, "s": 592, "text": "order: It basically sets the order of the tabs." }, { "code": null, "e": 707, "s": 640, "text": "paths: It controls the mapping of the route screen to path config." }, { "code": null, "e": 830, "s": 707, "text": "lazy: If its value is true, then the tab is rendered when it becomes active for the first time. Its default value is true." }, { "code": null, "e": 926, "s": 830, "text": "tabBarComponent: It is an optional prop. It overrides the component which is used as a tab bar." }, { "code": null, "e": 1027, "s": 926, "text": "tabBarOptions: It is an object of many properties like tabStyle , showLabel, showIcon, style, etc..." }, { "code": null, "e": 1070, "s": 1029, "text": "Now let’s start with the implementation:" }, { "code": null, "e": 1167, "s": 1070, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 1241, "s": 1167, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 1265, "s": 1241, "text": "npm install -g expo-cli" }, { "code": null, "e": 1335, "s": 1265, "text": "Step 2: Now create a project by the following command.expo init myapp" }, { "code": null, "e": 1390, "s": 1335, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 1406, "s": 1390, "text": "expo init myapp" }, { "code": null, "e": 1465, "s": 1406, "text": "Step 3: Now go into your project folder i.e. myappcd myapp" }, { "code": null, "e": 1516, "s": 1465, "text": "Step 3: Now go into your project folder i.e. myapp" }, { "code": null, "e": 1525, "s": 1516, "text": "cd myapp" }, { "code": null, "e": 1726, "s": 1525, "text": "Step 4: Now install react-navigation into your project. React Navigation is used to navigate between one page to another. Install it by using the following command.npm install @react-navigation/native" }, { "code": null, "e": 1891, "s": 1726, "text": "Step 4: Now install react-navigation into your project. React Navigation is used to navigate between one page to another. Install it by using the following command." }, { "code": null, "e": 1928, "s": 1891, "text": "npm install @react-navigation/native" }, { "code": null, "e": 2176, "s": 1928, "text": "Step 5: Now install dependencies into your react-native project by using the following command.npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view" }, { "code": null, "e": 2272, "s": 2176, "text": "Step 5: Now install dependencies into your react-native project by using the following command." }, { "code": null, "e": 2425, "s": 2272, "text": "npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view" }, { "code": null, "e": 2523, "s": 2427, "text": "Step 6: Now install bottom-tabs from react-navigation.npm install @react-navigation/bottom-tabs" }, { "code": null, "e": 2578, "s": 2523, "text": "Step 6: Now install bottom-tabs from react-navigation." }, { "code": null, "e": 2620, "s": 2578, "text": "npm install @react-navigation/bottom-tabs" }, { "code": null, "e": 2687, "s": 2620, "text": "For React Tab Navigation: This can be used in React Native as well" }, { "code": null, "e": 2742, "s": 2687, "text": "https://reactnavigation.org/docs/tab-based-navigation/" }, { "code": null, "e": 2761, "s": 2742, "text": "Project Structure:" }, { "code": null, "e": 2806, "s": 2761, "text": "Example: Now let’s implement Tab Navigation." }, { "code": null, "e": 2813, "s": 2806, "text": "App.js" }, { "code": "import * as React from 'react';import { Text, View } from 'react-native';import { NavigationContainer } from '@react-navigation/native';import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; function Home() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Home!</Text> </View> );} function Setting() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Settings!</Text> </View> );} function Notification() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Text>Notifications!</Text> </View> );} const Tab = createBottomTabNavigator(); export default function App() { return ( <NavigationContainer > <Tab.Navigator initialRouteName={Home} > <Tab.Screen name=\"Home\" component={Home} /> <Tab.Screen name=\"Notifications\" component={Notification} /> <Tab.Screen name=\"Settings\" component={Setting} /> </Tab.Navigator> </NavigationContainer> );}", "e": 3968, "s": 2813, "text": null }, { "code": null, "e": 4017, "s": 3968, "text": "Start the server by using the following command." }, { "code": null, "e": 4033, "s": 4017, "text": "npm run android" }, { "code": null, "e": 4202, "s": 4033, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. " }, { "code": null, "e": 4270, "s": 4202, "text": "Reference: https://reactnative.dev/docs/navigation#react-navigation" }, { "code": null, "e": 4277, "s": 4270, "text": "Picked" }, { "code": null, "e": 4290, "s": 4277, "text": "React-Native" }, { "code": null, "e": 4313, "s": 4290, "text": "React-Native Component" }, { "code": null, "e": 4324, "s": 4313, "text": "JavaScript" }, { "code": null, "e": 4341, "s": 4324, "text": "Web Technologies" }, { "code": null, "e": 4439, "s": 4341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4500, "s": 4439, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4540, "s": 4500, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4582, "s": 4540, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4623, "s": 4582, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4645, "s": 4623, "text": "JavaScript | Promises" }, { "code": null, "e": 4678, "s": 4645, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4740, "s": 4678, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4801, "s": 4740, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4851, "s": 4801, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to change opacity while scrolling the page?
04 Oct, 2019 jQuery is used to control and change the opacity during the scrolling of web page. Create a web pages to change the opacity while scrolling the page. The jQuery scroll function is used to scroll the web page and set opacity of text content.Example: <!-- HTML code to change the opacity of web page when scrolling it --><!DOCTYPE html><html> <head> <title> Change the opacity during scroll </title> <style> /* Margin and Padding is set to zero so the body can occupy the full screen page */ body { margin: 0; padding: 0; background: green; } /* To put the header in the center of the page we used justify-content and align-items and set their value as center, You can add any background image */ .header-bg { position: fixed; top:0; left:0; width: 100%; height: 300px; justify-content: center; align-items: center; display: flex; } /* Box shadow provides shadow effect to the element */ .header-bg h2 { margin: 0; padding: 0; color: #000; text-align: center; padding: 20px; max-width: 80%; } /* Set "position:relative" then section can move from its original position, by using position:relative, the position of the section is not dependent on the container. The box-sizing property is used to include the padding and border in an element */ section { position: relative; top:100vh; padding: 100px; width: 100%; min-height: 100vh; box-sizing: border-box; } section h2 { text-align:center; margin: 0 0 50px; padding: 0; font-size: 40px; color: #fff; } section p { text-align:center; color: #fff; font-size: 1.3em; } </style></head> <body> <div class="header-bg"> <h2>Change Opactity on Scroll</h2> </div> <section> <h2>GeeksforGeeks</h2> <p> A computer science portal for geeks </p> </section> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to change opacity when scrolling the web page --> <script> $(document).ready(function(){ $(window).scroll(function(){ $('.header-bg').css("opacity", 1- $(window).scrollTop() / 700) }) }) </script></body> </html> Output: ManasChhabra2 CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Oct, 2019" }, { "code": null, "e": 277, "s": 28, "text": "jQuery is used to control and change the opacity during the scrolling of web page. Create a web pages to change the opacity while scrolling the page. The jQuery scroll function is used to scroll the web page and set opacity of text content.Example:" }, { "code": "<!-- HTML code to change the opacity of web page when scrolling it --><!DOCTYPE html><html> <head> <title> Change the opacity during scroll </title> <style> /* Margin and Padding is set to zero so the body can occupy the full screen page */ body { margin: 0; padding: 0; background: green; } /* To put the header in the center of the page we used justify-content and align-items and set their value as center, You can add any background image */ .header-bg { position: fixed; top:0; left:0; width: 100%; height: 300px; justify-content: center; align-items: center; display: flex; } /* Box shadow provides shadow effect to the element */ .header-bg h2 { margin: 0; padding: 0; color: #000; text-align: center; padding: 20px; max-width: 80%; } /* Set \"position:relative\" then section can move from its original position, by using position:relative, the position of the section is not dependent on the container. The box-sizing property is used to include the padding and border in an element */ section { position: relative; top:100vh; padding: 100px; width: 100%; min-height: 100vh; box-sizing: border-box; } section h2 { text-align:center; margin: 0 0 50px; padding: 0; font-size: 40px; color: #fff; } section p { text-align:center; color: #fff; font-size: 1.3em; } </style></head> <body> <div class=\"header-bg\"> <h2>Change Opactity on Scroll</h2> </div> <section> <h2>GeeksforGeeks</h2> <p> A computer science portal for geeks </p> </section> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to change opacity when scrolling the web page --> <script> $(document).ready(function(){ $(window).scroll(function(){ $('.header-bg').css(\"opacity\", 1- $(window).scrollTop() / 700) }) }) </script></body> </html> ", "e": 2785, "s": 277, "text": null }, { "code": null, "e": 2793, "s": 2785, "text": "Output:" }, { "code": null, "e": 2807, "s": 2793, "text": "ManasChhabra2" }, { "code": null, "e": 2811, "s": 2807, "text": "CSS" }, { "code": null, "e": 2816, "s": 2811, "text": "HTML" }, { "code": null, "e": 2823, "s": 2816, "text": "JQuery" }, { "code": null, "e": 2840, "s": 2823, "text": "Web Technologies" }, { "code": null, "e": 2867, "s": 2840, "text": "Web technologies Questions" }, { "code": null, "e": 2872, "s": 2867, "text": "HTML" }, { "code": null, "e": 2970, "s": 2872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3007, "s": 2970, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3046, "s": 3007, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3085, "s": 3046, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3149, "s": 3085, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 3210, "s": 3149, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 3234, "s": 3210, "text": "REST API (Introduction)" }, { "code": null, "e": 3287, "s": 3234, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3347, "s": 3287, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3384, "s": 3347, "text": "Types of CSS (Cascading Style Sheet)" } ]
Round the given number to nearest multiple of 10
15 Jun, 2022 Given a positive integer n, round it to nearest whole number having zero as last digit. Examples: Input : 4722 Output : 4720 Input : 38 Output : 40 Input : 10 Output: 10 Approach: Let’s round down the given number n to the nearest integer which ends with 0 and store this value in a variable a. a = (n / 10) * 10. So, the round up n (call it b) is b = a + 10.If n – a > b – n then the answer is b otherwise the answer is a. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to round the given// integer to a whole number// which ends with zero.#include <bits/stdc++.h>using namespace std; // function to round the numberint round(int n){ // Smaller multiple int a = (n / 10) * 10; // Larger multiple int b = a + 10; // Return of closest of two return (n - a > b - n)? b : a;} // driver functionint main(){ int n = 4722; cout << round(n) << endl; return 0;} // Java Code for Round the given number// to nearest multiple of 10import java.util.*; class GFG { // function to round the number static int round(int n) { // Smaller multiple int a = (n / 10) * 10; // Larger multiple int b = a + 10; // Return of closest of two return (n - a > b - n)? b : a; } /* Driver program to test above function */ public static void main(String[] args) { int n = 4722; System.out.println(round(n)); }} // This code is contributed by Arnav Kr. Mandal. # Python3 code to round the given# integer to a whole number# which ends with zero. # function to round the numberdef round( n ): # Smaller multiple a = (n // 10) * 10 # Larger multiple b = a + 10 # Return of closest of two return (b if n - a > b - n else a) # driver coden = 4722print(round(n)) # This code is contributed by "Sharad_Bhardwaj". // C# Code for Round the given number// to nearest multiple of 10using System; class GFG { // function to round the number static int round(int n) { // Smaller multiple int a = (n / 10) * 10; // Larger multiple int b = a + 10; // Return of closest of two return (n - a > b - n)? b : a; } // Driver program public static void Main() { int n = 4722; Console.WriteLine(round(n)); }} // This code is contributed by Vt_m. <?php// PHP program to round the given integer// to a whole number which ends with zero. // function to round the numberfunction roundFunation($n){ // Smaller multiple $a = (int)($n / 10) * 10; // Larger multiple $b = ($a + 10); // Return of closest of two return ($n - $a > $b - $n) ? $b : $a;} // Driver Code$n = 4722;echo roundFunation($n), "\n"; // This code is contributed by ajit?> <script> // Javascript Code for Round the given number // to nearest multiple of 10 // function to round the number function round(n) { // Smaller multiple let a = parseInt(n / 10, 10) * 10; // Larger multiple let b = a + 10; // Return of closest of two return (n - a > b - n)? b : a; } let n = 4722; document.write(round(n)); // THIS CODE IS CONTRIBUTED BY MUKESH07.</script> Output: 4720 Time Complexity: O(1) Auxiliary Space: O(1) Another method if n is large:The above method is good only for Integer or Long MAX value. if the input length is greater then the int or long-range above method does not work. We can solve the problem using String. C++ Java Python3 C# Javascript // C++ code for above approach#include <bits/stdc++.h>using namespace std; // Program to round the number to the// nearest number having one's digit 0string Round(string s, int n){ string c = s; // last character is 0 then return the // original string if(c[n - 1] == '0') return s; // if last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if(c[n - 1] == '1' || c[n - 1] == '2' || c[n - 1] == '3' || c[n - 1] == '4' || c[n - 1] == '5' ) { c[n - 1] = '0'; return c; } else { c[n - 1] = '0'; // process carry for(int i = n - 2 ; i >= 0 ; i--) { if(c[i] == '9') c[i] = '0'; else { int t = c[i] - '0' + 1; c[i] = (char)(48 + t); break; } } } string s1 = c; if(s1[0] == '0') s1 = "1" + s1; // return final string return s1;} // Driver codeint main(){ string s="5748965412485599999874589965999"; int n=s.length(); // Function Call cout << Round(s,n) << endl; return 0;} // This code is contributed by divyeshrabadiya07 // Java code for above approachimport java.io.*; class GFG{ // Program to round the number to the // nearest number having one's digit 0 public static String round(String s, int n) { char[] c=s.toCharArray(); // last character is 0 then return the // original string if(c[n-1]=='0') return s; // if last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if(c[n-1] == '1' || c[n-1] == '2' || c[n-1] == '3' || c[n-1] == '4' || c[n-1] == '5' ) { c[n-1]='0'; return new String(c); } else { c[n-1]='0'; // process carry for(int i = n - 2 ; i >= 0 ; i--) { if(c[i] == '9') c[i]='0'; else { int t= c[i] - '0' + 1; c[i]=(char)(48+t); break; } } } String s1=new String(c); if(s1.charAt(0) == '0') s1="1"+s1; // return final string return s1; } // Driver Code public static void main (String[] args) { String s="5748965412485599999874589965999"; int n=s.length(); // Function Call System.out.println(round(s,n)); }} # Python3 code for above approach # Function to round the number to the# nearest number having one's digit 0def Round(s, n): s = list(s) c = s.copy() # Last character is 0 then return the # original string if (c[n - 1] == '0'): return ("".join(s)) # If last character is # 1 or 2 or 3 or 4 or 5 make it 0 elif (c[n - 1] == '1' or c[n - 1] == '2' or c[n - 1] == '3' or c[n - 1] == '4' or c[n - 1] == '5'): c[n - 1] = '0' return ("".join(c)) else: c[n - 1] = '0' # Process carry for i in range(n - 2, -1, -1): if (c[i] == '9'): c[i] = '0' else: t = ord(c[i]) - ord('0') + 1 c[i] = chr(48 + t) break s1 = "".join(c) if (s1[0] == '0'): s1 = "1" + s1 # Return final string return s1 # Driver codes = "5748965412485599999874589965999"n = len(s) print(Round(s, n)) # This code is contributed by rag2127 // C# code for above approachusing System;class GFG { // Program to round the number to the // nearest number having one's digit 0 static string round(string s, int n) { char[] c = s.ToCharArray(); // last character is 0 then return the // original string if(c[n - 1] == '0') return s; // if last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if(c[n - 1] == '1' || c[n - 1] == '2' || c[n - 1] == '3' || c[n - 1] == '4' || c[n - 1] == '5' ) { c[n - 1] = '0'; return new string(c); } else { c[n - 1] = '0'; // process carry for(int i = n - 2 ; i >= 0 ; i--) { if(c[i] == '9') c[i] = '0'; else { int t = c[i] - '0' + 1; c[i] = (char)(48 + t); break; } } } string s1 = new string(c); if(s1[0] == '0') s1 = "1" + s1; // return final string return s1; } static void Main() { string s="5748965412485599999874589965999"; int n=s.Length; // Function Call Console.WriteLine(round(s,n)); }} // This code is contributed by divyesh072019 <script> // Javascript code for above approach // Program to round the number to the// nearest number having one's digit 0function round(s, n){ let c = s.split(''); // Last character is 0 then return the // original string if (c[n - 1] == '0') return s; // If last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if (c[n - 1] == '1' || c[n - 1] == '2' || c[n - 1] == '3' || c[n - 1] == '4' || c[n - 1] == '5' ) { c[n - 1] = '0'; return c.join(""); } else { c[n - 1] = '0'; // process carry for(let i = n - 2 ; i >= 0 ; i--) { if (c[i] == '9') c[i] = '0'; else { let t = c[i].charCodeAt() - '0'.charCodeAt() + 1; c[i] = String.fromCharCode(48 + t); break; } } } let s1 = c.join(""); if (s1[0] == '0') s1 = "1" + s1; // Return final string return s1;} // Driver code let s = "5748965412485599999874589965999";let n = s.length; // Function Calldocument.write(round(s,n)); // This code is contributed by rameshtravel07 </script> 5748965412485599999874589966000 Time Complexity: O(N) where N is length of string. Auxiliary Space: O(1) jit_t amitroy9615 divyesh072019 divyeshrabadiya07 rag2127 mukesh07 rameshtravel07 tarakki100 Mathematical School Programming Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jun, 2022" }, { "code": null, "e": 141, "s": 53, "text": "Given a positive integer n, round it to nearest whole number having zero as last digit." }, { "code": null, "e": 152, "s": 141, "text": "Examples: " }, { "code": null, "e": 226, "s": 152, "text": "Input : 4722\nOutput : 4720\n\nInput : 38\nOutput : 40\n\nInput : 10\nOutput: 10" }, { "code": null, "e": 480, "s": 226, "text": "Approach: Let’s round down the given number n to the nearest integer which ends with 0 and store this value in a variable a. a = (n / 10) * 10. So, the round up n (call it b) is b = a + 10.If n – a > b – n then the answer is b otherwise the answer is a." }, { "code": null, "e": 533, "s": 480, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 537, "s": 533, "text": "C++" }, { "code": null, "e": 542, "s": 537, "text": "Java" }, { "code": null, "e": 550, "s": 542, "text": "Python3" }, { "code": null, "e": 553, "s": 550, "text": "C#" }, { "code": null, "e": 557, "s": 553, "text": "PHP" }, { "code": null, "e": 568, "s": 557, "text": "Javascript" }, { "code": "// C++ program to round the given// integer to a whole number// which ends with zero.#include <bits/stdc++.h>using namespace std; // function to round the numberint round(int n){ // Smaller multiple int a = (n / 10) * 10; // Larger multiple int b = a + 10; // Return of closest of two return (n - a > b - n)? b : a;} // driver functionint main(){ int n = 4722; cout << round(n) << endl; return 0;}", "e": 999, "s": 568, "text": null }, { "code": "// Java Code for Round the given number// to nearest multiple of 10import java.util.*; class GFG { // function to round the number static int round(int n) { // Smaller multiple int a = (n / 10) * 10; // Larger multiple int b = a + 10; // Return of closest of two return (n - a > b - n)? b : a; } /* Driver program to test above function */ public static void main(String[] args) { int n = 4722; System.out.println(round(n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 1584, "s": 999, "text": null }, { "code": "# Python3 code to round the given# integer to a whole number# which ends with zero. # function to round the numberdef round( n ): # Smaller multiple a = (n // 10) * 10 # Larger multiple b = a + 10 # Return of closest of two return (b if n - a > b - n else a) # driver coden = 4722print(round(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 1958, "s": 1584, "text": null }, { "code": "// C# Code for Round the given number// to nearest multiple of 10using System; class GFG { // function to round the number static int round(int n) { // Smaller multiple int a = (n / 10) * 10; // Larger multiple int b = a + 10; // Return of closest of two return (n - a > b - n)? b : a; } // Driver program public static void Main() { int n = 4722; Console.WriteLine(round(n)); }} // This code is contributed by Vt_m.", "e": 2479, "s": 1958, "text": null }, { "code": "<?php// PHP program to round the given integer// to a whole number which ends with zero. // function to round the numberfunction roundFunation($n){ // Smaller multiple $a = (int)($n / 10) * 10; // Larger multiple $b = ($a + 10); // Return of closest of two return ($n - $a > $b - $n) ? $b : $a;} // Driver Code$n = 4722;echo roundFunation($n), \"\\n\"; // This code is contributed by ajit?>", "e": 2895, "s": 2479, "text": null }, { "code": "<script> // Javascript Code for Round the given number // to nearest multiple of 10 // function to round the number function round(n) { // Smaller multiple let a = parseInt(n / 10, 10) * 10; // Larger multiple let b = a + 10; // Return of closest of two return (n - a > b - n)? b : a; } let n = 4722; document.write(round(n)); // THIS CODE IS CONTRIBUTED BY MUKESH07.</script>", "e": 3382, "s": 2895, "text": null }, { "code": null, "e": 3391, "s": 3382, "text": "Output: " }, { "code": null, "e": 3396, "s": 3391, "text": "4720" }, { "code": null, "e": 3418, "s": 3396, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3440, "s": 3418, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3616, "s": 3440, "text": "Another method if n is large:The above method is good only for Integer or Long MAX value. if the input length is greater then the int or long-range above method does not work." }, { "code": null, "e": 3655, "s": 3616, "text": "We can solve the problem using String." }, { "code": null, "e": 3659, "s": 3655, "text": "C++" }, { "code": null, "e": 3664, "s": 3659, "text": "Java" }, { "code": null, "e": 3672, "s": 3664, "text": "Python3" }, { "code": null, "e": 3675, "s": 3672, "text": "C#" }, { "code": null, "e": 3686, "s": 3675, "text": "Javascript" }, { "code": "// C++ code for above approach#include <bits/stdc++.h>using namespace std; // Program to round the number to the// nearest number having one's digit 0string Round(string s, int n){ string c = s; // last character is 0 then return the // original string if(c[n - 1] == '0') return s; // if last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if(c[n - 1] == '1' || c[n - 1] == '2' || c[n - 1] == '3' || c[n - 1] == '4' || c[n - 1] == '5' ) { c[n - 1] = '0'; return c; } else { c[n - 1] = '0'; // process carry for(int i = n - 2 ; i >= 0 ; i--) { if(c[i] == '9') c[i] = '0'; else { int t = c[i] - '0' + 1; c[i] = (char)(48 + t); break; } } } string s1 = c; if(s1[0] == '0') s1 = \"1\" + s1; // return final string return s1;} // Driver codeint main(){ string s=\"5748965412485599999874589965999\"; int n=s.length(); // Function Call cout << Round(s,n) << endl; return 0;} // This code is contributed by divyeshrabadiya07", "e": 4842, "s": 3686, "text": null }, { "code": "// Java code for above approachimport java.io.*; class GFG{ // Program to round the number to the // nearest number having one's digit 0 public static String round(String s, int n) { char[] c=s.toCharArray(); // last character is 0 then return the // original string if(c[n-1]=='0') return s; // if last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if(c[n-1] == '1' || c[n-1] == '2' || c[n-1] == '3' || c[n-1] == '4' || c[n-1] == '5' ) { c[n-1]='0'; return new String(c); } else { c[n-1]='0'; // process carry for(int i = n - 2 ; i >= 0 ; i--) { if(c[i] == '9') c[i]='0'; else { int t= c[i] - '0' + 1; c[i]=(char)(48+t); break; } } } String s1=new String(c); if(s1.charAt(0) == '0') s1=\"1\"+s1; // return final string return s1; } // Driver Code public static void main (String[] args) { String s=\"5748965412485599999874589965999\"; int n=s.length(); // Function Call System.out.println(round(s,n)); }}", "e": 5982, "s": 4842, "text": null }, { "code": "# Python3 code for above approach # Function to round the number to the# nearest number having one's digit 0def Round(s, n): s = list(s) c = s.copy() # Last character is 0 then return the # original string if (c[n - 1] == '0'): return (\"\".join(s)) # If last character is # 1 or 2 or 3 or 4 or 5 make it 0 elif (c[n - 1] == '1' or c[n - 1] == '2' or c[n - 1] == '3' or c[n - 1] == '4' or c[n - 1] == '5'): c[n - 1] = '0' return (\"\".join(c)) else: c[n - 1] = '0' # Process carry for i in range(n - 2, -1, -1): if (c[i] == '9'): c[i] = '0' else: t = ord(c[i]) - ord('0') + 1 c[i] = chr(48 + t) break s1 = \"\".join(c) if (s1[0] == '0'): s1 = \"1\" + s1 # Return final string return s1 # Driver codes = \"5748965412485599999874589965999\"n = len(s) print(Round(s, n)) # This code is contributed by rag2127", "e": 7013, "s": 5982, "text": null }, { "code": "// C# code for above approachusing System;class GFG { // Program to round the number to the // nearest number having one's digit 0 static string round(string s, int n) { char[] c = s.ToCharArray(); // last character is 0 then return the // original string if(c[n - 1] == '0') return s; // if last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if(c[n - 1] == '1' || c[n - 1] == '2' || c[n - 1] == '3' || c[n - 1] == '4' || c[n - 1] == '5' ) { c[n - 1] = '0'; return new string(c); } else { c[n - 1] = '0'; // process carry for(int i = n - 2 ; i >= 0 ; i--) { if(c[i] == '9') c[i] = '0'; else { int t = c[i] - '0' + 1; c[i] = (char)(48 + t); break; } } } string s1 = new string(c); if(s1[0] == '0') s1 = \"1\" + s1; // return final string return s1; } static void Main() { string s=\"5748965412485599999874589965999\"; int n=s.Length; // Function Call Console.WriteLine(round(s,n)); }} // This code is contributed by divyesh072019", "e": 8183, "s": 7013, "text": null }, { "code": "<script> // Javascript code for above approach // Program to round the number to the// nearest number having one's digit 0function round(s, n){ let c = s.split(''); // Last character is 0 then return the // original string if (c[n - 1] == '0') return s; // If last character is // 1 or 2 or 3 or 4 or 5 make it 0 else if (c[n - 1] == '1' || c[n - 1] == '2' || c[n - 1] == '3' || c[n - 1] == '4' || c[n - 1] == '5' ) { c[n - 1] = '0'; return c.join(\"\"); } else { c[n - 1] = '0'; // process carry for(let i = n - 2 ; i >= 0 ; i--) { if (c[i] == '9') c[i] = '0'; else { let t = c[i].charCodeAt() - '0'.charCodeAt() + 1; c[i] = String.fromCharCode(48 + t); break; } } } let s1 = c.join(\"\"); if (s1[0] == '0') s1 = \"1\" + s1; // Return final string return s1;} // Driver code let s = \"5748965412485599999874589965999\";let n = s.length; // Function Calldocument.write(round(s,n)); // This code is contributed by rameshtravel07 </script>", "e": 9413, "s": 8183, "text": null }, { "code": null, "e": 9445, "s": 9413, "text": "5748965412485599999874589966000" }, { "code": null, "e": 9496, "s": 9445, "text": "Time Complexity: O(N) where N is length of string." }, { "code": null, "e": 9519, "s": 9496, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 9525, "s": 9519, "text": "jit_t" }, { "code": null, "e": 9537, "s": 9525, "text": "amitroy9615" }, { "code": null, "e": 9551, "s": 9537, "text": "divyesh072019" }, { "code": null, "e": 9569, "s": 9551, "text": "divyeshrabadiya07" }, { "code": null, "e": 9577, "s": 9569, "text": "rag2127" }, { "code": null, "e": 9586, "s": 9577, "text": "mukesh07" }, { "code": null, "e": 9601, "s": 9586, "text": "rameshtravel07" }, { "code": null, "e": 9612, "s": 9601, "text": "tarakki100" }, { "code": null, "e": 9625, "s": 9612, "text": "Mathematical" }, { "code": null, "e": 9644, "s": 9625, "text": "School Programming" }, { "code": null, "e": 9652, "s": 9644, "text": "Strings" }, { "code": null, "e": 9660, "s": 9652, "text": "Strings" }, { "code": null, "e": 9673, "s": 9660, "text": "Mathematical" }, { "code": null, "e": 9771, "s": 9673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9801, "s": 9771, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9844, "s": 9801, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9904, "s": 9844, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9919, "s": 9904, "text": "C++ Data Types" }, { "code": null, "e": 9943, "s": 9919, "text": "Merge two sorted arrays" }, { "code": null, "e": 9961, "s": 9943, "text": "Python Dictionary" }, { "code": null, "e": 9986, "s": 9961, "text": "Reverse a string in Java" }, { "code": null, "e": 10002, "s": 9986, "text": "Arrays in C/C++" }, { "code": null, "e": 10025, "s": 10002, "text": "Introduction To PYTHON" } ]
Solidity – Fall Back Function
11 May, 2022 The solidity fallback function is executed if none of the other functions match the function identifier or no data was provided with the function call. Only one unnamed function can be assigned to a contract and it is executed whenever the contract receives plain Ether without any data. To receive Ether and add it to the total balance of the contract, the fallback function must be marked payable. If no such function exists, the contract cannot receive Ether through regular transactions and will throw an exception. Properties of a fallback function: Has no name or arguments.If it is not marked payable, the contract will throw an exception if it receives plain ether without data.Can not return anything.Can be defined once per contract.It is also executed if the caller meant to call a function that is not availableIt is mandatory to mark it external.It is limited to 2300 gas when called by another function. It is so for as to make this function call as cheap as possible. Has no name or arguments. If it is not marked payable, the contract will throw an exception if it receives plain ether without data. Can not return anything. Can be defined once per contract. It is also executed if the caller meant to call a function that is not available It is mandatory to mark it external. It is limited to 2300 gas when called by another function. It is so for as to make this function call as cheap as possible. Example: In the below example, the Contract is created to demonstrate different conditions for different fallback function. Solidity pragma solidity ^0.4.0; // Creating a contractcontract GeeksForGeeks { // Declaring the state variable uint x; // Mapping of addresses to their balances mapping(address => uint) balance; // Creating a constructor constructor() public { // Set x to default // value of 10 x=10; } // Creating a function function SetX(uint _x) public returns(bool) { // Set x to the // value sent x=_x; return true; } // This fallback function // will keep all the Ether function() public payable { balance[msg.sender] += msg.value; }} // Creating the sender contractcontract Sender { function transfer() public payable { // Address of GeeksForGeeks contract address _receiver = 0xbcc0185441de06F0452D45AEd6Ad8b98017796fb; // Transfers 100 Eth to above contract _receiver.transfer(100); }} Output: Output 1. Contract GeeksForGeeks: It has a variable x which is set to the default value 10 in the constructor(). The contract has a function called SetX(uint _x) which sets the function value to the desired parameter sent during the function call. The below declaration creates address to value map called balance which maps the addresses to their balance. mapping(address => uint) balance; 2. Contract Sender: This is a completely independent and unrelated contract. It sends a value in Ether to the contract GeeksForGeeks. The contract does not know the mechanism of the GeeksForGeeks contract. Sending a transaction without any message and only Ether can cause an error.The below statements declare a variable _receiver of the address type. It explicitly stores the address of contract GeeksForGeeks. It then uses address.transfer(value) to transfer Ether to the contract. address _receiver = 0xbcc0185441de06F0452D45AEd6Ad8b98017796fb; //Address of GeeksForGeeks contract _receiver.transfer(100); 3. Function() public payable: The function below is a fallback function. It is declared payable which allows it to accept transfer value. It is called in two cases A contract receives only Ether and no data.No function calls matched even though the account received data. A contract receives only Ether and no data. No function calls matched even though the account received data. This helps us to protect the function from throwing an error. In this program, the contract GeeksForGeeks receives only Ether and the fallback function uses the value received to add to the balance related to the sending address. function() public payable { balance[msg.sender] += msg.value; } Solidity-Functions Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect ReactJS with MetaMask ? Introduction to Solidity How to Install Solidity in Windows? Proof of Work (PoW) Consensus Mathematical Operations in Solidity Introduction to Solidity How to Install Solidity in Windows? Mathematical Operations in Solidity Solidity - Inheritance Solidity - Libraries
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2022" }, { "code": null, "e": 548, "s": 28, "text": "The solidity fallback function is executed if none of the other functions match the function identifier or no data was provided with the function call. Only one unnamed function can be assigned to a contract and it is executed whenever the contract receives plain Ether without any data. To receive Ether and add it to the total balance of the contract, the fallback function must be marked payable. If no such function exists, the contract cannot receive Ether through regular transactions and will throw an exception." }, { "code": null, "e": 583, "s": 548, "text": "Properties of a fallback function:" }, { "code": null, "e": 1011, "s": 583, "text": "Has no name or arguments.If it is not marked payable, the contract will throw an exception if it receives plain ether without data.Can not return anything.Can be defined once per contract.It is also executed if the caller meant to call a function that is not availableIt is mandatory to mark it external.It is limited to 2300 gas when called by another function. It is so for as to make this function call as cheap as possible." }, { "code": null, "e": 1037, "s": 1011, "text": "Has no name or arguments." }, { "code": null, "e": 1144, "s": 1037, "text": "If it is not marked payable, the contract will throw an exception if it receives plain ether without data." }, { "code": null, "e": 1169, "s": 1144, "text": "Can not return anything." }, { "code": null, "e": 1203, "s": 1169, "text": "Can be defined once per contract." }, { "code": null, "e": 1284, "s": 1203, "text": "It is also executed if the caller meant to call a function that is not available" }, { "code": null, "e": 1321, "s": 1284, "text": "It is mandatory to mark it external." }, { "code": null, "e": 1445, "s": 1321, "text": "It is limited to 2300 gas when called by another function. It is so for as to make this function call as cheap as possible." }, { "code": null, "e": 1570, "s": 1445, "text": "Example: In the below example, the Contract is created to demonstrate different conditions for different fallback function. " }, { "code": null, "e": 1579, "s": 1570, "text": "Solidity" }, { "code": "pragma solidity ^0.4.0; // Creating a contractcontract GeeksForGeeks { // Declaring the state variable uint x; // Mapping of addresses to their balances mapping(address => uint) balance; // Creating a constructor constructor() public { // Set x to default // value of 10 x=10; } // Creating a function function SetX(uint _x) public returns(bool) { // Set x to the // value sent x=_x; return true; } // This fallback function // will keep all the Ether function() public payable { balance[msg.sender] += msg.value; }} // Creating the sender contractcontract Sender { function transfer() public payable { // Address of GeeksForGeeks contract address _receiver = 0xbcc0185441de06F0452D45AEd6Ad8b98017796fb; // Transfers 100 Eth to above contract _receiver.transfer(100); }}", "e": 2554, "s": 1579, "text": null }, { "code": null, "e": 2562, "s": 2554, "text": "Output:" }, { "code": null, "e": 2569, "s": 2562, "text": "Output" }, { "code": null, "e": 2920, "s": 2569, "text": "1. Contract GeeksForGeeks: It has a variable x which is set to the default value 10 in the constructor(). The contract has a function called SetX(uint _x) which sets the function value to the desired parameter sent during the function call. The below declaration creates address to value map called balance which maps the addresses to their balance. " }, { "code": null, "e": 2955, "s": 2920, "text": "mapping(address => uint) balance;\n" }, { "code": null, "e": 3440, "s": 2955, "text": "2. Contract Sender: This is a completely independent and unrelated contract. It sends a value in Ether to the contract GeeksForGeeks. The contract does not know the mechanism of the GeeksForGeeks contract. Sending a transaction without any message and only Ether can cause an error.The below statements declare a variable _receiver of the address type. It explicitly stores the address of contract GeeksForGeeks. It then uses address.transfer(value) to transfer Ether to the contract." }, { "code": null, "e": 3569, "s": 3440, "text": "address _receiver = 0xbcc0185441de06F0452D45AEd6Ad8b98017796fb; //Address of GeeksForGeeks contract\n_receiver.transfer(100); \n\n" }, { "code": null, "e": 3600, "s": 3569, "text": "3. Function() public payable: " }, { "code": null, "e": 3734, "s": 3600, "text": "The function below is a fallback function. It is declared payable which allows it to accept transfer value. It is called in two cases" }, { "code": null, "e": 3842, "s": 3734, "text": "A contract receives only Ether and no data.No function calls matched even though the account received data." }, { "code": null, "e": 3886, "s": 3842, "text": "A contract receives only Ether and no data." }, { "code": null, "e": 3951, "s": 3886, "text": "No function calls matched even though the account received data." }, { "code": null, "e": 4181, "s": 3951, "text": "This helps us to protect the function from throwing an error. In this program, the contract GeeksForGeeks receives only Ether and the fallback function uses the value received to add to the balance related to the sending address." }, { "code": null, "e": 4262, "s": 4181, "text": "function() public payable\n {\n balance[msg.sender] += msg.value;\n }\n" }, { "code": null, "e": 4281, "s": 4262, "text": "Solidity-Functions" }, { "code": null, "e": 4292, "s": 4281, "text": "Blockchain" }, { "code": null, "e": 4301, "s": 4292, "text": "Solidity" }, { "code": null, "e": 4399, "s": 4301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4438, "s": 4399, "text": "How to connect ReactJS with MetaMask ?" }, { "code": null, "e": 4463, "s": 4438, "text": "Introduction to Solidity" }, { "code": null, "e": 4499, "s": 4463, "text": "How to Install Solidity in Windows?" }, { "code": null, "e": 4529, "s": 4499, "text": "Proof of Work (PoW) Consensus" }, { "code": null, "e": 4565, "s": 4529, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 4590, "s": 4565, "text": "Introduction to Solidity" }, { "code": null, "e": 4626, "s": 4590, "text": "How to Install Solidity in Windows?" }, { "code": null, "e": 4662, "s": 4626, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 4685, "s": 4662, "text": "Solidity - Inheritance" } ]
How to find the sum of non-missing values in an R data frame column?
To find the sum of non-missing values in an R data frame column, we can simply use sum function and set the na.rm to TRUE. For example, if we have a data frame called df that contains a column say x which has some missing values then the sum of the non-missing values can be found by using the command sum(df$x,na.rm=TRUE). Consider the below data frame − Live Demo x1<-sample(c(NA,2,3),20,replace=TRUE) x2<-sample(c(NA,5),20,replace=TRUE) df1<-data.frame(x1,x2) df1 x1 x2 1 3 5 2 2 NA 3 3 5 4 NA 5 5 NA NA 6 3 NA 7 3 5 8 3 NA 9 NA 5 10 3 NA 11 3 NA 12 2 NA 13 2 5 14 2 5 15 3 NA 16 2 NA 17 3 5 18 NA 5 19 3 5 20 3 5 Finding the sum of non-missing values in columns x1 and x2 − sum(df1$x1,na.rm=TRUE) [1] 43 sum(df1$x2,na.rm=TRUE) [1] 55 Live Demo y1<-sample(c(NA,rpois(1,2)),20,replace=TRUE) y2<-sample(c(NA,rpois(2,8)),20,replace=TRUE) df2<-data.frame(y1,y2) df2 y1 y2 1 NA NA 2 3 NA 3 3 4 4 3 4 5 NA 6 6 3 NA 7 3 4 8 3 4 9 3 NA 10 3 4 11 NA 6 12 3 6 13 NA 6 14 NA NA 15 3 NA 16 NA 4 17 3 6 18 3 6 19 NA NA 20 3 6 Finding the sum of non-missing values in columns y1 and y2 − sum(df2$y1,na.rm=TRUE) [1] 39 sum(df2$y2,na.rm=TRUE) [1] 66
[ { "code": null, "e": 1511, "s": 1187, "text": "To find the sum of non-missing values in an R data frame column, we can simply use sum function and set the na.rm to TRUE. For example, if we have a data frame called df that contains a column say x which has some missing values then the sum of the non-missing values can be found by using the command sum(df$x,na.rm=TRUE)." }, { "code": null, "e": 1543, "s": 1511, "text": "Consider the below data frame −" }, { "code": null, "e": 1554, "s": 1543, "text": " Live Demo" }, { "code": null, "e": 1655, "s": 1554, "text": "x1<-sample(c(NA,2,3),20,replace=TRUE)\nx2<-sample(c(NA,5),20,replace=TRUE)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 1854, "s": 1655, "text": " x1 x2\n1 3 5\n2 2 NA\n3 3 5\n4 NA 5\n5 NA NA\n6 3 NA\n7 3 5\n8 3 NA\n9 NA 5\n10 3 NA\n11 3 NA\n12 2 NA\n13 2 5\n14 2 5\n15 3 NA\n16 2 NA\n17 3 5\n18 NA 5\n19 3 5\n20 3 5" }, { "code": null, "e": 1915, "s": 1854, "text": "Finding the sum of non-missing values in columns x1 and x2 −" }, { "code": null, "e": 1938, "s": 1915, "text": "sum(df1$x1,na.rm=TRUE)" }, { "code": null, "e": 1945, "s": 1938, "text": "[1] 43" }, { "code": null, "e": 1968, "s": 1945, "text": "sum(df1$x2,na.rm=TRUE)" }, { "code": null, "e": 1975, "s": 1968, "text": "[1] 55" }, { "code": null, "e": 1986, "s": 1975, "text": " Live Demo" }, { "code": null, "e": 2103, "s": 1986, "text": "y1<-sample(c(NA,rpois(1,2)),20,replace=TRUE)\ny2<-sample(c(NA,rpois(2,8)),20,replace=TRUE)\ndf2<-data.frame(y1,y2)\ndf2" }, { "code": null, "e": 2300, "s": 2103, "text": " y1 y2\n1 NA NA\n2 3 NA\n3 3 4\n4 3 4\n5 NA 6\n6 3 NA\n7 3 4\n8 3 4\n9 3 NA\n10 3 4\n11 NA 6\n12 3 6\n13 NA 6\n14 NA NA\n15 3 NA\n16 NA 4\n17 3 6\n18 3 6\n19 NA NA\n20 3 6" }, { "code": null, "e": 2361, "s": 2300, "text": "Finding the sum of non-missing values in columns y1 and y2 −" }, { "code": null, "e": 2384, "s": 2361, "text": "sum(df2$y1,na.rm=TRUE)" }, { "code": null, "e": 2391, "s": 2384, "text": "[1] 39" }, { "code": null, "e": 2414, "s": 2391, "text": "sum(df2$y2,na.rm=TRUE)" }, { "code": null, "e": 2421, "s": 2414, "text": "[1] 66" } ]
Implementing an Autoencoder in PyTorch
07 Jul, 2022 Autoencoders are a type of neural network which generates an “n-layer” coding of the given input and attempts to reconstruct the input using the code generated. This Neural Network architecture is divided into the encoder structure, the decoder structure, and the latent space, also known as the “bottleneck”. To learn the data representations of the input, the network is trained using Unsupervised data. These compressed, data representations go through a decoding process wherein which the input is reconstructed. An autoencoder is a regression task that models an identity function. This structure comprises a conventional, feed-forward neural network that is structured to predict the latent view representation of the input data. It is given by: Where represents the hidden layer 1, represents the hidden layer 2, represents the input of the autoencoder, and h represents the low-dimensional, data space of the input This structure comprises a feed-forward neural network but the dimension of the data increases in the order of the encoder layer for predicting the input. It is given by: Where represents the hidden layer 1, represents the hidden layer 2, represents the low-dimensional, data space generated by the Encoder Structure and represents the reconstructed input. This is the data representation or the low-level, compressed representation of the model’s input. The decoder structure uses this low-dimensional form of data to reconstruct the input. It is represented by Autoencoder Architecture In the above figure, the top three layers represent the Encoder Block while the bottom three layers represent the Decoder Block. The latent state space is at the middle of the architecture . Autoencoders are used for image compression, feature extraction, dimensionality reduction, etc. Let’s now see the implementation. torch: This python package provides high-level tensor computation and deep neural networks built on autograd system. pip install torch torchvision: This module consists of a wide range of databases, image architectures, and transformations for computer vision pip install torchvision Step 1: Importing Modules We will use the torch.optim and the torch.nn module from the torch package and datasets & transforms from torchvision package. In this article, we will be using the popular MNIST dataset comprising grayscale images of handwritten single digits between 0 and 9. Python3 import torchfrom torchvision import datasetsfrom torchvision import transformsimport matplotlib.pyplot as plt Step 2: Loading the Dataset This snippet loads the MNIST dataset into loader using DataLoader module. The dataset is downloaded and transformed into image tensors. Using the DataLoader module, the tensors are loaded and ready to be used. The dataset is loaded with Shuffling enabled and a batch size of 64. Python3 # Transforms images to a PyTorch Tensortensor_transform = transforms.ToTensor() # Download the MNIST Datasetdataset = datasets.MNIST(root = "./data", train = True, download = True, transform = tensor_transform) # DataLoader is used to load the dataset# for trainingloader = torch.utils.data.DataLoader(dataset = dataset, batch_size = 32, shuffle = True) Step 3: Create Autoencoder Class In this coding snippet, the encoder section reduces the dimensionality of the data sequentially as given by: 28*28 = 784 ==> 128 ==> 64 ==> 36 ==> 18 ==> 9 Where the number of input nodes is 784 that are coded into 9 nodes in the latent space. Whereas, in the decoder section, the dimensionality of the data is linearly increased to the original input size, in order to reconstruct the input. 9 ==> 18 ==> 36 ==> 64 ==> 128 ==> 784 ==> 28*28 = 784 Where the input is the 9-node latent space representation and the output is the 28*28 reconstructed input. The encoder starts with 28*28 nodes in a Linear layer followed by a ReLU layer, and it goes on until the dimensionality is reduced to 9 nodes. The decryptor uses these 9 data representations to bring back the original image by using the inverse of the encoder architecture. The decryptor architecture uses a Sigmoid Layer to range the values between 0 and 1 only. Python3 # Creating a PyTorch class# 28*28 ==> 9 ==> 28*28class AE(torch.nn.Module): def __init__(self): super().__init__() # Building an linear encoder with Linear # layer followed by Relu activation function # 784 ==> 9 self.encoder = torch.nn.Sequential( torch.nn.Linear(28 * 28, 128), torch.nn.ReLU(), torch.nn.Linear(128, 64), torch.nn.ReLU(), torch.nn.Linear(64, 36), torch.nn.ReLU(), torch.nn.Linear(36, 18), torch.nn.ReLU(), torch.nn.Linear(18, 9) ) # Building an linear decoder with Linear # layer followed by Relu activation function # The Sigmoid activation function # outputs the value between 0 and 1 # 9 ==> 784 self.decoder = torch.nn.Sequential( torch.nn.Linear(9, 18), torch.nn.ReLU(), torch.nn.Linear(18, 36), torch.nn.ReLU(), torch.nn.Linear(36, 64), torch.nn.ReLU(), torch.nn.Linear(64, 128), torch.nn.ReLU(), torch.nn.Linear(128, 28 * 28), torch.nn.Sigmoid() ) def forward(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded Step 4: Initializing Model We validate the model using the Mean Squared Error function, and we use an Adam Optimizer with a learning rate of 0.1 and weight decay of Python3 # Model Initializationmodel = AE() # Validation using MSE Loss functionloss_function = torch.nn.MSELoss() # Using an Adam Optimizer with lr = 0.1optimizer = torch.optim.Adam(model.parameters(), lr = 1e-1, weight_decay = 1e-8) Step 5: Create Output Generation The output against each epoch is computed by passing as a parameter into the Model() class and the final tensor is stored in an output list. The image into (-1, 784) and is passed as a parameter to the Autoencoder class, which in turn returns a reconstructed image. The loss function is calculated using MSELoss function and plotted. In the optimizer, the initial gradient values are made to zero using zero_grad(). loss.backward() computes the grad values and stored. Using the step() function, the optimizer is updated. The original image and the reconstructed image from the outputs list are detached and transformed into a NumPy Array for plotting the images. Note: This snippet takes 15 to 20 mins to execute, depending on the processor type. Initialize epoch = 1, for quick results. Use a GPU/TPU runtime for faster computations. Python3 epochs = 20outputs = []losses = []for epoch in range(epochs): for (image, _) in loader: # Reshaping the image to (-1, 784) image = image.reshape(-1, 28*28) # Output of Autoencoder reconstructed = model(image) # Calculating the loss function loss = loss_function(reconstructed, image) # The gradients are set to zero, # the gradient is computed and stored. # .step() performs parameter update optimizer.zero_grad() loss.backward() optimizer.step() # Storing the losses in a list for plotting losses.append(loss) outputs.append((epochs, image, reconstructed)) # Defining the Plot Styleplt.style.use('fivethirtyeight')plt.xlabel('Iterations')plt.ylabel('Loss') # Plotting the last 100 valuesplt.plot(losses[-100:]) Output: Loss function graph Step 6: Input/Reconstructed Input to/from Autoencoder The first input image array and the first reconstructed input image array have been plotted using plt.imshow(). Python3 for i, item in enumerate(image): # Reshape the array for plotting item = item.reshape(-1, 28, 28) plt.imshow(item[0]) for i, item in enumerate(reconstructed): item = item.reshape(-1, 28, 28) plt.imshow(item[0]) Output: Sample Plot 1: Input image(left) and reconstructed input(right) Sample Plot 2: Input image(left) and reconstructed input(right) Although the rebuilt pictures appear to be adequate, they are extremely grainy. To enhance this outcome, extra layers and/or neurons may be added, or the autoencoder model could be built on convolutions neural network architecture. For dimensionality reduction, autoencoders are quite beneficial. However, it might also be used for data denoising and understanding a dataset’s spread. surinderdawra388 Picked Python-PyTorch Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Support Vector Machine Algorithm Markov Decision Process DBSCAN Clustering in ML | Density based clustering 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": 28, "s": 0, "text": "\n07 Jul, 2022" }, { "code": null, "e": 615, "s": 28, "text": "Autoencoders are a type of neural network which generates an “n-layer” coding of the given input and attempts to reconstruct the input using the code generated. This Neural Network architecture is divided into the encoder structure, the decoder structure, and the latent space, also known as the “bottleneck”. To learn the data representations of the input, the network is trained using Unsupervised data. These compressed, data representations go through a decoding process wherein which the input is reconstructed. An autoencoder is a regression task that models an identity function." }, { "code": null, "e": 780, "s": 615, "text": "This structure comprises a conventional, feed-forward neural network that is structured to predict the latent view representation of the input data. It is given by:" }, { "code": null, "e": 955, "s": 780, "text": "Where represents the hidden layer 1, represents the hidden layer 2, represents the input of the autoencoder, and h represents the low-dimensional, data space of the input" }, { "code": null, "e": 1126, "s": 955, "text": "This structure comprises a feed-forward neural network but the dimension of the data increases in the order of the encoder layer for predicting the input. It is given by:" }, { "code": null, "e": 1316, "s": 1126, "text": "Where represents the hidden layer 1, represents the hidden layer 2, represents the low-dimensional, data space generated by the Encoder Structure and represents the reconstructed input." }, { "code": null, "e": 1523, "s": 1316, "text": "This is the data representation or the low-level, compressed representation of the model’s input. The decoder structure uses this low-dimensional form of data to reconstruct the input. It is represented by " }, { "code": null, "e": 1548, "s": 1523, "text": "Autoencoder Architecture" }, { "code": null, "e": 1869, "s": 1548, "text": "In the above figure, the top three layers represent the Encoder Block while the bottom three layers represent the Decoder Block. The latent state space is at the middle of the architecture . Autoencoders are used for image compression, feature extraction, dimensionality reduction, etc. Let’s now see the implementation." }, { "code": null, "e": 1986, "s": 1869, "text": "torch: This python package provides high-level tensor computation and deep neural networks built on autograd system." }, { "code": null, "e": 2004, "s": 1986, "text": "pip install torch" }, { "code": null, "e": 2129, "s": 2004, "text": "torchvision: This module consists of a wide range of databases, image architectures, and transformations for computer vision" }, { "code": null, "e": 2153, "s": 2129, "text": "pip install torchvision" }, { "code": null, "e": 2179, "s": 2153, "text": "Step 1: Importing Modules" }, { "code": null, "e": 2440, "s": 2179, "text": "We will use the torch.optim and the torch.nn module from the torch package and datasets & transforms from torchvision package. In this article, we will be using the popular MNIST dataset comprising grayscale images of handwritten single digits between 0 and 9." }, { "code": null, "e": 2448, "s": 2440, "text": "Python3" }, { "code": "import torchfrom torchvision import datasetsfrom torchvision import transformsimport matplotlib.pyplot as plt", "e": 2558, "s": 2448, "text": null }, { "code": null, "e": 2586, "s": 2558, "text": "Step 2: Loading the Dataset" }, { "code": null, "e": 2865, "s": 2586, "text": "This snippet loads the MNIST dataset into loader using DataLoader module. The dataset is downloaded and transformed into image tensors. Using the DataLoader module, the tensors are loaded and ready to be used. The dataset is loaded with Shuffling enabled and a batch size of 64." }, { "code": null, "e": 2873, "s": 2865, "text": "Python3" }, { "code": "# Transforms images to a PyTorch Tensortensor_transform = transforms.ToTensor() # Download the MNIST Datasetdataset = datasets.MNIST(root = \"./data\", train = True, download = True, transform = tensor_transform) # DataLoader is used to load the dataset# for trainingloader = torch.utils.data.DataLoader(dataset = dataset, batch_size = 32, shuffle = True)", "e": 3371, "s": 2873, "text": null }, { "code": null, "e": 3404, "s": 3371, "text": "Step 3: Create Autoencoder Class" }, { "code": null, "e": 3513, "s": 3404, "text": "In this coding snippet, the encoder section reduces the dimensionality of the data sequentially as given by:" }, { "code": null, "e": 3560, "s": 3513, "text": "28*28 = 784 ==> 128 ==> 64 ==> 36 ==> 18 ==> 9" }, { "code": null, "e": 3797, "s": 3560, "text": "Where the number of input nodes is 784 that are coded into 9 nodes in the latent space. Whereas, in the decoder section, the dimensionality of the data is linearly increased to the original input size, in order to reconstruct the input." }, { "code": null, "e": 3852, "s": 3797, "text": "9 ==> 18 ==> 36 ==> 64 ==> 128 ==> 784 ==> 28*28 = 784" }, { "code": null, "e": 3959, "s": 3852, "text": "Where the input is the 9-node latent space representation and the output is the 28*28 reconstructed input." }, { "code": null, "e": 4323, "s": 3959, "text": "The encoder starts with 28*28 nodes in a Linear layer followed by a ReLU layer, and it goes on until the dimensionality is reduced to 9 nodes. The decryptor uses these 9 data representations to bring back the original image by using the inverse of the encoder architecture. The decryptor architecture uses a Sigmoid Layer to range the values between 0 and 1 only." }, { "code": null, "e": 4331, "s": 4323, "text": "Python3" }, { "code": "# Creating a PyTorch class# 28*28 ==> 9 ==> 28*28class AE(torch.nn.Module): def __init__(self): super().__init__() # Building an linear encoder with Linear # layer followed by Relu activation function # 784 ==> 9 self.encoder = torch.nn.Sequential( torch.nn.Linear(28 * 28, 128), torch.nn.ReLU(), torch.nn.Linear(128, 64), torch.nn.ReLU(), torch.nn.Linear(64, 36), torch.nn.ReLU(), torch.nn.Linear(36, 18), torch.nn.ReLU(), torch.nn.Linear(18, 9) ) # Building an linear decoder with Linear # layer followed by Relu activation function # The Sigmoid activation function # outputs the value between 0 and 1 # 9 ==> 784 self.decoder = torch.nn.Sequential( torch.nn.Linear(9, 18), torch.nn.ReLU(), torch.nn.Linear(18, 36), torch.nn.ReLU(), torch.nn.Linear(36, 64), torch.nn.ReLU(), torch.nn.Linear(64, 128), torch.nn.ReLU(), torch.nn.Linear(128, 28 * 28), torch.nn.Sigmoid() ) def forward(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded", "e": 5645, "s": 4331, "text": null }, { "code": null, "e": 5672, "s": 5645, "text": "Step 4: Initializing Model" }, { "code": null, "e": 5811, "s": 5672, "text": "We validate the model using the Mean Squared Error function, and we use an Adam Optimizer with a learning rate of 0.1 and weight decay of " }, { "code": null, "e": 5819, "s": 5811, "text": "Python3" }, { "code": "# Model Initializationmodel = AE() # Validation using MSE Loss functionloss_function = torch.nn.MSELoss() # Using an Adam Optimizer with lr = 0.1optimizer = torch.optim.Adam(model.parameters(), lr = 1e-1, weight_decay = 1e-8)", "e": 6101, "s": 5819, "text": null }, { "code": null, "e": 6134, "s": 6101, "text": "Step 5: Create Output Generation" }, { "code": null, "e": 6656, "s": 6134, "text": "The output against each epoch is computed by passing as a parameter into the Model() class and the final tensor is stored in an output list. The image into (-1, 784) and is passed as a parameter to the Autoencoder class, which in turn returns a reconstructed image. The loss function is calculated using MSELoss function and plotted. In the optimizer, the initial gradient values are made to zero using zero_grad(). loss.backward() computes the grad values and stored. Using the step() function, the optimizer is updated." }, { "code": null, "e": 6798, "s": 6656, "text": "The original image and the reconstructed image from the outputs list are detached and transformed into a NumPy Array for plotting the images." }, { "code": null, "e": 6970, "s": 6798, "text": "Note: This snippet takes 15 to 20 mins to execute, depending on the processor type. Initialize epoch = 1, for quick results. Use a GPU/TPU runtime for faster computations." }, { "code": null, "e": 6978, "s": 6970, "text": "Python3" }, { "code": "epochs = 20outputs = []losses = []for epoch in range(epochs): for (image, _) in loader: # Reshaping the image to (-1, 784) image = image.reshape(-1, 28*28) # Output of Autoencoder reconstructed = model(image) # Calculating the loss function loss = loss_function(reconstructed, image) # The gradients are set to zero, # the gradient is computed and stored. # .step() performs parameter update optimizer.zero_grad() loss.backward() optimizer.step() # Storing the losses in a list for plotting losses.append(loss) outputs.append((epochs, image, reconstructed)) # Defining the Plot Styleplt.style.use('fivethirtyeight')plt.xlabel('Iterations')plt.ylabel('Loss') # Plotting the last 100 valuesplt.plot(losses[-100:])", "e": 7801, "s": 6978, "text": null }, { "code": null, "e": 7809, "s": 7801, "text": "Output:" }, { "code": null, "e": 7829, "s": 7809, "text": "Loss function graph" }, { "code": null, "e": 7883, "s": 7829, "text": "Step 6: Input/Reconstructed Input to/from Autoencoder" }, { "code": null, "e": 7995, "s": 7883, "text": "The first input image array and the first reconstructed input image array have been plotted using plt.imshow()." }, { "code": null, "e": 8003, "s": 7995, "text": "Python3" }, { "code": "for i, item in enumerate(image): # Reshape the array for plotting item = item.reshape(-1, 28, 28) plt.imshow(item[0]) for i, item in enumerate(reconstructed): item = item.reshape(-1, 28, 28) plt.imshow(item[0])", "e": 8222, "s": 8003, "text": null }, { "code": null, "e": 8230, "s": 8222, "text": "Output:" }, { "code": null, "e": 8294, "s": 8230, "text": "Sample Plot 1: Input image(left) and reconstructed input(right)" }, { "code": null, "e": 8358, "s": 8294, "text": "Sample Plot 2: Input image(left) and reconstructed input(right)" }, { "code": null, "e": 8743, "s": 8358, "text": "Although the rebuilt pictures appear to be adequate, they are extremely grainy. To enhance this outcome, extra layers and/or neurons may be added, or the autoencoder model could be built on convolutions neural network architecture. For dimensionality reduction, autoencoders are quite beneficial. However, it might also be used for data denoising and understanding a dataset’s spread." }, { "code": null, "e": 8760, "s": 8743, "text": "surinderdawra388" }, { "code": null, "e": 8767, "s": 8760, "text": "Picked" }, { "code": null, "e": 8782, "s": 8767, "text": "Python-PyTorch" }, { "code": null, "e": 8799, "s": 8782, "text": "Machine Learning" }, { "code": null, "e": 8806, "s": 8799, "text": "Python" }, { "code": null, "e": 8823, "s": 8806, "text": "Machine Learning" }, { "code": null, "e": 8921, "s": 8823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8962, "s": 8921, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 8998, "s": 8962, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 9031, "s": 8998, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 9055, "s": 9031, "text": "Markov Decision Process" }, { "code": null, "e": 9106, "s": 9055, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 9134, "s": 9106, "text": "Read JSON file using Python" }, { "code": null, "e": 9184, "s": 9134, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 9206, "s": 9184, "text": "Python map() function" } ]
React.js displayName
31 Mar, 2021 The displayName string is used in debugging messages. It’s usually not necessary to set it explicitly because the name of the function or class that describes the component infers it. If you wish to show a different name for debugging purposes or when you build a higher-order component, you may want to set it specifically. The displayName given by React is a highly recommended feature that greatly aids in unit testing and debugging. It also comes in handy when inspecting a part with React dev tools. Creating React Application: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Project Structure: It will look like the following. 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 ReactDOM from 'react-dom'; const child_class = class Myclass { render() { return ( <div></div> ) }} child_class.displayName = "Kapil";class App extends React.Component { render() { return ( <div> <p> displayName of child class is: {child_class.displayName} </p> </div> ) }} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Picked ReactJS-Basics ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to do crud operations in ReactJS ? How to create a multi-page website using React.js ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Mar, 2021" }, { "code": null, "e": 353, "s": 28, "text": "The displayName string is used in debugging messages. It’s usually not necessary to set it explicitly because the name of the function or class that describes the component infers it. If you wish to show a different name for debugging purposes or when you build a higher-order component, you may want to set it specifically." }, { "code": null, "e": 533, "s": 353, "text": "The displayName given by React is a highly recommended feature that greatly aids in unit testing and debugging. It also comes in handy when inspecting a part with React dev tools." }, { "code": null, "e": 561, "s": 533, "text": "Creating React Application:" }, { "code": null, "e": 656, "s": 561, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 720, "s": 656, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 752, "s": 720, "text": "npx create-react-app foldername" }, { "code": null, "e": 865, "s": 752, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 965, "s": 865, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 979, "s": 965, "text": "cd foldername" }, { "code": null, "e": 1031, "s": 979, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1160, "s": 1031, "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": 1167, "s": 1160, "text": "App.js" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; const child_class = class Myclass { render() { return ( <div></div> ) }} child_class.displayName = \"Kapil\";class App extends React.Component { render() { return ( <div> <p> displayName of child class is: {child_class.displayName} </p> </div> ) }} export default App;", "e": 1568, "s": 1167, "text": null }, { "code": null, "e": 1681, "s": 1568, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1691, "s": 1681, "text": "npm start" }, { "code": null, "e": 1790, "s": 1691, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 1797, "s": 1790, "text": "Picked" }, { "code": null, "e": 1812, "s": 1797, "text": "ReactJS-Basics" }, { "code": null, "e": 1820, "s": 1812, "text": "ReactJS" }, { "code": null, "e": 1837, "s": 1820, "text": "Web Technologies" }, { "code": null, "e": 1935, "s": 1837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1973, "s": 1935, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2000, "s": 1973, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 2039, "s": 2000, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 2078, "s": 2039, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 2130, "s": 2078, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 2163, "s": 2130, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2225, "s": 2163, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2286, "s": 2225, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2336, "s": 2286, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Pylint module in Python
18 Apr, 2022 We often get stuck in the middle or encounter errors when we code/run some programs. We usually surf the internet for help and make our code run. But how do we understand the published code on the internet? Some of the typical answers to this question are docstrings, articles written above that code.., One of the biggest problems in this era is understanding the other’s programs. Situations are even worse if there are no explanatory things like comments, docstrings in the code. As a programmer, we should make our code readable and understandable. To address the solution, Python provides a module pylint. This article provides a brief introduction to the pylint module and provides tips to get a good score on my code. Let’s Start. Pylint is a tool that Lists Errors which comes after execution of that Python code Enforces a coding standard and looks for code smells Suggest how particular blocks can be updated Offer details about the code’s complexity Pylint tool is similar to pychecker, pyflakes, flake8, and mypy. To install pylint, make sure Python is installed on your PC. Open the command prompt(Windows) / terminal(Linux) on your PC and type the following command pip install pylint To verify the pylint installation, type the following command pylint --version You should see pylint “2.4.4” version. We can also verify the installation by reinstalling the pylint. In that case, if pylint is already installed you should see Requirement already satisfied on your screen. Consider the following program that accepts two numbers and prints their sum. Python3 a = 1b = 2print(a + b) Now save the above program in the file gfg.pyOpen your command prompt / terminal and type the following command pylint gfg.py In the pylint 2.4.4 version, you will get a report as shown below. Messages might change depending on the version. Score for the code given above is -10.0/10.0(Very low). If we get a low score it doesn’t mean that our code is wrong. The score represents how good/bad your code is understandable by another programmer. We need to improve our code by considering the suggestions given in the report. Each message suggestion/point in the report will be given with a message format that consists of an ID and its meaning. Each ID starts with an alphabet and the rest will be numbered. Each alphabet denotes the type of message object. Some of the message objects are Let’s discuss some techniques to improve score. ID C0326 suggest a bad-white space error means we need to give a whitespace between a and = symbol. This rule is applicable to all declarations where an operator is used immediately after an identifier. ID C0304 comes under missing-new-line suggestion which means we have to add a blank line when we complete our code. ID C0114 comes under missing-module-docstring suggestion which means we need to add a docstring at the top which refers to the use of the program written below that. ID C0103 comes under invalid-name suggestion which can be avoided by writing the identifiers start with a capital letter. But, we usually believe that class names use CamelCasing i.e class names start with an upper-case letter. To avoid this suggestion we will add a regular expression to pylint that actually accepts all the variables in the lowercase letters. We will discuss this more in the further examples. The modified version of the code is: Python3 '''This program adds two numbers and displays their results'''A = 1B = 2print('Sum of Numbers:', A + B) If we run the above code using pylint, we will get the following result Here we improved our score from -10.0 to 10.0. That’s great. But, is my code understandable? The answer is no. There are some more changes which we need to specify the pylint module to score our code. As discussed earlier, the pylint module will use the uppercase naming convention by default. The regular expression used to identify that uppercase convention is (([A-Z_][A-Z1-9_]*)|(__.*__))$. We need to add our suggestion as a regular expression that accepts identifiers starting with lowercase alphabets. To do that, open your command prompt and execute the following statement. pylint --const-rgx='[a-z\_][a-z0-9\_]{2, 30}$' filename.py . This will avoid the use of the uppercase convention. We can modify that permanently by changing rules in pylint –generate-rcfile which we will discuss in future articles. simmytarika5 python-modules 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 Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Apr, 2022" }, { "code": null, "e": 812, "s": 52, "text": "We often get stuck in the middle or encounter errors when we code/run some programs. We usually surf the internet for help and make our code run. But how do we understand the published code on the internet? Some of the typical answers to this question are docstrings, articles written above that code.., One of the biggest problems in this era is understanding the other’s programs. Situations are even worse if there are no explanatory things like comments, docstrings in the code. As a programmer, we should make our code readable and understandable. To address the solution, Python provides a module pylint. This article provides a brief introduction to the pylint module and provides tips to get a good score on my code. Let’s Start. Pylint is a tool that" }, { "code": null, "e": 873, "s": 812, "text": "Lists Errors which comes after execution of that Python code" }, { "code": null, "e": 926, "s": 873, "text": "Enforces a coding standard and looks for code smells" }, { "code": null, "e": 971, "s": 926, "text": "Suggest how particular blocks can be updated" }, { "code": null, "e": 1013, "s": 971, "text": "Offer details about the code’s complexity" }, { "code": null, "e": 1078, "s": 1013, "text": "Pylint tool is similar to pychecker, pyflakes, flake8, and mypy." }, { "code": null, "e": 1232, "s": 1078, "text": "To install pylint, make sure Python is installed on your PC. Open the command prompt(Windows) / terminal(Linux) on your PC and type the following command" }, { "code": null, "e": 1252, "s": 1232, "text": "pip install pylint " }, { "code": null, "e": 1314, "s": 1252, "text": "To verify the pylint installation, type the following command" }, { "code": null, "e": 1331, "s": 1314, "text": "pylint --version" }, { "code": null, "e": 1540, "s": 1331, "text": "You should see pylint “2.4.4” version. We can also verify the installation by reinstalling the pylint. In that case, if pylint is already installed you should see Requirement already satisfied on your screen." }, { "code": null, "e": 1619, "s": 1540, "text": "Consider the following program that accepts two numbers and prints their sum. " }, { "code": null, "e": 1627, "s": 1619, "text": "Python3" }, { "code": "a = 1b = 2print(a + b)", "e": 1650, "s": 1627, "text": null }, { "code": null, "e": 1762, "s": 1650, "text": "Now save the above program in the file gfg.pyOpen your command prompt / terminal and type the following command" }, { "code": null, "e": 1776, "s": 1762, "text": "pylint gfg.py" }, { "code": null, "e": 2440, "s": 1776, "text": "In the pylint 2.4.4 version, you will get a report as shown below. Messages might change depending on the version. Score for the code given above is -10.0/10.0(Very low). If we get a low score it doesn’t mean that our code is wrong. The score represents how good/bad your code is understandable by another programmer. We need to improve our code by considering the suggestions given in the report. Each message suggestion/point in the report will be given with a message format that consists of an ID and its meaning. Each ID starts with an alphabet and the rest will be numbered. Each alphabet denotes the type of message object. Some of the message objects are" }, { "code": null, "e": 2488, "s": 2440, "text": "Let’s discuss some techniques to improve score." }, { "code": null, "e": 2691, "s": 2488, "text": "ID C0326 suggest a bad-white space error means we need to give a whitespace between a and = symbol. This rule is applicable to all declarations where an operator is used immediately after an identifier." }, { "code": null, "e": 2807, "s": 2691, "text": "ID C0304 comes under missing-new-line suggestion which means we have to add a blank line when we complete our code." }, { "code": null, "e": 2973, "s": 2807, "text": "ID C0114 comes under missing-module-docstring suggestion which means we need to add a docstring at the top which refers to the use of the program written below that." }, { "code": null, "e": 3386, "s": 2973, "text": "ID C0103 comes under invalid-name suggestion which can be avoided by writing the identifiers start with a capital letter. But, we usually believe that class names use CamelCasing i.e class names start with an upper-case letter. To avoid this suggestion we will add a regular expression to pylint that actually accepts all the variables in the lowercase letters. We will discuss this more in the further examples." }, { "code": null, "e": 3424, "s": 3386, "text": "The modified version of the code is: " }, { "code": null, "e": 3432, "s": 3424, "text": "Python3" }, { "code": "'''This program adds two numbers and displays their results'''A = 1B = 2print('Sum of Numbers:', A + B)", "e": 3536, "s": 3432, "text": null }, { "code": null, "e": 3810, "s": 3536, "text": "If we run the above code using pylint, we will get the following result Here we improved our score from -10.0 to 10.0. That’s great. But, is my code understandable? The answer is no. There are some more changes which we need to specify the pylint module to score our code." }, { "code": null, "e": 4192, "s": 3810, "text": "As discussed earlier, the pylint module will use the uppercase naming convention by default. The regular expression used to identify that uppercase convention is (([A-Z_][A-Z1-9_]*)|(__.*__))$. We need to add our suggestion as a regular expression that accepts identifiers starting with lowercase alphabets. To do that, open your command prompt and execute the following statement." }, { "code": null, "e": 4251, "s": 4192, "text": "pylint --const-rgx='[a-z\\_][a-z0-9\\_]{2, 30}$' filename.py" }, { "code": null, "e": 4424, "s": 4251, "text": ". This will avoid the use of the uppercase convention. We can modify that permanently by changing rules in pylint –generate-rcfile which we will discuss in future articles." }, { "code": null, "e": 4437, "s": 4424, "text": "simmytarika5" }, { "code": null, "e": 4452, "s": 4437, "text": "python-modules" }, { "code": null, "e": 4459, "s": 4452, "text": "Python" }, { "code": null, "e": 4557, "s": 4459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4589, "s": 4557, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4616, "s": 4589, "text": "Python Classes and Objects" }, { "code": null, "e": 4637, "s": 4616, "text": "Python OOPs Concepts" }, { "code": null, "e": 4660, "s": 4637, "text": "Introduction To PYTHON" }, { "code": null, "e": 4716, "s": 4660, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4747, "s": 4716, "text": "Python | os.path.join() method" }, { "code": null, "e": 4789, "s": 4747, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4831, "s": 4789, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4870, "s": 4831, "text": "Python | Get unique values from a list" } ]
How to fetch data from JSON file and display in HTML table using jQuery ?
01 Jul, 2022 The task is to fetch data from the given JSON file and convert data into an HTML table. Approach: We have a JSON file containing data in the form of an array of objects. In our code, we are using jQuery to complete our task. The jQuery code uses getJSON() method to fetch the data from the file’s location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array. It also takes two arguments. One is the data and the other one is the function containing the index and the element. An empty string is used to construct rows that contain the data from the JSON objects. The append() method is used to append the string containing rows in the table. JSON file: Example: <html lang="en"> <head> <meta charset="UTF-8"> <title>GFG User Details</title> <!-- INCLUDING JQUERY--> <script src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- CSS FOR STYLING THE PAGE --> <style> table { margin: 0 auto; font-size: large; border: 1px solid black; } h1 { text-align: center; color: #006600; font-size: xx-large; font-family: 'Gill Sans', 'Gill Sans MT', ' Calibri', 'Trebuchet MS', 'sans-serif'; } td { background-color: #E4F5D4; border: 1px solid black; } th, td { font-weight: bold; border: 1px solid black; padding: 10px; text-align: center; } td { font-weight: lighter; } </style></head> <body> <section> <h1>GeeksForGeeks</h1> <!-- TABLE CONSTRUCTION--> <table id='table'> <!-- HEADING FORMATION --> <tr> <th>GFG UserHandle</th> <th>Practice Problems</th> <th>Coding Score</th> <th>GFG Articles</th> </tr> <script> $(document).ready(function () { // FETCHING DATA FROM JSON FILE $.getJSON("gfgdetails.json", function (data) { var student = ''; // ITERATING THROUGH OBJECTS $.each(data, function (key, value) { //CONSTRUCTION OF ROWS HAVING // DATA FROM JSON OBJECT student += '<tr>'; student += '<td>' + value.GFGUserName + '</td>'; student += '<td>' + value.NoOfProblems + '</td>'; student += '<td>' + value.TotalScore + '</td>'; student += '<td>' + value.Articles + '</td>'; student += '</tr>'; }); //INSERTING ROWS INTO TABLE $('#table').append(student); }); }); </script> </section></body> </html> Output: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. CSS-Misc HTML-Misc jQuery-Misc CSS HTML JavaScript JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jul, 2022" }, { "code": null, "e": 140, "s": 52, "text": "The task is to fetch data from the given JSON file and convert data into an HTML table." }, { "code": null, "e": 867, "s": 140, "text": "Approach: We have a JSON file containing data in the form of an array of objects. In our code, we are using jQuery to complete our task. The jQuery code uses getJSON() method to fetch the data from the file’s location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array. It also takes two arguments. One is the data and the other one is the function containing the index and the element. An empty string is used to construct rows that contain the data from the JSON objects. The append() method is used to append the string containing rows in the table." }, { "code": null, "e": 878, "s": 867, "text": "JSON file:" }, { "code": null, "e": 887, "s": 878, "text": "Example:" }, { "code": "<html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GFG User Details</title> <!-- INCLUDING JQUERY--> <script src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- CSS FOR STYLING THE PAGE --> <style> table { margin: 0 auto; font-size: large; border: 1px solid black; } h1 { text-align: center; color: #006600; font-size: xx-large; font-family: 'Gill Sans', 'Gill Sans MT', ' Calibri', 'Trebuchet MS', 'sans-serif'; } td { background-color: #E4F5D4; border: 1px solid black; } th, td { font-weight: bold; border: 1px solid black; padding: 10px; text-align: center; } td { font-weight: lighter; } </style></head> <body> <section> <h1>GeeksForGeeks</h1> <!-- TABLE CONSTRUCTION--> <table id='table'> <!-- HEADING FORMATION --> <tr> <th>GFG UserHandle</th> <th>Practice Problems</th> <th>Coding Score</th> <th>GFG Articles</th> </tr> <script> $(document).ready(function () { // FETCHING DATA FROM JSON FILE $.getJSON(\"gfgdetails.json\", function (data) { var student = ''; // ITERATING THROUGH OBJECTS $.each(data, function (key, value) { //CONSTRUCTION OF ROWS HAVING // DATA FROM JSON OBJECT student += '<tr>'; student += '<td>' + value.GFGUserName + '</td>'; student += '<td>' + value.NoOfProblems + '</td>'; student += '<td>' + value.TotalScore + '</td>'; student += '<td>' + value.Articles + '</td>'; student += '</tr>'; }); //INSERTING ROWS INTO TABLE $('#table').append(student); }); }); </script> </section></body> </html>", "e": 3410, "s": 887, "text": null }, { "code": null, "e": 3418, "s": 3410, "text": "Output:" }, { "code": null, "e": 3612, "s": 3418, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 3880, "s": 3612, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 3889, "s": 3880, "text": "CSS-Misc" }, { "code": null, "e": 3899, "s": 3889, "text": "HTML-Misc" }, { "code": null, "e": 3911, "s": 3899, "text": "jQuery-Misc" }, { "code": null, "e": 3915, "s": 3911, "text": "CSS" }, { "code": null, "e": 3920, "s": 3915, "text": "HTML" }, { "code": null, "e": 3931, "s": 3920, "text": "JavaScript" }, { "code": null, "e": 3938, "s": 3931, "text": "JQuery" }, { "code": null, "e": 3955, "s": 3938, "text": "Web Technologies" }, { "code": null, "e": 3960, "s": 3955, "text": "HTML" } ]
Expected SARSA in Reinforcement Learning
28 Apr, 2021 Prerequisites: SARSASARSA and Q-Learning technique in Reinforcement Learning are algorithms that uses Temporal Difference(TD) Update to improve the agent’s behaviour. Expected SARSA technique is an alternative for improving the agent’s policy. It is very similar to SARSA and Q-Learning, and differs in the action value function it follows. We know that SARSA is an on-policy technique, Q-learning is an off-policy technique, but Expected SARSA can be use either as an on-policy or off-policy. This is where Expected SARSA is much more flexible compared to both these algorithms.Let’s compare the action-value function of all the three algorithms and find out what is different in Expected SARSA. SARSA: Q-Learning: Expected SARSA: We see that Expected SARSA takes the weighted sum of all possible next actions with respect to the probability of taking that action. If the Expected Return is greedy with respect to the expected return, then this equation gets transformed to Q-Learning. Otherwise Expected SARSA is on-policy and computes the expected return for all actions, rather than randomly selecting an action like SARSA.Keeping the theory and the formulae in mind, let us compare all the three algorithms, with an experiment. We shall implement a Cliff Walker as our environment provided by the gym libraryCode: Python code to create the class Agent which will be inherited by the other agents to avoid duplicate code. Python3 # Agent.py import numpy as np class Agent: """ The Base class that is implemented by other classes to avoid the duplicate 'choose_action' method """ def choose_action(self, state): action = 0 if np.random.uniform(0, 1) < self.epsilon: action = self.action_space.sample() else: action = np.argmax(self.Q[state, :]) return action Code: Python code to create the SARSA Agent. Python3 # SarsaAgent.py import numpy as npfrom Agent import Agent class SarsaAgent(Agent): """ The Agent that uses SARSA update to improve it's behaviour """ def __init__(self, epsilon, alpha, gamma, num_state, num_actions, action_space): """ Constructor Args: epsilon: The degree of exploration gamma: The discount factor num_state: The number of states num_actions: The number of actions action_space: To call the random action """ self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.num_state = num_state self.num_actions = num_actions self.Q = np.zeros((self.num_state, self.num_actions)) self.action_space = action_space def update(self, prev_state, next_state, reward, prev_action, next_action): """ Update the action value function using the SARSA update. Q(S, A) = Q(S, A) + alpha(reward + (gamma * Q(S_, A_) - Q(S, A)) Args: prev_state: The previous state next_state: The next state reward: The reward for taking the respective action prev_action: The previous action next_action: The next action Returns: None """ predict = self.Q[prev_state, prev_action] target = reward + self.gamma * self.Q[next_state, next_action] self.Q[prev_state, prev_action] += self.alpha * (target - predict) Code: Python code to create the Q-Learning Agent. Python3 # QLearningAgent.py import numpy as npfrom Agent import Agent class QLearningAgent(Agent): def __init__(self, epsilon, alpha, gamma, num_state, num_actions, action_space): """ Constructor Args: epsilon: The degree of exploration gamma: The discount factor num_state: The number of states num_actions: The number of actions action_space: To call the random action """ self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.num_state = num_state self.num_actions = num_actions self.Q = np.zeros((self.num_state, self.num_actions)) self.action_space = action_space def update(self, state, state2, reward, action, action2): """ Update the action value function using the Q-Learning update. Q(S, A) = Q(S, A) + alpha(reward + (gamma * Q(S_, A_) - Q(S, A)) Args: prev_state: The previous state next_state: The next state reward: The reward for taking the respective action prev_action: The previous action next_action: The next action Returns: None """ predict = self.Q[state, action] target = reward + self.gamma * np.max(self.Q[state2, :]) self.Q[state, action] += self.alpha * (target - predict) Code: Python code to create the Expected SARSA Agent. In this experiment we are using the following equation for the policy. Python3 # ExpectedSarsaAgent.py import numpy as npfrom Agent import Agent class ExpectedSarsaAgent(Agent): def __init__(self, epsilon, alpha, gamma, num_state, num_actions, action_space): """ Constructor Args: epsilon: The degree of exploration gamma: The discount factor num_state: The number of states num_actions: The number of actions action_space: To call the random action """ self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.num_state = num_state self.num_actions = num_actions self.Q = np.zeros((self.num_state, self.num_actions)) self.action_space = action_space def update(self, prev_state, next_state, reward, prev_action, next_action): """ Update the action value function using the Expected SARSA update. Q(S, A) = Q(S, A) + alpha(reward + (pi * Q(S_, A_) - Q(S, A)) Args: prev_state: The previous state next_state: The next state reward: The reward for taking the respective action prev_action: The previous action next_action: The next action Returns: None """ predict = self.Q[prev_state, prev_action] expected_q = 0 q_max = np.max(self.Q[next_state, :]) greedy_actions = 0 for i in range(self.num_actions): if self.Q[next_state][i] == q_max: greedy_actions += 1 non_greedy_action_probability = self.epsilon / self.num_actions greedy_action_probability = ((1 - self.epsilon) / greedy_actions) + non_greedy_action_probability for i in range(self.num_actions): if self.Q[next_state][i] == q_max: expected_q += self.Q[next_state][i] * greedy_action_probability else: expected_q += self.Q[next_state][i] * non_greedy_action_probability target = reward + self.gamma * expected_q self.Q[prev_state, prev_action] += self.alpha * (target - predict) Python code to create an environment and Test all the three algorithms. Python3 # main.py import gymimport numpy as np from ExpectedSarsaAgent import ExpectedSarsaAgentfrom QLearningAgent import QLearningAgentfrom SarsaAgent import SarsaAgentfrom matplotlib import pyplot as plt # Using the gym library to create the environmentenv = gym.make('CliffWalking-v0') # Defining all the required parametersepsilon = 0.1total_episodes = 500max_steps = 100alpha = 0.5gamma = 1""" The two parameters below is used to calculate the reward by each algorithm"""episodeReward = 0totalReward = { 'SarsaAgent': [], 'QLearningAgent': [], 'ExpectedSarsaAgent': []} # Defining all the three agentsexpectedSarsaAgent = ExpectedSarsaAgent( epsilon, alpha, gamma, env.observation_space.n, env.action_space.n, env.action_space)qLearningAgent = QLearningAgent( epsilon, alpha, gamma, env.observation_space.n, env.action_space.n, env.action_space)sarsaAgent = SarsaAgent( epsilon, alpha, gamma, env.observation_space.n, env.action_space.n, env.action_space) # Now we run all the episodes and calculate the reward obtained by# each agent at the end of the episode agents = [expectedSarsaAgent, qLearningAgent, sarsaAgent] for agent in agents: for _ in range(total_episodes): # Initialize the necessary parameters before # the start of the episode t = 0 state1 = env.reset() action1 = agent.choose_action(state1) episodeReward = 0 while t < max_steps: # Getting the next state, reward, and other parameters state2, reward, done, info = env.step(action1) # Choosing the next action action2 = agent.choose_action(state2) # Learning the Q-value agent.update(state1, state2, reward, action1, action2) state1 = state2 action1 = action2 # Updating the respective vaLues t += 1 episodeReward += reward # If at the end of learning process if done: break # Append the sum of reward at the end of the episode totalReward[type(agent).__name__].append(episodeReward)env.close() # Calculate the mean of sum of returns for each episodemeanReturn = { 'SARSA-Agent': np.mean(totalReward['SarsaAgent']), 'Q-Learning-Agent': np.mean(totalReward['QLearningAgent']), 'Expected-SARSA-Agent': np.mean(totalReward['ExpectedSarsaAgent'])} # Print the resultsprint(f"SARSA Average Sum of Reward: {meanReturn['SARSA-Agent']}")print(f"Q-Learning Average Sum of Return: {meanReturn['Q-Learning-Agent']}")print(f"Expected Sarsa Average Sum of Return: {meanReturn['Expected-SARSA-Agent']}") Output: Conclusion: We have seen that Expected SARSA performs reasonably well in certain problems. It considers all possible outcomes before selecting a particular action. The fact that Expected SARSA can be used either as an off or on policy, is what makes this algorithm so dynamic. simmytarika5 arorakashish0911 Machine Learning Python 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 ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2021" }, { "code": null, "e": 727, "s": 28, "text": "Prerequisites: SARSASARSA and Q-Learning technique in Reinforcement Learning are algorithms that uses Temporal Difference(TD) Update to improve the agent’s behaviour. Expected SARSA technique is an alternative for improving the agent’s policy. It is very similar to SARSA and Q-Learning, and differs in the action value function it follows. We know that SARSA is an on-policy technique, Q-learning is an off-policy technique, but Expected SARSA can be use either as an on-policy or off-policy. This is where Expected SARSA is much more flexible compared to both these algorithms.Let’s compare the action-value function of all the three algorithms and find out what is different in Expected SARSA. " }, { "code": null, "e": 735, "s": 727, "text": "SARSA: " }, { "code": null, "e": 748, "s": 735, "text": "Q-Learning: " }, { "code": null, "e": 765, "s": 748, "text": "Expected SARSA: " }, { "code": null, "e": 1460, "s": 765, "text": "We see that Expected SARSA takes the weighted sum of all possible next actions with respect to the probability of taking that action. If the Expected Return is greedy with respect to the expected return, then this equation gets transformed to Q-Learning. Otherwise Expected SARSA is on-policy and computes the expected return for all actions, rather than randomly selecting an action like SARSA.Keeping the theory and the formulae in mind, let us compare all the three algorithms, with an experiment. We shall implement a Cliff Walker as our environment provided by the gym libraryCode: Python code to create the class Agent which will be inherited by the other agents to avoid duplicate code. " }, { "code": null, "e": 1468, "s": 1460, "text": "Python3" }, { "code": "# Agent.py import numpy as np class Agent: \"\"\" The Base class that is implemented by other classes to avoid the duplicate 'choose_action' method \"\"\" def choose_action(self, state): action = 0 if np.random.uniform(0, 1) < self.epsilon: action = self.action_space.sample() else: action = np.argmax(self.Q[state, :]) return action", "e": 1864, "s": 1468, "text": null }, { "code": null, "e": 1910, "s": 1864, "text": "Code: Python code to create the SARSA Agent. " }, { "code": null, "e": 1918, "s": 1910, "text": "Python3" }, { "code": "# SarsaAgent.py import numpy as npfrom Agent import Agent class SarsaAgent(Agent): \"\"\" The Agent that uses SARSA update to improve it's behaviour \"\"\" def __init__(self, epsilon, alpha, gamma, num_state, num_actions, action_space): \"\"\" Constructor Args: epsilon: The degree of exploration gamma: The discount factor num_state: The number of states num_actions: The number of actions action_space: To call the random action \"\"\" self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.num_state = num_state self.num_actions = num_actions self.Q = np.zeros((self.num_state, self.num_actions)) self.action_space = action_space def update(self, prev_state, next_state, reward, prev_action, next_action): \"\"\" Update the action value function using the SARSA update. Q(S, A) = Q(S, A) + alpha(reward + (gamma * Q(S_, A_) - Q(S, A)) Args: prev_state: The previous state next_state: The next state reward: The reward for taking the respective action prev_action: The previous action next_action: The next action Returns: None \"\"\" predict = self.Q[prev_state, prev_action] target = reward + self.gamma * self.Q[next_state, next_action] self.Q[prev_state, prev_action] += self.alpha * (target - predict)", "e": 3398, "s": 1918, "text": null }, { "code": null, "e": 3449, "s": 3398, "text": "Code: Python code to create the Q-Learning Agent. " }, { "code": null, "e": 3457, "s": 3449, "text": "Python3" }, { "code": "# QLearningAgent.py import numpy as npfrom Agent import Agent class QLearningAgent(Agent): def __init__(self, epsilon, alpha, gamma, num_state, num_actions, action_space): \"\"\" Constructor Args: epsilon: The degree of exploration gamma: The discount factor num_state: The number of states num_actions: The number of actions action_space: To call the random action \"\"\" self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.num_state = num_state self.num_actions = num_actions self.Q = np.zeros((self.num_state, self.num_actions)) self.action_space = action_space def update(self, state, state2, reward, action, action2): \"\"\" Update the action value function using the Q-Learning update. Q(S, A) = Q(S, A) + alpha(reward + (gamma * Q(S_, A_) - Q(S, A)) Args: prev_state: The previous state next_state: The next state reward: The reward for taking the respective action prev_action: The previous action next_action: The next action Returns: None \"\"\" predict = self.Q[state, action] target = reward + self.gamma * np.max(self.Q[state2, :]) self.Q[state, action] += self.alpha * (target - predict)", "e": 4829, "s": 3457, "text": null }, { "code": null, "e": 4956, "s": 4829, "text": "Code: Python code to create the Expected SARSA Agent. In this experiment we are using the following equation for the policy. " }, { "code": null, "e": 4964, "s": 4956, "text": "Python3" }, { "code": "# ExpectedSarsaAgent.py import numpy as npfrom Agent import Agent class ExpectedSarsaAgent(Agent): def __init__(self, epsilon, alpha, gamma, num_state, num_actions, action_space): \"\"\" Constructor Args: epsilon: The degree of exploration gamma: The discount factor num_state: The number of states num_actions: The number of actions action_space: To call the random action \"\"\" self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.num_state = num_state self.num_actions = num_actions self.Q = np.zeros((self.num_state, self.num_actions)) self.action_space = action_space def update(self, prev_state, next_state, reward, prev_action, next_action): \"\"\" Update the action value function using the Expected SARSA update. Q(S, A) = Q(S, A) + alpha(reward + (pi * Q(S_, A_) - Q(S, A)) Args: prev_state: The previous state next_state: The next state reward: The reward for taking the respective action prev_action: The previous action next_action: The next action Returns: None \"\"\" predict = self.Q[prev_state, prev_action] expected_q = 0 q_max = np.max(self.Q[next_state, :]) greedy_actions = 0 for i in range(self.num_actions): if self.Q[next_state][i] == q_max: greedy_actions += 1 non_greedy_action_probability = self.epsilon / self.num_actions greedy_action_probability = ((1 - self.epsilon) / greedy_actions) + non_greedy_action_probability for i in range(self.num_actions): if self.Q[next_state][i] == q_max: expected_q += self.Q[next_state][i] * greedy_action_probability else: expected_q += self.Q[next_state][i] * non_greedy_action_probability target = reward + self.gamma * expected_q self.Q[prev_state, prev_action] += self.alpha * (target - predict)", "e": 7033, "s": 4964, "text": null }, { "code": null, "e": 7106, "s": 7033, "text": "Python code to create an environment and Test all the three algorithms. " }, { "code": null, "e": 7114, "s": 7106, "text": "Python3" }, { "code": "# main.py import gymimport numpy as np from ExpectedSarsaAgent import ExpectedSarsaAgentfrom QLearningAgent import QLearningAgentfrom SarsaAgent import SarsaAgentfrom matplotlib import pyplot as plt # Using the gym library to create the environmentenv = gym.make('CliffWalking-v0') # Defining all the required parametersepsilon = 0.1total_episodes = 500max_steps = 100alpha = 0.5gamma = 1\"\"\" The two parameters below is used to calculate the reward by each algorithm\"\"\"episodeReward = 0totalReward = { 'SarsaAgent': [], 'QLearningAgent': [], 'ExpectedSarsaAgent': []} # Defining all the three agentsexpectedSarsaAgent = ExpectedSarsaAgent( epsilon, alpha, gamma, env.observation_space.n, env.action_space.n, env.action_space)qLearningAgent = QLearningAgent( epsilon, alpha, gamma, env.observation_space.n, env.action_space.n, env.action_space)sarsaAgent = SarsaAgent( epsilon, alpha, gamma, env.observation_space.n, env.action_space.n, env.action_space) # Now we run all the episodes and calculate the reward obtained by# each agent at the end of the episode agents = [expectedSarsaAgent, qLearningAgent, sarsaAgent] for agent in agents: for _ in range(total_episodes): # Initialize the necessary parameters before # the start of the episode t = 0 state1 = env.reset() action1 = agent.choose_action(state1) episodeReward = 0 while t < max_steps: # Getting the next state, reward, and other parameters state2, reward, done, info = env.step(action1) # Choosing the next action action2 = agent.choose_action(state2) # Learning the Q-value agent.update(state1, state2, reward, action1, action2) state1 = state2 action1 = action2 # Updating the respective vaLues t += 1 episodeReward += reward # If at the end of learning process if done: break # Append the sum of reward at the end of the episode totalReward[type(agent).__name__].append(episodeReward)env.close() # Calculate the mean of sum of returns for each episodemeanReturn = { 'SARSA-Agent': np.mean(totalReward['SarsaAgent']), 'Q-Learning-Agent': np.mean(totalReward['QLearningAgent']), 'Expected-SARSA-Agent': np.mean(totalReward['ExpectedSarsaAgent'])} # Print the resultsprint(f\"SARSA Average Sum of Reward: {meanReturn['SARSA-Agent']}\")print(f\"Q-Learning Average Sum of Return: {meanReturn['Q-Learning-Agent']}\")print(f\"Expected Sarsa Average Sum of Return: {meanReturn['Expected-SARSA-Agent']}\")", "e": 9785, "s": 7114, "text": null }, { "code": null, "e": 9795, "s": 9785, "text": "Output: " }, { "code": null, "e": 10073, "s": 9795, "text": "Conclusion: We have seen that Expected SARSA performs reasonably well in certain problems. It considers all possible outcomes before selecting a particular action. The fact that Expected SARSA can be used either as an off or on policy, is what makes this algorithm so dynamic. " }, { "code": null, "e": 10086, "s": 10073, "text": "simmytarika5" }, { "code": null, "e": 10103, "s": 10086, "text": "arorakashish0911" }, { "code": null, "e": 10120, "s": 10103, "text": "Machine Learning" }, { "code": null, "e": 10127, "s": 10120, "text": "Python" }, { "code": null, "e": 10144, "s": 10127, "text": "Machine Learning" }, { "code": null, "e": 10242, "s": 10144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10283, "s": 10242, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 10316, "s": 10283, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 10352, "s": 10316, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 10376, "s": 10352, "text": "Markov Decision Process" }, { "code": null, "e": 10427, "s": 10376, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 10455, "s": 10427, "text": "Read JSON file using Python" }, { "code": null, "e": 10477, "s": 10455, "text": "Python map() function" }, { "code": null, "e": 10527, "s": 10477, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 10545, "s": 10527, "text": "Python Dictionary" } ]
vector :: assign() in C++ STL
09 Jun, 2022 vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary. The syntax for assigning constant values: vectorname.assign(int size, int value) Parameters: size - number of values to be assigned value - value to be assigned to the vectorname Program 1: The program below shows how to assign constant values to a vector CPP // CPP program to demonstrate// how to assign constant values to a vector #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.assign(7, 100); cout << "Size of first: " << int(v.size()) << '\n'; cout << "Elements are\n"; for (int i = 0; i < v.size(); i++) cout << v[i] << endl; return 0;} Size of first: 7 Elements are 100 100 100 100 100 100 100 The syntax for assigning values from an array or list: vectorname.assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned. Program 2: The program below shows how to assign values from an array or list CPP // CPP program to demonstrate// how to assign values to a vector// from a list #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1; int a[] = { 1, 2, 3 }; // assign first 2 values v1.assign(a, a + 2); cout << "Elements of vector1 are\n"; for (int i = 0; i < v1.size(); i++) cout << v1[i] << " "; vector<int> v2; // assign first 3 values v2.assign(a, a + 3); cout << "\nElements of vector2 are\n"; for (int i = 0; i < v2.size(); i++) cout << v2[i] << " "; return 0;} Elements of vector1 are 1 2 Elements of vector2 are 1 2 3 The syntax for modifying values from a vector vectorname.assign(InputIterator first, InputIterator last) Parameters: first - Input iterator to the initial position range. last - Input iterator to the final position range. Program 3: The program below shows how to modify the vector CPP // CPP program to demonstrate// how to modify vector size #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.assign(7, 100); cout << "Size of first: " << int(v.size()) << '\n'; cout << "Elements are\n"; for (int i = 0; i < v.size(); i++) cout << v[i] << endl; // modify the elements v.assign(v.begin(), v.begin() + 3); cout << "\nModified VectorElements are\n"; for (int i = 0; i < v.size(); i++) cout << v[i] << endl; return 0;} Size of first: 7 Elements are 100 100 100 100 100 100 100 Modified VectorElements are 100 100 100 Time Complexity – Linear O(N) Syntax for assigning values with initializer list: vectorname.assign((initializer_list) Parameter: initializer_list Program 4:The program below shows how to assign a vector with an initializer list. C++ #include <iostream>#include <vector>using namespace std;int main(){ vector<int> v; // Initialize v with an initialization list v.assign({ 1, 2, 3 }); cout << "The list is:" << endl; for (auto i = v.begin(); i != v.end(); i++) { // Printing 1 2 3 as output cout << *i << " "; } return 0;} The list is: 1 2 3 poulami21ghosh utkarshgupta110092 cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Substring in C++ C++ Classes and Objects Sorting a vector in C++ Virtual Function in C++ C++ Data Types Templates in C++ with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 214, "s": 52, "text": "vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary." }, { "code": null, "e": 257, "s": 214, "text": "The syntax for assigning constant values: " }, { "code": null, "e": 396, "s": 257, "text": "vectorname.assign(int size, int value)\n\nParameters: \nsize - number of values to be assigned\nvalue - value to be assigned to the vectorname" }, { "code": null, "e": 474, "s": 396, "text": "Program 1: The program below shows how to assign constant values to a vector " }, { "code": null, "e": 478, "s": 474, "text": "CPP" }, { "code": "// CPP program to demonstrate// how to assign constant values to a vector #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.assign(7, 100); cout << \"Size of first: \" << int(v.size()) << '\\n'; cout << \"Elements are\\n\"; for (int i = 0; i < v.size(); i++) cout << v[i] << endl; return 0;}", "e": 820, "s": 478, "text": null }, { "code": null, "e": 878, "s": 820, "text": "Size of first: 7\nElements are\n100\n100\n100\n100\n100\n100\n100" }, { "code": null, "e": 934, "s": 878, "text": "The syntax for assigning values from an array or list: " }, { "code": null, "e": 1106, "s": 934, "text": "vectorname.assign(arr, arr + size)\n\nParameters: \narr - the array which is to be assigned to a vector\nsize - number of elements from the beginning which has to be assigned." }, { "code": null, "e": 1185, "s": 1106, "text": "Program 2: The program below shows how to assign values from an array or list " }, { "code": null, "e": 1189, "s": 1185, "text": "CPP" }, { "code": "// CPP program to demonstrate// how to assign values to a vector// from a list #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1; int a[] = { 1, 2, 3 }; // assign first 2 values v1.assign(a, a + 2); cout << \"Elements of vector1 are\\n\"; for (int i = 0; i < v1.size(); i++) cout << v1[i] << \" \"; vector<int> v2; // assign first 3 values v2.assign(a, a + 3); cout << \"\\nElements of vector2 are\\n\"; for (int i = 0; i < v2.size(); i++) cout << v2[i] << \" \"; return 0;}", "e": 1730, "s": 1189, "text": null }, { "code": null, "e": 1790, "s": 1730, "text": "Elements of vector1 are\n1 2 \nElements of vector2 are\n1 2 3 " }, { "code": null, "e": 1837, "s": 1790, "text": "The syntax for modifying values from a vector " }, { "code": null, "e": 2016, "s": 1837, "text": "vectorname.assign(InputIterator first, InputIterator last) \n\nParameters: \nfirst - Input iterator to the initial position range.\nlast - Input iterator to the final position range." }, { "code": null, "e": 2077, "s": 2016, "text": "Program 3: The program below shows how to modify the vector " }, { "code": null, "e": 2081, "s": 2077, "text": "CPP" }, { "code": "// CPP program to demonstrate// how to modify vector size #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.assign(7, 100); cout << \"Size of first: \" << int(v.size()) << '\\n'; cout << \"Elements are\\n\"; for (int i = 0; i < v.size(); i++) cout << v[i] << endl; // modify the elements v.assign(v.begin(), v.begin() + 3); cout << \"\\nModified VectorElements are\\n\"; for (int i = 0; i < v.size(); i++) cout << v[i] << endl; return 0;}", "e": 2582, "s": 2081, "text": null }, { "code": null, "e": 2681, "s": 2582, "text": "Size of first: 7\nElements are\n100\n100\n100\n100\n100\n100\n100\n\nModified VectorElements are\n100\n100\n100" }, { "code": null, "e": 2711, "s": 2681, "text": "Time Complexity – Linear O(N)" }, { "code": null, "e": 2762, "s": 2711, "text": "Syntax for assigning values with initializer list:" }, { "code": null, "e": 2827, "s": 2762, "text": "vectorname.assign((initializer_list)\nParameter: initializer_list" }, { "code": null, "e": 2910, "s": 2827, "text": "Program 4:The program below shows how to assign a vector with an initializer list." }, { "code": null, "e": 2914, "s": 2910, "text": "C++" }, { "code": "#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v; // Initialize v with an initialization list v.assign({ 1, 2, 3 }); cout << \"The list is:\" << endl; for (auto i = v.begin(); i != v.end(); i++) { // Printing 1 2 3 as output cout << *i << \" \"; } return 0;}", "e": 3245, "s": 2914, "text": null }, { "code": null, "e": 3265, "s": 3245, "text": "The list is:\n1 2 3 " }, { "code": null, "e": 3280, "s": 3265, "text": "poulami21ghosh" }, { "code": null, "e": 3299, "s": 3280, "text": "utkarshgupta110092" }, { "code": null, "e": 3310, "s": 3299, "text": "cpp-vector" }, { "code": null, "e": 3314, "s": 3310, "text": "STL" }, { "code": null, "e": 3318, "s": 3314, "text": "C++" }, { "code": null, "e": 3322, "s": 3318, "text": "STL" }, { "code": null, "e": 3326, "s": 3322, "text": "CPP" }, { "code": null, "e": 3424, "s": 3326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3467, "s": 3424, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3501, "s": 3467, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3526, "s": 3501, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3580, "s": 3526, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3597, "s": 3580, "text": "Substring in C++" }, { "code": null, "e": 3621, "s": 3597, "text": "C++ Classes and Objects" }, { "code": null, "e": 3645, "s": 3621, "text": "Sorting a vector in C++" }, { "code": null, "e": 3669, "s": 3645, "text": "Virtual Function in C++" }, { "code": null, "e": 3684, "s": 3669, "text": "C++ Data Types" } ]
Relationship between grammar and language in Theory of Computation
20 Nov, 2019 A grammar is a set of production rules which are used to generate strings of a language. In this article, we have discussed how to find the language generated by a grammar and vice versa as well. Given a grammar G, its corresponding language L(G) represents the set of all strings generated from G. Consider the following grammar, G: S-> aSb|ε In this grammar, using S-> ε, we can generate ε. Therefore, ε is part of L(G). Similarly, using S=>aSb=>ab, ab is generated. Similarly, aabb can also be generated.Therefore, L(G) = {anbn, n>=0} In language L(G) discussed above, the condition n = 0 is taken to accept ε.Key Points – For a given grammar G, its corresponding language L(G) is unique. The language L(G) corresponding to grammar G must contain all strings which can be generated from G. The language L(G) corresponding to grammar G must not contain any string which can not be generated from G. Let us discuss questions based on this: Que-1. Consider the grammar: (GATE-CS-2009) S -> aSa|bSb|a|b The language generated by the above grammar over the alphabet {a,b} is the set of:(A) All palindromes(B) All odd length palindromes.(C) Strings that begin and end with the same symbol(D) All even length palindromes Solution: Using S->a and S->b, a and b can be generated. Similarly using S=>aSa=>aba, aba can be generated. Other strings which can be generated from grammar are: a, b, aba, bab, aaa, bbb, ababa, ...Therefore, option (B) is correct. Que-2. Consider the following context-free grammars: (GATE-CS-2016)Which one of the following pairs of languages is generated by G1 and G2, respectively? Solution: Consider the grammar G1:Using S=>B=>b, b can be generated.Using S=>B=>bB, bb can be generated.Using S=>aS=>aB=>ab can be generated.Using S=>aS=>aB=>abB=>abb can be generated.As we can see, number of a’s can be zero or more but number of b is always greater than zero.Therefore, L(G1) = {ambn| m>=0 and n>0} Consider the grammar G2:Using S=>aA=>a, a can be generated.Using S=>bB=>b, b can be generated.Using S=>aA=>aaA=>aa can be generated.Using S=>bB=>bbB=>bb can be generated.Using S=>aA=>aB=>abB=>abb can be generated. As we can see, either a or b must be greater than 0.Therefore, L(G2) = {ambn| m>0 or n>0} Given a language L(G), its corresponding grammar G represents the production rules which produces L(G). Consider the language L(G): L(G) = {anbn, n>=0} The language L(G) is set of strings ε, ab, aabb, aaabbb....For ε string in L(G), the production rule can be S->ε.For other strings in L(G), the production rule can be S->aSb|ε.Therefore, grammar G corresponding to L(G) is: S->aSb| ε Key Points – For a given language L(G), there can be more than one grammar which can produce L(G). The grammar G corresponding to language L(G) must generate all possible strings of L(G). The grammar G corresponding to language L(G) must not generate any string which is not part of L(G). Let us discuss questions based on this: Que-3. Which one of the following grammar generates the language L = {ai b j | i≠j}? (GATE-CS-2006) Solution: The given language L contains the strings : {a, b, aa, bb, aaa, bbb, aab, abb...} It means either the string must contain one or more number of a OR one or more number of b OR a followed by b having unequal number of a and b. If we consider grammar in option (A), it can generate ab as: S=>AC=>aAC=>aC=>ab However, ab can’t be generated by language L. Therefore, grammar in option (A) is not correct. Similarly, grammar in option (B) can generate ab as: S=>aS=>ab However, ab can’t be generated by language L. Therefore, grammar in option (B) is not correct. Similarly, grammar in option (C) can generate ab as: S=>AC=>C=>aCb=>ab However, ab can’t be generated by language L. Therefore, grammar in option (C) is not correct.Therefore, using method of elimination, option (D) is correct. VaibhavRai3 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS Difference between DFA and NFA Boyer-Moore Majority Voting Algorithm Variation of Turing Machine Design 101 sequence detector (Mealy machine) Post Correspondence Problem
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Nov, 2019" }, { "code": null, "e": 248, "s": 52, "text": "A grammar is a set of production rules which are used to generate strings of a language. In this article, we have discussed how to find the language generated by a grammar and vice versa as well." }, { "code": null, "e": 383, "s": 248, "text": "Given a grammar G, its corresponding language L(G) represents the set of all strings generated from G. Consider the following grammar," }, { "code": null, "e": 396, "s": 383, "text": "G: S-> aSb|ε" }, { "code": null, "e": 570, "s": 396, "text": "In this grammar, using S-> ε, we can generate ε. Therefore, ε is part of L(G). Similarly, using S=>aSb=>ab, ab is generated. Similarly, aabb can also be generated.Therefore," }, { "code": null, "e": 590, "s": 570, "text": "L(G) = {anbn, n>=0}" }, { "code": null, "e": 678, "s": 590, "text": "In language L(G) discussed above, the condition n = 0 is taken to accept ε.Key Points –" }, { "code": null, "e": 744, "s": 678, "text": "For a given grammar G, its corresponding language L(G) is unique." }, { "code": null, "e": 845, "s": 744, "text": "The language L(G) corresponding to grammar G must contain all strings which can be generated from G." }, { "code": null, "e": 953, "s": 845, "text": "The language L(G) corresponding to grammar G must not contain any string which can not be generated from G." }, { "code": null, "e": 993, "s": 953, "text": "Let us discuss questions based on this:" }, { "code": null, "e": 1037, "s": 993, "text": "Que-1. Consider the grammar: (GATE-CS-2009)" }, { "code": null, "e": 1055, "s": 1037, "text": "S -> aSa|bSb|a|b " }, { "code": null, "e": 1270, "s": 1055, "text": "The language generated by the above grammar over the alphabet {a,b} is the set of:(A) All palindromes(B) All odd length palindromes.(C) Strings that begin and end with the same symbol(D) All even length palindromes" }, { "code": null, "e": 1503, "s": 1270, "text": "Solution: Using S->a and S->b, a and b can be generated. Similarly using S=>aSa=>aba, aba can be generated. Other strings which can be generated from grammar are: a, b, aba, bab, aaa, bbb, ababa, ...Therefore, option (B) is correct." }, { "code": null, "e": 1657, "s": 1503, "text": "Que-2. Consider the following context-free grammars: (GATE-CS-2016)Which one of the following pairs of languages is generated by G1 and G2, respectively?" }, { "code": null, "e": 1945, "s": 1657, "text": "Solution: Consider the grammar G1:Using S=>B=>b, b can be generated.Using S=>B=>bB, bb can be generated.Using S=>aS=>aB=>ab can be generated.Using S=>aS=>aB=>abB=>abb can be generated.As we can see, number of a’s can be zero or more but number of b is always greater than zero.Therefore," }, { "code": null, "e": 1974, "s": 1945, "text": "L(G1) = {ambn| m>=0 and n>0}" }, { "code": null, "e": 2188, "s": 1974, "text": "Consider the grammar G2:Using S=>aA=>a, a can be generated.Using S=>bB=>b, b can be generated.Using S=>aA=>aaA=>aa can be generated.Using S=>bB=>bbB=>bb can be generated.Using S=>aA=>aB=>abB=>abb can be generated." }, { "code": null, "e": 2251, "s": 2188, "text": "As we can see, either a or b must be greater than 0.Therefore," }, { "code": null, "e": 2278, "s": 2251, "text": "L(G2) = {ambn| m>0 or n>0}" }, { "code": null, "e": 2410, "s": 2278, "text": "Given a language L(G), its corresponding grammar G represents the production rules which produces L(G). Consider the language L(G):" }, { "code": null, "e": 2430, "s": 2410, "text": "L(G) = {anbn, n>=0}" }, { "code": null, "e": 2653, "s": 2430, "text": "The language L(G) is set of strings ε, ab, aabb, aaabbb....For ε string in L(G), the production rule can be S->ε.For other strings in L(G), the production rule can be S->aSb|ε.Therefore, grammar G corresponding to L(G) is:" }, { "code": null, "e": 2664, "s": 2653, "text": "S->aSb| ε " }, { "code": null, "e": 2677, "s": 2664, "text": "Key Points –" }, { "code": null, "e": 2763, "s": 2677, "text": "For a given language L(G), there can be more than one grammar which can produce L(G)." }, { "code": null, "e": 2852, "s": 2763, "text": "The grammar G corresponding to language L(G) must generate all possible strings of L(G)." }, { "code": null, "e": 2953, "s": 2852, "text": "The grammar G corresponding to language L(G) must not generate any string which is not part of L(G)." }, { "code": null, "e": 2993, "s": 2953, "text": "Let us discuss questions based on this:" }, { "code": null, "e": 3094, "s": 2993, "text": "Que-3. Which one of the following grammar generates the language L = {ai b j | i≠j}? (GATE-CS-2006)" }, { "code": null, "e": 3148, "s": 3094, "text": "Solution: The given language L contains the strings :" }, { "code": null, "e": 3186, "s": 3148, "text": "{a, b, aa, bb, aaa, bbb, aab, abb...}" }, { "code": null, "e": 3330, "s": 3186, "text": "It means either the string must contain one or more number of a OR one or more number of b OR a followed by b having unequal number of a and b." }, { "code": null, "e": 3391, "s": 3330, "text": "If we consider grammar in option (A), it can generate ab as:" }, { "code": null, "e": 3410, "s": 3391, "text": "S=>AC=>aAC=>aC=>ab" }, { "code": null, "e": 3505, "s": 3410, "text": "However, ab can’t be generated by language L. Therefore, grammar in option (A) is not correct." }, { "code": null, "e": 3558, "s": 3505, "text": "Similarly, grammar in option (B) can generate ab as:" }, { "code": null, "e": 3568, "s": 3558, "text": "S=>aS=>ab" }, { "code": null, "e": 3663, "s": 3568, "text": "However, ab can’t be generated by language L. Therefore, grammar in option (B) is not correct." }, { "code": null, "e": 3716, "s": 3663, "text": "Similarly, grammar in option (C) can generate ab as:" }, { "code": null, "e": 3734, "s": 3716, "text": "S=>AC=>C=>aCb=>ab" }, { "code": null, "e": 3891, "s": 3734, "text": "However, ab can’t be generated by language L. Therefore, grammar in option (C) is not correct.Therefore, using method of elimination, option (D) is correct." }, { "code": null, "e": 3903, "s": 3891, "text": "VaibhavRai3" }, { "code": null, "e": 3911, "s": 3903, "text": "GATE CS" }, { "code": null, "e": 3944, "s": 3911, "text": "Theory of Computation & Automata" }, { "code": null, "e": 4042, "s": 3944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4062, "s": 4042, "text": "Layers of OSI Model" }, { "code": null, "e": 4086, "s": 4062, "text": "ACID Properties in DBMS" }, { "code": null, "e": 4099, "s": 4086, "text": "TCP/IP Model" }, { "code": null, "e": 4126, "s": 4099, "text": "Types of Operating Systems" }, { "code": null, "e": 4147, "s": 4126, "text": "Normal Forms in DBMS" }, { "code": null, "e": 4178, "s": 4147, "text": "Difference between DFA and NFA" }, { "code": null, "e": 4216, "s": 4178, "text": "Boyer-Moore Majority Voting Algorithm" }, { "code": null, "e": 4244, "s": 4216, "text": "Variation of Turing Machine" }, { "code": null, "e": 4289, "s": 4244, "text": "Design 101 sequence detector (Mealy machine)" } ]
How to merge multiple excel files into a single files with Python ?
07 Mar, 2022 Normally, we’re working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one which is not only time-consume, troublesome but also error-prone. This task can be done easily and quickly with few lines of code in Python with the Pandas module. First, we need to install the module with pip. So let’s get the installation out of our way. Use the following command in the terminal: pip install pandas Method 1: Using dataframe.append() Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value. Syntax : DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None) Parameters : other : DataFrame or Series/dict-like object, or list of these ignore_index : If True, do not use the index labels. default False. verify_integrity : If True, raise ValueError on creating index with duplicates. default False. sort : Sort columns if the columns of self and other are not aligned. default False. Returns: appended DataFrame Example: Excel Used: FoodSales1-1, FoodSales2-1 Python3 # importing the required modulesimport globimport pandas as pd # specifying the path to csv filespath = "C:/downloads" # csv files in the pathfile_list = glob.glob(path + "/*.xlsx") # list of excel files we want to merge.# pd.read_excel(file_path) reads the excel# data into pandas dataframe.excl_list = [] for file in file_list: excl_list.append(pd.read_excel(file)) # create a new dataframe to store the# merged excel file.excl_merged = pd.DataFrame() for excl_file in excl_list: # appends the data into the excl_merged # dataframe. excl_merged = excl_merged.append( excl_file, ignore_index=True) # exports the dataframe into excel file with# specified name.excl_merged.to_excel('total_food_sales.xlsx', index=False) Output : ‘total_food_sales.xlsx’ Method 2: Using pandas.concat() The pandas.concat() function does all the heavy lifting of performing concatenation operations along with an axis of Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes. Syntax: concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy) Parameters: objs: Series or DataFrame objects axis: axis to concatenate along; default = 0 //along rows join: way to handle indexes on other axis; default = ‘outer’ ignore_index: if True, do not use the index values along the concatenation axis; default = False keys: sequence to add an identifier to the result indexes; default = None levels: specific levels (unique values) to use for constructing a MultiIndex; default = None names: names for the levels in the resulting hierarchical index; default = None verify_integrity: check whether the new concatenated axis contains duplicates; default = False sort: sort non-concatenation axis if it is not already aligned when join is ‘outer’; default = False copy: if False, do not copy data unnecessarily; default = True Returns: a pandas dataframe with concatenated data. Example: In the last example, we worked on only two Excel files with a few rows. Let’s try merging more files each containing approximately 5000 rows and 7 columns. We have 5 files BankE, BankD, BankC, BankB, BankA having historical stock data for respective bank. Let’s merge them into a single ‘Bank_Stocks.xlsx’ file. Here we are using the pandas.concat() method. Python3 # importing the required modulesimport globimport pandas as pd # specifying the path to csv filespath = "C:/downloads" # csv files in the pathfile_list = glob.glob(path + "/*.xlsx") # list of excel files we want to merge.# pd.read_excel(file_path) reads the # excel data into pandas dataframe.excl_list = [] for file in file_list: excl_list.append(pd.read_excel(file)) # concatenate all DataFrames in the list# into a single DataFrame, returns new# DataFrame.excl_merged = pd.concat(excl_list, ignore_index=True) # exports the dataframe into excel file# with specified name.excl_merged.to_excel('Bank_Stocks.xlsx', index=False) Output : Bank_Stocks.xlsx fgonvrz0ayd1fs840q2db5xhwsf5qnvno28cwt0m Picked Python-excel Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Mar, 2022" }, { "code": null, "e": 468, "s": 52, "text": "Normally, we’re working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one which is not only time-consume, troublesome but also error-prone. " }, { "code": null, "e": 660, "s": 468, "text": "This task can be done easily and quickly with few lines of code in Python with the Pandas module. First, we need to install the module with pip. So let’s get the installation out of our way. " }, { "code": null, "e": 703, "s": 660, "text": "Use the following command in the terminal:" }, { "code": null, "e": 722, "s": 703, "text": "pip install pandas" }, { "code": null, "e": 757, "s": 722, "text": "Method 1: Using dataframe.append()" }, { "code": null, "e": 1015, "s": 757, "text": "Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value." }, { "code": null, "e": 1103, "s": 1015, "text": "Syntax : DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)" }, { "code": null, "e": 1116, "s": 1103, "text": "Parameters :" }, { "code": null, "e": 1179, "s": 1116, "text": "other : DataFrame or Series/dict-like object, or list of these" }, { "code": null, "e": 1247, "s": 1179, "text": "ignore_index : If True, do not use the index labels. default False." }, { "code": null, "e": 1342, "s": 1247, "text": "verify_integrity : If True, raise ValueError on creating index with duplicates. default False." }, { "code": null, "e": 1427, "s": 1342, "text": "sort : Sort columns if the columns of self and other are not aligned. default False." }, { "code": null, "e": 1455, "s": 1427, "text": "Returns: appended DataFrame" }, { "code": null, "e": 1464, "s": 1455, "text": "Example:" }, { "code": null, "e": 1504, "s": 1464, "text": "Excel Used: FoodSales1-1, FoodSales2-1 " }, { "code": null, "e": 1512, "s": 1504, "text": "Python3" }, { "code": "# importing the required modulesimport globimport pandas as pd # specifying the path to csv filespath = \"C:/downloads\" # csv files in the pathfile_list = glob.glob(path + \"/*.xlsx\") # list of excel files we want to merge.# pd.read_excel(file_path) reads the excel# data into pandas dataframe.excl_list = [] for file in file_list: excl_list.append(pd.read_excel(file)) # create a new dataframe to store the# merged excel file.excl_merged = pd.DataFrame() for excl_file in excl_list: # appends the data into the excl_merged # dataframe. excl_merged = excl_merged.append( excl_file, ignore_index=True) # exports the dataframe into excel file with# specified name.excl_merged.to_excel('total_food_sales.xlsx', index=False)", "e": 2253, "s": 1512, "text": null }, { "code": null, "e": 2262, "s": 2253, "text": "Output :" }, { "code": null, "e": 2286, "s": 2262, "text": "‘total_food_sales.xlsx’" }, { "code": null, "e": 2318, "s": 2286, "text": "Method 2: Using pandas.concat()" }, { "code": null, "e": 2553, "s": 2318, "text": "The pandas.concat() function does all the heavy lifting of performing concatenation operations along with an axis of Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes." }, { "code": null, "e": 2651, "s": 2553, "text": "Syntax: concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)" }, { "code": null, "e": 2663, "s": 2651, "text": "Parameters:" }, { "code": null, "e": 2697, "s": 2663, "text": "objs: Series or DataFrame objects" }, { "code": null, "e": 2755, "s": 2697, "text": "axis: axis to concatenate along; default = 0 //along rows" }, { "code": null, "e": 2816, "s": 2755, "text": "join: way to handle indexes on other axis; default = ‘outer’" }, { "code": null, "e": 2913, "s": 2816, "text": "ignore_index: if True, do not use the index values along the concatenation axis; default = False" }, { "code": null, "e": 2987, "s": 2913, "text": "keys: sequence to add an identifier to the result indexes; default = None" }, { "code": null, "e": 3080, "s": 2987, "text": "levels: specific levels (unique values) to use for constructing a MultiIndex; default = None" }, { "code": null, "e": 3160, "s": 3080, "text": "names: names for the levels in the resulting hierarchical index; default = None" }, { "code": null, "e": 3255, "s": 3160, "text": "verify_integrity: check whether the new concatenated axis contains duplicates; default = False" }, { "code": null, "e": 3356, "s": 3255, "text": "sort: sort non-concatenation axis if it is not already aligned when join is ‘outer’; default = False" }, { "code": null, "e": 3419, "s": 3356, "text": "copy: if False, do not copy data unnecessarily; default = True" }, { "code": null, "e": 3471, "s": 3419, "text": "Returns: a pandas dataframe with concatenated data." }, { "code": null, "e": 3480, "s": 3471, "text": "Example:" }, { "code": null, "e": 3838, "s": 3480, "text": "In the last example, we worked on only two Excel files with a few rows. Let’s try merging more files each containing approximately 5000 rows and 7 columns. We have 5 files BankE, BankD, BankC, BankB, BankA having historical stock data for respective bank. Let’s merge them into a single ‘Bank_Stocks.xlsx’ file. Here we are using the pandas.concat() method." }, { "code": null, "e": 3846, "s": 3838, "text": "Python3" }, { "code": "# importing the required modulesimport globimport pandas as pd # specifying the path to csv filespath = \"C:/downloads\" # csv files in the pathfile_list = glob.glob(path + \"/*.xlsx\") # list of excel files we want to merge.# pd.read_excel(file_path) reads the # excel data into pandas dataframe.excl_list = [] for file in file_list: excl_list.append(pd.read_excel(file)) # concatenate all DataFrames in the list# into a single DataFrame, returns new# DataFrame.excl_merged = pd.concat(excl_list, ignore_index=True) # exports the dataframe into excel file# with specified name.excl_merged.to_excel('Bank_Stocks.xlsx', index=False)", "e": 4477, "s": 3846, "text": null }, { "code": null, "e": 4486, "s": 4477, "text": "Output :" }, { "code": null, "e": 4503, "s": 4486, "text": "Bank_Stocks.xlsx" }, { "code": null, "e": 4544, "s": 4503, "text": "fgonvrz0ayd1fs840q2db5xhwsf5qnvno28cwt0m" }, { "code": null, "e": 4551, "s": 4544, "text": "Picked" }, { "code": null, "e": 4564, "s": 4551, "text": "Python-excel" }, { "code": null, "e": 4571, "s": 4564, "text": "Python" }, { "code": null, "e": 4669, "s": 4571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4687, "s": 4669, "text": "Python Dictionary" }, { "code": null, "e": 4729, "s": 4687, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4751, "s": 4729, "text": "Enumerate() in Python" }, { "code": null, "e": 4786, "s": 4751, "text": "Read a file line by line in Python" }, { "code": null, "e": 4818, "s": 4786, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4844, "s": 4818, "text": "Python String | replace()" }, { "code": null, "e": 4873, "s": 4844, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4900, "s": 4873, "text": "Python Classes and Objects" }, { "code": null, "e": 4921, "s": 4900, "text": "Python OOPs Concepts" } ]
Remove all leaf nodes from the binary search tree
16 Mar, 2022 We have given a binary search tree and we want to delete the leaf nodes from the binary search tree. Examples: Input : 20 10 5 15 30 25 35 Output : Inorder before Deleting the leaf node 5 10 15 20 25 30 35 Inorder after Deleting the leaf node 10 20 30 This is the binary search tree where we want to delete the leaf node. 20 / \ 10 30 / \ / \ 5 15 25 35 After deleting the leaf node the binary search tree looks like 20 / \ 10 30 We traverse given Binary Search Tree in inorder way. During traversal, we check if current node is leaf, if yes, we delete it. Else we recur for left and right children. An important thing to remember is, we must assign new left and right children if there is any modification in roots of subtrees. C++ Java Python3 C# Javascript // C++ program to delete leaf Node from// binary search tree.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* left; struct Node* right;}; // Create a newNode in binary search tree.struct Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Insert a Node in binary search tree.struct Node* insert(struct Node* root, int data){ if (root == NULL) return newNode(data); if (data < root->data) root->left = insert(root->left, data); else if (data > root->data) root->right = insert(root->right, data); return root;} // Function for inorder traversal in a BST.void inorder(struct Node* root){ if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); }} // Delete leaf nodes from binary search tree.struct Node* leafDelete(struct Node* root){ if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { free(root); return NULL; } // Else recursively delete in left and right // subtrees. root->left = leafDelete(root->left); root->right = leafDelete(root->right); return root;} // Driver codeint main(){ struct Node* root = NULL; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); cout << "Inorder before Deleting the leaf Node." << endl; inorder(root); cout << endl; leafDelete(root); cout << "INorder after Deleting the leaf Node." << endl; inorder(root); return 0;} // Java program to delete leaf Node from// binary search tree.class GfG { static class Node { int data; Node left; Node right; } // Create a newNode in binary search tree. static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Insert a Node in binary search tree. static Node insert(Node root, int data) { if (root == null) return newNode(data); if (data < root.data) root.left = insert(root.left, data); else if (data > root.data) root.right = insert(root.right, data); return root; } // Function for inorder traversal in a BST. static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } } // Delete leaf nodes from binary search tree. static Node leafDelete(Node root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return null; } // Else recursively delete in left and right // subtrees. root.left = leafDelete(root.left); root.right = leafDelete(root.right); return root; } // Driver code public static void main(String[] args) { Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); System.out.println("Inorder before Deleting the leaf Node. "); inorder(root); System.out.println(); leafDelete(root); System.out.println("INorder after Deleting the leaf Node. "); inorder(root); }}// This code is contributed by Prerna saini # Python 3 program to delete leaf# Node from binary search tree. # Create a newNode in binary search tree.class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Insert a Node in binary search tree.def insert(root, data): if root == None: return newNode(data) if data < root.data: root.left = insert(root.left, data) else if data > root.data: root.right = insert(root.right, data) return root # Function for inorder traversal in a BST.def inorder(root): if root != None: inorder(root.left) print(root.data, end = " ") inorder(root.right) # Delete leaf nodes from binary search tree.def leafDelete(root): if root == None: return None if root.left == None and root.right == None: return None # Else recursively delete in left # and right subtrees. root.left = leafDelete(root.left) root.right = leafDelete(root.right) return root # Driver codeif __name__ == '__main__': root = None root = insert(root, 20) insert(root, 10) insert(root, 5) insert(root, 15) insert(root, 30) insert(root, 25) insert(root, 35) print("Inorder before Deleting the leaf Node.") inorder(root) leafDelete(root) print() print("INorder after Deleting the leaf Node.") inorder(root) # This code is contributed by PranchalK // C# program to delete leaf Node from// binary search tree.using System; class GfG { class Node { public int data; public Node left; public Node right; } // Create a newNode in binary search tree. static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Insert a Node in binary search tree. static Node insert(Node root, int data) { if (root == null) return newNode(data); if (data < root.data) root.left = insert(root.left, data); else if (data > root.data) root.right = insert(root.right, data); return root; } // Function for inorder traversal in a BST. static void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(root.data + " "); inorder(root.right); } } // Delete leaf nodes from binary search tree. static Node leafDelete(Node root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return null; } // Else recursively delete in // left and right subtrees. root.left = leafDelete(root.left); root.right = leafDelete(root.right); return root; } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); Console.WriteLine("Inorder before Deleting" + "the leaf Node. "); inorder(root); Console.WriteLine(); leafDelete(root); Console.WriteLine("INorder after Deleting" + "the leaf Node. "); inorder(root); }} // This code has been contributed// by PrinciRaj1992 <script> // JavaScript program to delete leaf Node from// binary search tree.class Node { constructor() { this.data = 0; this.left = null; this.right = null; }} // Create a newNode in binary search tree. function newNode(data) { var temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Insert a Node in binary search tree. function insert(root , data) { if (root == null) return newNode(data); if (data < root.data) root.left = insert(root.left, data); else if (data > root.data) root.right = insert(root.right, data); return root; } // Function for inorder traversal in a BST. function inorder(root) { if (root != null) { inorder(root.left); document.write(root.data + " "); inorder(root.right); } } // Delete leaf nodes from binary search tree. function leafDelete(root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return null; } // Else recursively delete in left and right // subtrees. root.left = leafDelete(root.left); root.right = leafDelete(root.right); return root; } // Driver code var root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); document.write( "Inorder before Deleting the leaf Node. <br/>" ); inorder(root); document.write("<br/>"); leafDelete(root); document.write( "INorder after Deleting the leaf Node. <br/>" ); inorder(root); // This code is contributed by todaysgaurav </script> Output: Inorder before Deleting the leaf node. 5 10 15 20 25 30 35 INorder after Deleting the leaf node. 10 20 30 Remove all leaf nodes from the binary search tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersRemove all leaf nodes from the binary search tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1gW-fL6-vHE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prerna saini PranchalKatiyar princiraj1992 RajBhise Ankur_Agarwal gp6 todaysgaurav simmytarika5 Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Lowest Common Ancestor in a Binary Search Tree. Optimal Binary Search Tree | DP-24 Merge Two Balanced Binary Search Trees Convert a normal BST to Balanced BST set vs unordered_set in C++ STL Find the node with minimum value in a Binary Search Tree Find k-th smallest element in BST (Order Statistics in BST) Check if a given array can represent Preorder Traversal of Binary Search Tree
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Mar, 2022" }, { "code": null, "e": 165, "s": 52, "text": "We have given a binary search tree and we want to delete the leaf nodes from the binary search tree. Examples: " }, { "code": null, "e": 664, "s": 165, "text": "Input : 20 10 5 15 30 25 35\nOutput : Inorder before Deleting the leaf node\n 5 10 15 20 25 30 35\n Inorder after Deleting the leaf node\n 10 20 30\n\n This is the binary search tree where we\n want to delete the leaf node.\n 20\n / \\\n 10 30\n / \\ / \\\n 5 15 25 35 \n\n After deleting the leaf node the binary \n search tree looks like\n 20\n / \\\n 10 30\n " }, { "code": null, "e": 967, "s": 666, "text": "We traverse given Binary Search Tree in inorder way. During traversal, we check if current node is leaf, if yes, we delete it. Else we recur for left and right children. An important thing to remember is, we must assign new left and right children if there is any modification in roots of subtrees. " }, { "code": null, "e": 971, "s": 967, "text": "C++" }, { "code": null, "e": 976, "s": 971, "text": "Java" }, { "code": null, "e": 984, "s": 976, "text": "Python3" }, { "code": null, "e": 987, "s": 984, "text": "C#" }, { "code": null, "e": 998, "s": 987, "text": "Javascript" }, { "code": "// C++ program to delete leaf Node from// binary search tree.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* left; struct Node* right;}; // Create a newNode in binary search tree.struct Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Insert a Node in binary search tree.struct Node* insert(struct Node* root, int data){ if (root == NULL) return newNode(data); if (data < root->data) root->left = insert(root->left, data); else if (data > root->data) root->right = insert(root->right, data); return root;} // Function for inorder traversal in a BST.void inorder(struct Node* root){ if (root != NULL) { inorder(root->left); cout << root->data << \" \"; inorder(root->right); }} // Delete leaf nodes from binary search tree.struct Node* leafDelete(struct Node* root){ if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { free(root); return NULL; } // Else recursively delete in left and right // subtrees. root->left = leafDelete(root->left); root->right = leafDelete(root->right); return root;} // Driver codeint main(){ struct Node* root = NULL; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); cout << \"Inorder before Deleting the leaf Node.\" << endl; inorder(root); cout << endl; leafDelete(root); cout << \"INorder after Deleting the leaf Node.\" << endl; inorder(root); return 0;}", "e": 2671, "s": 998, "text": null }, { "code": "// Java program to delete leaf Node from// binary search tree.class GfG { static class Node { int data; Node left; Node right; } // Create a newNode in binary search tree. static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Insert a Node in binary search tree. static Node insert(Node root, int data) { if (root == null) return newNode(data); if (data < root.data) root.left = insert(root.left, data); else if (data > root.data) root.right = insert(root.right, data); return root; } // Function for inorder traversal in a BST. static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + \" \"); inorder(root.right); } } // Delete leaf nodes from binary search tree. static Node leafDelete(Node root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return null; } // Else recursively delete in left and right // subtrees. root.left = leafDelete(root.left); root.right = leafDelete(root.right); return root; } // Driver code public static void main(String[] args) { Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); System.out.println(\"Inorder before Deleting the leaf Node. \"); inorder(root); System.out.println(); leafDelete(root); System.out.println(\"INorder after Deleting the leaf Node. \"); inorder(root); }}// This code is contributed by Prerna saini", "e": 4600, "s": 2671, "text": null }, { "code": "# Python 3 program to delete leaf# Node from binary search tree. # Create a newNode in binary search tree.class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Insert a Node in binary search tree.def insert(root, data): if root == None: return newNode(data) if data < root.data: root.left = insert(root.left, data) else if data > root.data: root.right = insert(root.right, data) return root # Function for inorder traversal in a BST.def inorder(root): if root != None: inorder(root.left) print(root.data, end = \" \") inorder(root.right) # Delete leaf nodes from binary search tree.def leafDelete(root): if root == None: return None if root.left == None and root.right == None: return None # Else recursively delete in left # and right subtrees. root.left = leafDelete(root.left) root.right = leafDelete(root.right) return root # Driver codeif __name__ == '__main__': root = None root = insert(root, 20) insert(root, 10) insert(root, 5) insert(root, 15) insert(root, 30) insert(root, 25) insert(root, 35) print(\"Inorder before Deleting the leaf Node.\") inorder(root) leafDelete(root) print() print(\"INorder after Deleting the leaf Node.\") inorder(root) # This code is contributed by PranchalK", "e": 6035, "s": 4600, "text": null }, { "code": "// C# program to delete leaf Node from// binary search tree.using System; class GfG { class Node { public int data; public Node left; public Node right; } // Create a newNode in binary search tree. static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Insert a Node in binary search tree. static Node insert(Node root, int data) { if (root == null) return newNode(data); if (data < root.data) root.left = insert(root.left, data); else if (data > root.data) root.right = insert(root.right, data); return root; } // Function for inorder traversal in a BST. static void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(root.data + \" \"); inorder(root.right); } } // Delete leaf nodes from binary search tree. static Node leafDelete(Node root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return null; } // Else recursively delete in // left and right subtrees. root.left = leafDelete(root.left); root.right = leafDelete(root.right); return root; } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); Console.WriteLine(\"Inorder before Deleting\" + \"the leaf Node. \"); inorder(root); Console.WriteLine(); leafDelete(root); Console.WriteLine(\"INorder after Deleting\" + \"the leaf Node. \"); inorder(root); }} // This code has been contributed// by PrinciRaj1992", "e": 8052, "s": 6035, "text": null }, { "code": "<script> // JavaScript program to delete leaf Node from// binary search tree.class Node { constructor() { this.data = 0; this.left = null; this.right = null; }} // Create a newNode in binary search tree. function newNode(data) { var temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Insert a Node in binary search tree. function insert(root , data) { if (root == null) return newNode(data); if (data < root.data) root.left = insert(root.left, data); else if (data > root.data) root.right = insert(root.right, data); return root; } // Function for inorder traversal in a BST. function inorder(root) { if (root != null) { inorder(root.left); document.write(root.data + \" \"); inorder(root.right); } } // Delete leaf nodes from binary search tree. function leafDelete(root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return null; } // Else recursively delete in left and right // subtrees. root.left = leafDelete(root.left); root.right = leafDelete(root.right); return root; } // Driver code var root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); document.write( \"Inorder before Deleting the leaf Node. <br/>\" ); inorder(root); document.write(\"<br/>\"); leafDelete(root); document.write( \"INorder after Deleting the leaf Node. <br/>\" ); inorder(root); // This code is contributed by todaysgaurav </script>", "e": 9962, "s": 8052, "text": null }, { "code": null, "e": 9972, "s": 9962, "text": "Output: " }, { "code": null, "e": 10078, "s": 9972, "text": "Inorder before Deleting the leaf node.\n5 10 15 20 25 30 35\nINorder after Deleting the leaf node.\n10 20 30" }, { "code": null, "e": 10994, "s": 10078, "text": "Remove all leaf nodes from the binary search tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersRemove all leaf nodes from the binary search tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=1gW-fL6-vHE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 11003, "s": 10994, "text": "Chapters" }, { "code": null, "e": 11030, "s": 11003, "text": "descriptions off, selected" }, { "code": null, "e": 11080, "s": 11030, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 11103, "s": 11080, "text": "captions off, selected" }, { "code": null, "e": 11111, "s": 11103, "text": "English" }, { "code": null, "e": 11135, "s": 11111, "text": "This is a modal window." }, { "code": null, "e": 11204, "s": 11135, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 11226, "s": 11204, "text": "End of dialog window." }, { "code": null, "e": 11268, "s": 11226, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk " }, { "code": null, "e": 11693, "s": 11268, "text": "This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11708, "s": 11695, "text": "prerna saini" }, { "code": null, "e": 11724, "s": 11708, "text": "PranchalKatiyar" }, { "code": null, "e": 11738, "s": 11724, "text": "princiraj1992" }, { "code": null, "e": 11747, "s": 11738, "text": "RajBhise" }, { "code": null, "e": 11761, "s": 11747, "text": "Ankur_Agarwal" }, { "code": null, "e": 11765, "s": 11761, "text": "gp6" }, { "code": null, "e": 11778, "s": 11765, "text": "todaysgaurav" }, { "code": null, "e": 11791, "s": 11778, "text": "simmytarika5" }, { "code": null, "e": 11810, "s": 11791, "text": "Binary Search Tree" }, { "code": null, "e": 11829, "s": 11810, "text": "Binary Search Tree" }, { "code": null, "e": 11927, "s": 11829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11983, "s": 11927, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 12053, "s": 11983, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 12101, "s": 12053, "text": "Lowest Common Ancestor in a Binary Search Tree." }, { "code": null, "e": 12136, "s": 12101, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 12175, "s": 12136, "text": "Merge Two Balanced Binary Search Trees" }, { "code": null, "e": 12212, "s": 12175, "text": "Convert a normal BST to Balanced BST" }, { "code": null, "e": 12244, "s": 12212, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 12301, "s": 12244, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 12361, "s": 12301, "text": "Find k-th smallest element in BST (Order Statistics in BST)" } ]
Python: Inplace Editing using FileInput
19 Feb, 2020 Python3’s fileinput provides many useful features that can be used to do many things without lots of code. It comes handy in many places but in this article, we’ll use the fileinput to do in-place editing in a text file. Basically we’ll be changing the text in a text file without creating any other file or overheads. Syntax: FileInput(filename, inplace=True, backup='.bak') Note: The backup is extension for the backup file created before editing. Example 1:Changing only the first line of file Text file: # Python code to change only first line of fileimport fileinput filename = "GFG.txt" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if f.isfirstline(): print("changing only first line", end ='\n') else: print(line, end ='') Output: Example 2:Search and replace line with other line in file Text file: # python3 code to search and # replace line with other line in fileimport fileinput filename = "GFG.txt" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if "search this line and change it\n" == line: print("changing the matched line with this line", end ='\n') else: print(line, end ='') Output: Example 3:Search text inline and replace that line with another line in the file. Text file: # python3 code to search text in # line and replace that line with # other line in fileimport fileinput filename = "GFG.txt" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if "searchtext" in line: print("changing this line with line that contains searched text", end ='\n') else: print(line, end ='') Output: Example 4:Search text and replace that text in file. Text file: # python code to search# text and replace that text# in file import fileinput filename = "GFG.txt" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if "replace text" in line: print(line.replace("replace text", "changed text"), end ='') else: print(line, end ='') Output: python-file-handling python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2020" }, { "code": null, "e": 347, "s": 28, "text": "Python3’s fileinput provides many useful features that can be used to do many things without lots of code. It comes handy in many places but in this article, we’ll use the fileinput to do in-place editing in a text file. Basically we’ll be changing the text in a text file without creating any other file or overheads." }, { "code": null, "e": 355, "s": 347, "text": "Syntax:" }, { "code": null, "e": 405, "s": 355, "text": "FileInput(filename, inplace=True, backup='.bak')\n" }, { "code": null, "e": 479, "s": 405, "text": "Note: The backup is extension for the backup file created before editing." }, { "code": null, "e": 526, "s": 479, "text": "Example 1:Changing only the first line of file" }, { "code": null, "e": 537, "s": 526, "text": "Text file:" }, { "code": "# Python code to change only first line of fileimport fileinput filename = \"GFG.txt\" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if f.isfirstline(): print(\"changing only first line\", end ='\\n') else: print(line, end ='')", "e": 870, "s": 537, "text": null }, { "code": null, "e": 878, "s": 870, "text": "Output:" }, { "code": null, "e": 936, "s": 878, "text": "Example 2:Search and replace line with other line in file" }, { "code": null, "e": 947, "s": 936, "text": "Text file:" }, { "code": "# python3 code to search and # replace line with other line in fileimport fileinput filename = \"GFG.txt\" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if \"search this line and change it\\n\" == line: print(\"changing the matched line with this line\", end ='\\n') else: print(line, end ='')", "e": 1363, "s": 947, "text": null }, { "code": null, "e": 1371, "s": 1363, "text": "Output:" }, { "code": null, "e": 1453, "s": 1371, "text": "Example 3:Search text inline and replace that line with another line in the file." }, { "code": null, "e": 1464, "s": 1453, "text": "Text file:" }, { "code": "# python3 code to search text in # line and replace that line with # other line in fileimport fileinput filename = \"GFG.txt\" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if \"searchtext\" in line: print(\"changing this line with line that contains searched text\", end ='\\n') else: print(line, end ='')", "e": 1888, "s": 1464, "text": null }, { "code": null, "e": 1896, "s": 1888, "text": "Output:" }, { "code": null, "e": 1949, "s": 1896, "text": "Example 4:Search text and replace that text in file." }, { "code": null, "e": 1960, "s": 1949, "text": "Text file:" }, { "code": "# python code to search# text and replace that text# in file import fileinput filename = \"GFG.txt\" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if \"replace text\" in line: print(line.replace(\"replace text\", \"changed text\"), end ='') else: print(line, end ='')", "e": 2365, "s": 1960, "text": null }, { "code": null, "e": 2373, "s": 2365, "text": "Output:" }, { "code": null, "e": 2394, "s": 2373, "text": "python-file-handling" }, { "code": null, "e": 2409, "s": 2394, "text": "python-modules" }, { "code": null, "e": 2416, "s": 2409, "text": "Python" } ]
JavaScript - The Arrays Object
The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Use the following syntax to create an Array object − var fruits = new Array( "apple", "orange", "mango" ); The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295. You can create array by simply assigning values as follows − var fruits = [ "apple", "orange", "mango" ]; You will use ordinal numbers to access and to set values inside an array as follows. fruits[0] is the first element fruits[1] is the second element fruits[2] is the third element Here is a list of the properties of the Array object along with their description. Returns a reference to the array function that created the object. index The property represents the zero-based index of the match in the string input This property is only present in arrays created by regular expression matches. Reflects the number of elements in an array. The prototype property allows you to add properties and methods to an object. In the following sections, we will have a few examples to illustrate the usage of Array properties. Here is a list of the methods of the Array object along with their description. Returns a new array comprised of this array joined with other array(s) and/or value(s). Returns true if every element in this array satisfies the provided testing function. Creates a new array with all of the elements of this array for which the provided filtering function returns true. Calls a function for each element in the array. Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. Joins all elements of an array into a string. Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. Creates a new array with the results of calling a provided function on every element in this array. Removes the last element from an array and returns that element. Adds one or more elements to the end of an array and returns the new length of the array. Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value. Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. Removes the first element from an array and returns that element. Extracts a section of an array and returns a new array. Returns true if at least one element in this array satisfies the provided testing function. Represents the source code of an object Sorts the elements of an array Adds and/or removes elements from an array. Returns a string representing the array and its elements. Adds one or more elements to the front of an array and returns the new length of the array. In the following sections, we will have a few examples to demonstrate the usage of Array methods. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2755, "s": 2466, "text": "The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." }, { "code": null, "e": 2808, "s": 2755, "text": "Use the following syntax to create an Array object −" }, { "code": null, "e": 2863, "s": 2808, "text": "var fruits = new Array( \"apple\", \"orange\", \"mango\" );\n" }, { "code": null, "e": 3092, "s": 2863, "text": "The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295." }, { "code": null, "e": 3153, "s": 3092, "text": "You can create array by simply assigning values as follows −" }, { "code": null, "e": 3198, "s": 3153, "text": "var fruits = [ \"apple\", \"orange\", \"mango\" ];" }, { "code": null, "e": 3283, "s": 3198, "text": "You will use ordinal numbers to access and to set values inside an array as follows." }, { "code": null, "e": 3378, "s": 3283, "text": "fruits[0] is the first element\nfruits[1] is the second element\nfruits[2] is the third element\n" }, { "code": null, "e": 3461, "s": 3378, "text": "Here is a list of the properties of the Array object along with their description." }, { "code": null, "e": 3528, "s": 3461, "text": "Returns a reference to the array function that created the object." }, { "code": null, "e": 3534, "s": 3528, "text": "index" }, { "code": null, "e": 3606, "s": 3534, "text": "The property represents the zero-based index of the match in the string" }, { "code": null, "e": 3612, "s": 3606, "text": "input" }, { "code": null, "e": 3691, "s": 3612, "text": "This property is only present in arrays created by regular expression matches." }, { "code": null, "e": 3736, "s": 3691, "text": "Reflects the number of elements in an array." }, { "code": null, "e": 3814, "s": 3736, "text": "The prototype property allows you to add properties and methods to an object." }, { "code": null, "e": 3914, "s": 3814, "text": "In the following sections, we will have a few examples to illustrate the usage of Array properties." }, { "code": null, "e": 3994, "s": 3914, "text": "Here is a list of the methods of the Array object along with their description." }, { "code": null, "e": 4082, "s": 3994, "text": "Returns a new array comprised of this array joined with other array(s) and/or value(s)." }, { "code": null, "e": 4167, "s": 4082, "text": "Returns true if every element in this array satisfies the provided testing function." }, { "code": null, "e": 4282, "s": 4167, "text": "Creates a new array with all of the elements of this array for which the provided filtering function returns true." }, { "code": null, "e": 4330, "s": 4282, "text": "Calls a function for each element in the array." }, { "code": null, "e": 4447, "s": 4330, "text": "Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found." }, { "code": null, "e": 4493, "s": 4447, "text": "Joins all elements of an array into a string." }, { "code": null, "e": 4612, "s": 4493, "text": "Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found." }, { "code": null, "e": 4712, "s": 4612, "text": "Creates a new array with the results of calling a provided function on every element in this array." }, { "code": null, "e": 4777, "s": 4712, "text": "Removes the last element from an array and returns that element." }, { "code": null, "e": 4867, "s": 4777, "text": "Adds one or more elements to the end of an array and returns the new length of the array." }, { "code": null, "e": 4987, "s": 4867, "text": "Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value." }, { "code": null, "e": 5107, "s": 4987, "text": "Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value." }, { "code": null, "e": 5217, "s": 5107, "text": "Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first." }, { "code": null, "e": 5283, "s": 5217, "text": "Removes the first element from an array and returns that element." }, { "code": null, "e": 5339, "s": 5283, "text": "Extracts a section of an array and returns a new array." }, { "code": null, "e": 5431, "s": 5339, "text": "Returns true if at least one element in this array satisfies the provided testing function." }, { "code": null, "e": 5471, "s": 5431, "text": "Represents the source code of an object" }, { "code": null, "e": 5502, "s": 5471, "text": "Sorts the elements of an array" }, { "code": null, "e": 5546, "s": 5502, "text": "Adds and/or removes elements from an array." }, { "code": null, "e": 5604, "s": 5546, "text": "Returns a string representing the array and its elements." }, { "code": null, "e": 5696, "s": 5604, "text": "Adds one or more elements to the front of an array and returns the new length of the array." }, { "code": null, "e": 5794, "s": 5696, "text": "In the following sections, we will have a few examples to demonstrate the usage of Array methods." }, { "code": null, "e": 5829, "s": 5794, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5843, "s": 5829, "text": " Anadi Sharma" }, { "code": null, "e": 5877, "s": 5843, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 5891, "s": 5877, "text": " Lets Kode It" }, { "code": null, "e": 5926, "s": 5891, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5943, "s": 5926, "text": " Frahaan Hussain" }, { "code": null, "e": 5978, "s": 5943, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5995, "s": 5978, "text": " Frahaan Hussain" }, { "code": null, "e": 6028, "s": 5995, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 6056, "s": 6028, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6090, "s": 6056, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 6118, "s": 6090, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6125, "s": 6118, "text": " Print" }, { "code": null, "e": 6136, "s": 6125, "text": " Add Notes" } ]
Accessing Census Data with Python | by Jackson Gilkey | Towards Data Science
With the 2020 Census already underway and the coming redistricting accessing and understanding public Census data is more relevant than ever. This post will guide you through getting your hands on the data using a Python package called CensusData to import the data into Pandas There are 5 data sets available through CensusData including the classic Decennial Census as well as 4 different American Community Survey (ACS) estimates. The ACS started in 2005 and replaced the long form Census that used to be sent every ten years to a subset of households along with the traditional Census. Instead, the ACS is conducted on a rolling basis and sent to roughly 3.5 million households each month. This subset is then used to create estimates of the entire population. The questions on the ACS are also more in-depth and include topics like education, employment and internet access. ACS 1-year estimates (2012–2018) For areas with populations 65,000+, most frequently updated but with the lowest “resolution” since it excludes areas with low population and has the smallest sample size ACS 1-year supplemental estimates (2014–2017) Supplemental dataset that focuses on lower population areas of 20,000+ ACS 3-year estimates (2010–2012 to 2011–2013) For areas with populations 20,000+, very much the middle ground between the 1 and 5 years. Currently discounted by the Census Bureau but old versions can still be accessed. ACS 5-year estimates (2005–2009 to 2014–2018) Data for all areas, highest resolution and largest sample size but the least current Census 2010 Summary File 1 Counts every resident of the US, updated every 10 years. Estimates that span multiple years are aggregates You should never compare estimates from overlapping ranges, for instance comparing ACS 3-year 2010–2012 to 2011–2013 Installing is easily done using pip through your terminal. pip install censusdata Now you can either look up the exact table you’re interested in using documentation on the census site, for instance here for the ACS. Or you can use the search method of CensusData import pandas as pdimport censusdatasample = censusdata.search('acs5', 2015,'concept', 'transportation') Here are the details of the Search Parameters taken from the documentation: src (str) — Census data source: ‘acs1’ for ACS 1-year estimates, ‘acs5’ for ACS 5-year estimates, ‘acs3’ for ACS 3-year estimates, ‘acsse’ for ACS 1-year supplemental estimates, ‘sf1’ for SF1 data. year (int) — Year of data. field (str) — Field in which to search. criterion (str) — Search criterion. tabletype (str, optional) — Type of table from which variables are drawn (only applicable to ACS data). Options are ‘detail’ (detail tables), ‘subject’ (subject tables), ‘profile’ (data profile tables), ‘cprofile’ (comparison profile tables). So in the above search query, we’re looking for 5 year ACS estimates from 2015 with ‘transportation’ in the concept. Now this search will return a list of 3 tuples containing variable names, concepts, and labels matching the search criterion. This list can be quite large. print(len(sample))>>>3630 Let’s examine two of the first tuples in detail to understand what they’re telling us. print(sample[0])>>>('B08006_001E', 'B08006. Sex of Workers by Means of Transportation to Work', 'Total:')print(sample[2])>>>('B08006_002E', 'B08006. Sex of Workers by Means of Transportation to Work', 'Car, truck, or van:') The first element is the Variable Name and contains two elements, the parent table and the sub table designation. Both entries share the same parent table ‘B08006’ which corresponds to the second element the Concept, ‘B08006. Sex of Workers by Means of Transportation to Work’. The final element is the label which corresponds to their subtable. Once you know the parent table you’re interested in you can use the print table command to get a clean readout of all of the subtables. censusdata.printtable(censusdata.censustable('acs5', 2015, 'B23025')) The final piece you’ll need in order to download some Census data is the geography codes of the region you’re interested in. We can use the geographies method in order to explore this information. states = censusdata.geographies(censusdata.censusgeo([('state', '*')]), 'acs5', 2015) This query will return a dictionary object where each key is the name of a state. Below is a sample of the first two elements. {'Alabama': censusgeo((('state', '01'),)), 'Alaska': censusgeo((('state', '02'),))} So in order to find the code for New York, we would need to print the corresponding value. print(states['New York']>>>Summary level: 040, state:36 We’re interested in the second value, 36, which can then be used to get all the county codes for that state. counties = censusdata.geographies(censusdata.censusgeo([('state', '36'), ('county', '*')]), 'acs5', 2015)print(counties)>>>Summary level: 040, state:36{'Queens County, New York': censusgeo((('state', '36'), ('county', '081'))), 'Rensselaer County, New York': censusgeo((('state', '36'), ('county', '083'))),'Richmond County, New York': censusgeo((('state', '36'), ('county', '085'))),...} Now we have everything we’ll need to download our first set of Census data! data = censusdata.download('acs5', 2015, censusdata.censusgeo([('state', '36'), ('county', '081'), ('block group', '*')]), ['B23025_001E', 'B23025_002E', 'B23025_003E', 'B23025_004E', 'B23025_005E', 'B23025_006E', 'B23025_007E']) That query will store the requested data as a Pandas dataframe that can be accessed using standard Pandas methods. print(data.head) Congratulations! You’ve officially accessed the public US Census Data.
[ { "code": null, "e": 450, "s": 172, "text": "With the 2020 Census already underway and the coming redistricting accessing and understanding public Census data is more relevant than ever. This post will guide you through getting your hands on the data using a Python package called CensusData to import the data into Pandas" }, { "code": null, "e": 606, "s": 450, "text": "There are 5 data sets available through CensusData including the classic Decennial Census as well as 4 different American Community Survey (ACS) estimates." }, { "code": null, "e": 1052, "s": 606, "text": "The ACS started in 2005 and replaced the long form Census that used to be sent every ten years to a subset of households along with the traditional Census. Instead, the ACS is conducted on a rolling basis and sent to roughly 3.5 million households each month. This subset is then used to create estimates of the entire population. The questions on the ACS are also more in-depth and include topics like education, employment and internet access." }, { "code": null, "e": 1255, "s": 1052, "text": "ACS 1-year estimates (2012–2018) For areas with populations 65,000+, most frequently updated but with the lowest “resolution” since it excludes areas with low population and has the smallest sample size" }, { "code": null, "e": 1372, "s": 1255, "text": "ACS 1-year supplemental estimates (2014–2017) Supplemental dataset that focuses on lower population areas of 20,000+" }, { "code": null, "e": 1591, "s": 1372, "text": "ACS 3-year estimates (2010–2012 to 2011–2013) For areas with populations 20,000+, very much the middle ground between the 1 and 5 years. Currently discounted by the Census Bureau but old versions can still be accessed." }, { "code": null, "e": 1722, "s": 1591, "text": "ACS 5-year estimates (2005–2009 to 2014–2018) Data for all areas, highest resolution and largest sample size but the least current" }, { "code": null, "e": 1806, "s": 1722, "text": "Census 2010 Summary File 1 Counts every resident of the US, updated every 10 years." }, { "code": null, "e": 1856, "s": 1806, "text": "Estimates that span multiple years are aggregates" }, { "code": null, "e": 1973, "s": 1856, "text": "You should never compare estimates from overlapping ranges, for instance comparing ACS 3-year 2010–2012 to 2011–2013" }, { "code": null, "e": 2032, "s": 1973, "text": "Installing is easily done using pip through your terminal." }, { "code": null, "e": 2055, "s": 2032, "text": "pip install censusdata" }, { "code": null, "e": 2237, "s": 2055, "text": "Now you can either look up the exact table you’re interested in using documentation on the census site, for instance here for the ACS. Or you can use the search method of CensusData" }, { "code": null, "e": 2342, "s": 2237, "text": "import pandas as pdimport censusdatasample = censusdata.search('acs5', 2015,'concept', 'transportation')" }, { "code": null, "e": 2418, "s": 2342, "text": "Here are the details of the Search Parameters taken from the documentation:" }, { "code": null, "e": 2616, "s": 2418, "text": "src (str) — Census data source: ‘acs1’ for ACS 1-year estimates, ‘acs5’ for ACS 5-year estimates, ‘acs3’ for ACS 3-year estimates, ‘acsse’ for ACS 1-year supplemental estimates, ‘sf1’ for SF1 data." }, { "code": null, "e": 2643, "s": 2616, "text": "year (int) — Year of data." }, { "code": null, "e": 2683, "s": 2643, "text": "field (str) — Field in which to search." }, { "code": null, "e": 2719, "s": 2683, "text": "criterion (str) — Search criterion." }, { "code": null, "e": 2962, "s": 2719, "text": "tabletype (str, optional) — Type of table from which variables are drawn (only applicable to ACS data). Options are ‘detail’ (detail tables), ‘subject’ (subject tables), ‘profile’ (data profile tables), ‘cprofile’ (comparison profile tables)." }, { "code": null, "e": 3235, "s": 2962, "text": "So in the above search query, we’re looking for 5 year ACS estimates from 2015 with ‘transportation’ in the concept. Now this search will return a list of 3 tuples containing variable names, concepts, and labels matching the search criterion. This list can be quite large." }, { "code": null, "e": 3261, "s": 3235, "text": "print(len(sample))>>>3630" }, { "code": null, "e": 3348, "s": 3261, "text": "Let’s examine two of the first tuples in detail to understand what they’re telling us." }, { "code": null, "e": 3574, "s": 3348, "text": "print(sample[0])>>>('B08006_001E', 'B08006. Sex of Workers by Means of Transportation to Work', 'Total:')print(sample[2])>>>('B08006_002E', 'B08006. Sex of Workers by Means of Transportation to Work', 'Car, truck, or van:')" }, { "code": null, "e": 3920, "s": 3574, "text": "The first element is the Variable Name and contains two elements, the parent table and the sub table designation. Both entries share the same parent table ‘B08006’ which corresponds to the second element the Concept, ‘B08006. Sex of Workers by Means of Transportation to Work’. The final element is the label which corresponds to their subtable." }, { "code": null, "e": 4056, "s": 3920, "text": "Once you know the parent table you’re interested in you can use the print table command to get a clean readout of all of the subtables." }, { "code": null, "e": 4126, "s": 4056, "text": "censusdata.printtable(censusdata.censustable('acs5', 2015, 'B23025'))" }, { "code": null, "e": 4323, "s": 4126, "text": "The final piece you’ll need in order to download some Census data is the geography codes of the region you’re interested in. We can use the geographies method in order to explore this information." }, { "code": null, "e": 4409, "s": 4323, "text": "states = censusdata.geographies(censusdata.censusgeo([('state', '*')]), 'acs5', 2015)" }, { "code": null, "e": 4536, "s": 4409, "text": "This query will return a dictionary object where each key is the name of a state. Below is a sample of the first two elements." }, { "code": null, "e": 4620, "s": 4536, "text": "{'Alabama': censusgeo((('state', '01'),)), 'Alaska': censusgeo((('state', '02'),))}" }, { "code": null, "e": 4711, "s": 4620, "text": "So in order to find the code for New York, we would need to print the corresponding value." }, { "code": null, "e": 4767, "s": 4711, "text": "print(states['New York']>>>Summary level: 040, state:36" }, { "code": null, "e": 4876, "s": 4767, "text": "We’re interested in the second value, 36, which can then be used to get all the county codes for that state." }, { "code": null, "e": 5289, "s": 4876, "text": "counties = censusdata.geographies(censusdata.censusgeo([('state', '36'), ('county', '*')]), 'acs5', 2015)print(counties)>>>Summary level: 040, state:36{'Queens County, New York': censusgeo((('state', '36'), ('county', '081'))), 'Rensselaer County, New York': censusgeo((('state', '36'), ('county', '083'))),'Richmond County, New York': censusgeo((('state', '36'), ('county', '085'))),...}" }, { "code": null, "e": 5365, "s": 5289, "text": "Now we have everything we’ll need to download our first set of Census data!" }, { "code": null, "e": 5698, "s": 5365, "text": "data = censusdata.download('acs5', 2015, censusdata.censusgeo([('state', '36'), ('county', '081'), ('block group', '*')]), ['B23025_001E', 'B23025_002E', 'B23025_003E', 'B23025_004E', 'B23025_005E', 'B23025_006E', 'B23025_007E'])" }, { "code": null, "e": 5813, "s": 5698, "text": "That query will store the requested data as a Pandas dataframe that can be accessed using standard Pandas methods." }, { "code": null, "e": 5830, "s": 5813, "text": "print(data.head)" } ]